<commit_before>// Most of this code was taken from @satya164's babel-plugin-css-prop
// @see https://github.com/satya164/babel-plugin-css-prop
import { useCssProp } from '../utils/options'

const getName = (node, t) => {
  if (typeof node.name === 'string') return node.name
  if (t.isJSXMemberExpression(node)) {
    return `${getName(node.object, t)}.${node.property.name}`
  }
  throw path.buildCodeFrameError(
    `Cannot infer name from node with type "${
      node.type
    }". Please submit an issue at github.com/styled-components/babel-plugin-styled-components with your code so we can take a look at your use case!`
  )
}

export default t => (path, state) => {
  if (!useCssProp(state)) return
  if (path.node.name.name !== 'css') return

  const program = state.file.path
  const importName =
    state.customImportName || program.scope.generateUidIdentifier('styled')
  if (!state.customImportName) state.customImportName = importName
  // Insert require('styled-components') if it doesn't exist yet
  const { bindings } = program.scope
  if (!state.required) {
    if (!bindings[importName]) {
      program.node.body.push(
        t.variableDeclaration('var', [
          t.variableDeclarator(
            importName,
            t.memberExpression(
              t.callExpression(t.identifier('require'), [
                t.stringLiteral('styled-components'),
              ]),
              t.identifier('default')
            )
          ),
        ])
      )
    }
    state.required = true
  }

  const elem = path.parentPath
  const name = getName(elem.node.name, t)
  const id = path.scope.generateUidIdentifier(
    'Styled' + name.replace(/^([a-z])/, (match, p1) => p1.toUpperCase())
  )

  const styled = t.callExpression(importName, [
    /^[a-z]/.test(name) ? t.stringLiteral(name) : t.identifier(name),
  ])

  let css

  if (t.isStringLiteral(path.node.value)) {
    css = t.templateLiteral(
      [
        t.templateElement(
          { raw: path.node.value.value, cooked: path.node.value.value },
          true
        ),
      ],
      []
    )
  } else if (t.isJSXExpressionContainer(path.node.value)) {
    if (t.isTemplateLiteral(path.node.value.expression)) {
      css = path.node.value.expression
    } else if (
      t.isTaggedTemplateExpression(path.node.value.expression) &&
      path.node.value.expression.tag.name === 'css'
    ) {
      css = path.node.value.expression.quasi
    } else {
      css = t.templateLiteral(
        [
          t.templateElement({ raw: '', cooked: '' }, false),
          t.templateElement({ raw: '', cooked: '' }, true),
        ],
        [path.node.value.expression]
      )
    }
  }

  if (!css) return

  elem.node.attributes = elem.node.attributes.filter(attr => attr !== path.node)
  elem.node.name = t.jSXIdentifier(id.name)

  if (elem.parentPath.node.closingElement) {
    elem.parentPath.node.closingElement.name = t.jSXIdentifier(id.name)
  }

  css.expressions = css.expressions.reduce((acc, ex) => {
    if (
      Object.entries(bindings).some(([, b] /*: any */) =>
        b.referencePaths.find(p => p.node === ex)
      ) ||
      t.isFunctionExpression(ex) ||
      t.isArrowFunctionExpression(ex)
    ) {
      acc.push(ex)
    } else {
      const name = path.scope.generateUidIdentifier('css')
      const p = t.identifier('p')

      elem.node.attributes.push(
        t.jSXAttribute(t.jSXIdentifier(name.name), t.jSXExpressionContainer(ex))
      )

      acc.push(t.arrowFunctionExpression([p], t.memberExpression(p, name)))
    }

    return acc
  }, [])

  // Add the tagged template expression and then requeue the newly added node
  // so Babel runs over it again
  program.node.body.push(
    t.variableDeclaration('var', [
      t.variableDeclarator(id, t.taggedTemplateExpression(styled, css)),
    ])
  )
  program.requeue(program.get('body')[program.get('body').length - 1])
}
<commit_msg>Code cleanup<commit_after>// Most of this code was taken from @satya164's babel-plugin-css-prop
// @see https://github.com/satya164/babel-plugin-css-prop
import { useCssProp } from '../utils/options'

const getName = (node, t) => {
  if (typeof node.name === 'string') return node.name
  if (t.isJSXMemberExpression(node)) {
    return `${getName(node.object, t)}.${node.property.name}`
  }
  throw path.buildCodeFrameError(
    `Cannot infer name from node with type "${
      node.type
    }". Please submit an issue at github.com/styled-components/babel-plugin-styled-components with your code so we can take a look at your use case!`
  )
}

export default t => (path, state) => {
  if (!useCssProp(state)) return
  if (path.node.name.name !== 'css') return

  const program = state.file.path
  const importName =
    state.customImportName || program.scope.generateUidIdentifier('styled')
  if (!state.customImportName) state.customImportName = importName
  // Insert require('styled-components') if it doesn't exist yet
  const { bindings } = program.scope
  if (!state.required) {
    if (!bindings[importName]) {
      program.node.body.push(
        t.variableDeclaration('var', [
          t.variableDeclarator(
            importName,
            t.memberExpression(
              t.callExpression(t.identifier('require'), [
                t.stringLiteral('styled-components'),
              ]),
              t.identifier('default')
            )
          ),
        ])
      )
    }
    state.required = true
  }

  const elem = path.parentPath
  const name = getName(elem.node.name, t)
  const id = path.scope.generateUidIdentifier(
    'Styled' + name.replace(/^([a-z])/, (match, p1) => p1.toUpperCase())
  )

  const styled = t.callExpression(importName, [
    /^[a-z]/.test(name) ? t.stringLiteral(name) : t.identifier(name),
  ])

  let css

  if (t.isStringLiteral(path.node.value)) {
    css = t.templateLiteral(
      [
        t.templateElement(
          { raw: path.node.value.value, cooked: path.node.value.value },
          true
        ),
      ],
      []
    )
  } else if (t.isJSXExpressionContainer(path.node.value)) {
    if (t.isTemplateLiteral(path.node.value.expression)) {
      css = path.node.value.expression
    } else if (
      t.isTaggedTemplateExpression(path.node.value.expression) &&
      path.node.value.expression.tag.name === 'css'
    ) {
      css = path.node.value.expression.quasi
    } else {
      css = t.templateLiteral(
        [
          t.templateElement({ raw: '', cooked: '' }, false),
          t.templateElement({ raw: '', cooked: '' }, true),
        ],
        [path.node.value.expression]
      )
    }
  }

  if (!css) return

  elem.node.attributes = elem.node.attributes.filter(attr => attr !== path.node)
  elem.node.name = t.jSXIdentifier(id.name)

  if (elem.parentPath.node.closingElement) {
    elem.parentPath.node.closingElement.name = t.jSXIdentifier(id.name)
  }

  css.expressions = css.expressions.reduce((acc, ex) => {
    if (
      Object.entries(bindings).some(([, b] /*: any */) =>
        b.referencePaths.find(p => p.node === ex)
      ) ||
      t.isFunctionExpression(ex) ||
      t.isArrowFunctionExpression(ex)
    ) {
      acc.push(ex)
    } else {
      const name = path.scope.generateUidIdentifier('css')
      const p = t.identifier('p')

      elem.node.attributes.push(
        t.jSXAttribute(t.jSXIdentifier(name.name), t.jSXExpressionContainer(ex))
      )

      acc.push(t.arrowFunctionExpression([p], t.memberExpression(p, name)))
    }

    return acc
  }, [])

  // Add the tagged template expression and then requeue the newly added node
  // so Babel runs over it again
  const length = program.node.body.push(
    t.variableDeclaration('var', [
      t.variableDeclarator(id, t.taggedTemplateExpression(styled, css)),
    ])
  )

  program.requeue(program.get('body')[length - 1])
}
<|endoftext|>


<commit_before>moduleAid.VERSION = '2.0.0';
moduleAid.LAZY = true;

// modifyFunction(aOriginal, aArray) - allows me to modify a function quickly from within my scripts
//	aOriginal - (function) function to be modified
//	aArray - (array) [ [original, new] x n ], where new replaces original in the modified function
// Note to self, by using the Function() method to create functions I'm priving them from their original context,
// that is, while inside a function created by that method in a module loaded by moduleAid I can't call 'subObj' (as in 'mainObj.subObj') by itself as I normally do,
// I have to either use 'mainObj.subObj' or 'this.subObj'; I try to avoid this as that is how I'm building my modularized add-ons,
// so I'm using eval, at least for now until I find a better way to implement this functionality.
// Don't forget that in bootstraped add-ons, these modified functions take the context of the modifier (sandboxed).
this.modifyFunction = function(aOriginal, aArray) {
	var newCode = aOriginal.toString();
	for(var i=0; i < aArray.length; i++) {
		newCode = newCode.replace(aArray[i][0], aArray[i][1].replace("{([objName])}", objName));
	}

	try {
		eval('var ret = ' + newCode + ';');
		return ret;
	}
	catch(ex) {
		Cu.reportError(ex);
		return null;
	}
};

// aSync(aFunc, aDelay) - lets me run aFunc asynchronously, basically it's a one shot timer with a delay of aDelay msec
//	aFunc - (function) to be called asynchronously
//	(optional) aDelay - (int) msec to set the timer, defaults to 0msec
this.aSync = function(aFunc, aDelay) {
	return timerAid.create(aFunc, (!aDelay) ? 0 : aDelay);
}
<commit_msg>missed the final closing argument<commit_after>moduleAid.VERSION = '2.0.1';
moduleAid.LAZY = true;

// modifyFunction(aOriginal, aArray) - allows me to modify a function quickly from within my scripts
//	aOriginal - (function) function to be modified
//	aArray - (array) [ [original, new] x n ], where new replaces original in the modified function
// Note to self, by using the Function() method to create functions I'm priving them from their original context,
// that is, while inside a function created by that method in a module loaded by moduleAid I can't call 'subObj' (as in 'mainObj.subObj') by itself as I normally do,
// I have to either use 'mainObj.subObj' or 'this.subObj'; I try to avoid this as that is how I'm building my modularized add-ons,
// so I'm using eval, at least for now until I find a better way to implement this functionality.
// Don't forget that in bootstraped add-ons, these modified functions take the context of the modifier (sandboxed).
this.modifyFunction = function(aOriginal, aArray) {
	var newCode = aOriginal.toString();
	for(var i=0; i < aArray.length; i++) {
		newCode = newCode.replace(aArray[i][0], aArray[i][1].replace("{([objName])}", objName));
	}

	try {
		eval('var ret = ' + newCode + ';');
		return ret;
	}
	catch(ex) {
		Cu.reportError(ex);
		return null;
	}
};

// aSync(aFunc, aDelay) - lets me run aFunc asynchronously, basically it's a one shot timer with a delay of aDelay msec
//	aFunc - (function) to be called asynchronously
//	(optional) aDelay - (int) msec to set the timer, defaults to 0msec
this.aSync = function(aFunc, aDelay) {
	return timerAid.create(aFunc, (!aDelay) ? 0 : aDelay);
};
<|endoftext|>


<commit_before>import Config from 'classes/Config';

/* global self, console */
/* eslint-disable no-console */

let winObj;

// window object exists
if(typeof self === 'object' && self.self === self) {
	winObj = self;
}
// fake our window object for testing/SSR
else {
	winObj = {};
	winObj.self = winObj;
	winObj.top = winObj;
}

export const win = winObj;

export const isIframe = win.self !== win.top;

export const debug = (output) => {
	if(!Config.get('debug', false)) {
		return;
	}

	console.info(output);
};
<commit_msg>Update helper class, to add uuid, shared definition class and other minor changes.<commit_after>import Config from 'classes/Config';
import DefinitionClass from 'classes/Definition';

/* global self, console */
/* eslint-disable no-console */

let winObj;

// window object exists
if(typeof self === 'object' && self.self === self) {
	winObj = self;
}
// fake our window object for testing/SSR
else {
	winObj = {};
	winObj.self = winObj;
	winObj.top = winObj;
}

export const win = winObj;

export const inIframeContext = () => {
	return win.self !== win.top;
};

export const isIframe = inIframeContext();

export const debug = (output) => {
	if(!Config.get('debug', false)) {
		return;
	}

	console.info(output);
};

export const uuid = (a) => {
	return a ?
		(a^Math.random() * 16 >> a / 4).toString(16) :
		([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, uuid);
};

export const Definition = (
	isIframe ? win.top.astroDefinition : (win.astroDefinition = DefinitionClass)
);
<|endoftext|>


<commit_before>function addHeaderOptionsIcon() {
  const headerButtons = $('div.project-header > div.d-table.mt-1.float-right.f6');
  headerButtons.prepend(`

      <button class="btn-link muted-link v-align-middle jgh-projects-options-toggle" type="button" aria-haspop="true">
        <svg class="octicon octicon-tools" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M4.48 7.27c.26.26 1.28 1.33 1.28 1.33l.56-.58-.88-.91 1.69-1.8s-.76-.74-.43-.45c.32-1.19.03-2.51-.87-3.44C4.93.5 3.66.2 2.52.51l1.93 2-.51 1.96-1.89.52-1.93-2C-.19 4.17.1 5.48 1 6.4c.94.98 2.29 1.26 3.48.87zm6.44 1.94l-2.33 2.3 3.84 3.98c.31.33.73.49 1.14.49.41 0 .82-.16 1.14-.49.63-.65.63-1.7 0-2.35l-3.79-3.93zM16 2.53L13.55 0 6.33 7.46l.88.91-4.31 4.46-.99.53-1.39 2.27.35.37 2.2-1.44.51-1.02L7.9 9.08l.88.91L16 2.53z"></path></svg>
        Options
      </button>

  `);
}

function addProjectsOptionsPane() {
  const panes = $('div.project-pane');
  const panesParent = panes.parent();
  const isFullscreen = window.location.search.match(/fullscreen=true/);

  panesParent.append(`

        <button class="btn-link position-absolute top-0 right-0 mt-2 mr-3 link-gray jgh-projects-options-toggle" aria-label="Hide project options" type="button">
          <svg aria-hidden="true" class="octicon octicon-x" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48z"></path></svg>
        </button>

Project options

Hide repositories

  `);
}

function addButtonsEventListeners() {
  $('button.jgh-projects-options-toggle').on('click', toggleProjectOptionsPane);
}

function toggleProjectOptionsPane() {
  const pane = $('div.project-pane.jgh-projects-options-pane');
  if (pane.hasClass('d-none')) {
    pane.removeClass('d-none');

    openPane();
  } else {
    pane.addClass('d-none');
  }
}

function getRepositoriesList() {
  const repositories = new Set();
  const cardsDesc = $('.issue-card').find('small');

  cardsDesc.each((index, cardDesc) => {
    const cardText = cardDesc.innerText.trim();
    const matchRepo = cardText.match(/.*\/(.*)#\d+ .*/);
    if (matchRepo && matchRepo.length > 1) {
      repositories.add(matchRepo[1]);
    }
  });

  return repositories;
}

function openPane() {
  const repositories = getRepositoriesList();
  let repositoriesCheckboxes = '';
  repositories.forEach(repo => {
    repositoriesCheckboxes += `

          <input type="checkbox" id="${repo}" class="jgh-projects-options-toggle-repo"> ${repo}

    `;
  });

  $('#jgh-projects-options-repolist').html(repositoriesCheckboxes);

  $('.jgh-projects-options-toggle-repo').on('click', toggleRepositoryEvent);
}

function toggleRepositoryEvent(e) {
  const repo = e.target.id;
  const checked = e.target.checked;

  const repoPattern = `.*\\/${repo}#\\d+ .*`;
  const cards = $('.issue-card');
  cards.each((index, card) => {
    const cardDesc = $(card).find('small')[0];
    if (cardDesc.innerText.match(repoPattern)) {
      if (checked) {
        $(card).hide();
      } else {
        $(card).show();
      }
    }
  });
}

$(document).ready(() => {
  addHeaderOptionsIcon();
  addProjectsOptionsPane();
  addButtonsEventListeners();
});
<commit_msg>Hide cards by label<commit_after>function addHeaderOptionsIcon() {
  const headerButtons = $('div.project-header > div.d-table.mt-1.float-right.f6');
  headerButtons.prepend(`

      <button class="btn-link muted-link v-align-middle jgh-projects-options-toggle" type="button" aria-haspop="true">
        <svg class="octicon octicon-tools" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M4.48 7.27c.26.26 1.28 1.33 1.28 1.33l.56-.58-.88-.91 1.69-1.8s-.76-.74-.43-.45c.32-1.19.03-2.51-.87-3.44C4.93.5 3.66.2 2.52.51l1.93 2-.51 1.96-1.89.52-1.93-2C-.19 4.17.1 5.48 1 6.4c.94.98 2.29 1.26 3.48.87zm6.44 1.94l-2.33 2.3 3.84 3.98c.31.33.73.49 1.14.49.41 0 .82-.16 1.14-.49.63-.65.63-1.7 0-2.35l-3.79-3.93zM16 2.53L13.55 0 6.33 7.46l.88.91-4.31 4.46-.99.53-1.39 2.27.35.37 2.2-1.44.51-1.02L7.9 9.08l.88.91L16 2.53z"></path></svg>
        Options
      </button>

  `);
}

function addProjectsOptionsPane() {
  const panes = $('div.project-pane');
  const panesParent = panes.parent();
  const isFullscreen = window.location.search.match(/fullscreen=true/);

  panesParent.append(`

        <button class="btn-link position-absolute top-0 right-0 mt-2 mr-3 link-gray jgh-projects-options-toggle" aria-label="Hide project options" type="button">
          <svg aria-hidden="true" class="octicon octicon-x" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48z"></path></svg>
        </button>

Project options

Hide repositories

Hide labels

  `);
}

function addButtonsEventListeners() {
  $('button.jgh-projects-options-toggle').on('click', toggleProjectOptionsPane);
}

function toggleProjectOptionsPane() {
  const pane = $('div.project-pane.jgh-projects-options-pane');
  if (pane.hasClass('d-none')) {
    pane.removeClass('d-none');

    openPane();
  } else {
    pane.addClass('d-none');
  }
}

function getRepositoriesList() {
  const repositories = new Set();
  const cardsDesc = $('.issue-card').find('small');

  cardsDesc.each((index, cardDesc) => {
    const cardText = cardDesc.innerText.trim();
    const matchRepo = cardText.match(/.*\/(.*)#\d+ .*/);
    if (matchRepo && matchRepo.length > 1) {
      repositories.add(matchRepo[1]);
    }
  });

  return repositories;
}

function getLabelsList() {
  const labels = {};
  const labelEls = $('.issue-card-label');
  labelEls.each((index, label) => {
    labels[label.innerText] = label.style.cssText;
  });

  return labels;
}

function openPane() {
  // Hide repositories
  const repositories = getRepositoriesList();
  let repositoriesCheckboxes = '';
  repositories.forEach((repo) => {
    repositoriesCheckboxes += `

          <input type="checkbox" id="${repo}" class="jgh-projects-options-toggle-repo"> ${repo}

    `;
  });
  $('#jgh-projects-options-repolist').html(repositoriesCheckboxes);
  $('.jgh-projects-options-toggle-repo').on('click', toggleRepositoryEvent);

  // Hide labels
  const labels = getLabelsList();
  let labelsCheckboxes = '';
  $.each(labels, (label, style) => {
    labelsCheckboxes += `

          <input type="checkbox" id="${label}" class="jgh-projects-options-toggle-label">
          ${label}

    `;
  });
  $('#jgh-projects-options-labelist').html(labelsCheckboxes);
  $('.jgh-projects-options-toggle-label').on('click', toggleLabelEvent);
}

function toggleRepositoryEvent(e) {
  const repo = e.target.id;
  const checked = e.target.checked;

  const repoPattern = `.*\\/${repo}#\\d+ .*`;
  const cards = $('.issue-card');
  cards.each((index, card) => {
    const cardDesc = $(card).find('small')[0];
    if (cardDesc.innerText.match(repoPattern)) {
      if (checked) {
        $(card).hide();
      } else {
        $(card).show();
      }
    }
  });
}

function toggleLabelEvent(e) {
  const label = e.target.id;
  const checked = e.target.checked;

  const cards = $('.issue-card');
  cards.each((index, card) => {
    const cardLabels = $(card).find('.issue-card-label');
    if (cardLabels.length && cardLabels[0].innerText === label) {
      if (checked) {
        $(card).hide();
      } else {
        $(card).show();
      }
    }
  });
}

$(document).ready(() => {
  addHeaderOptionsIcon();
  addProjectsOptionsPane();
  addButtonsEventListeners();
});
<|endoftext|>


<commit_before>/**
 * Copyright 2012-present Thom Seddon.
 *
 * 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.
 */

//Globals
var dropdown = document.querySelector('.global-nav .pull-right .nav .dropdown-menu');
var currentAccount;

/**
 * Get current account from DOM
 */

var getCurrentAccount = function () {
  // Get current uid and image from DOM
  var account = dropdown.querySelector('.account-group');
  var img = dropdown.querySelector('.account-group img');

  if (!account) return false;

  return {
      uid: account.getAttribute('data-user-id'),
      name: account.getAttribute('data-screen-name'),
      img: img.getAttribute('src')
  };
};

/**
 * Switch current account
 */

var switchAccount = function (event) {
  var target = event.target;
  var uid;
  while (target.tagName !== 'LI') {
    target = target.parentNode;
  }
  uid = target.getAttribute('data-user-id');

  chrome.extension.sendMessage({type: 'switchAccount', uid: uid});
};

/**
 * Inject accounts into DOM
 */

var render = function (accounts) {

  // Cleanup previous render
  var twichers = dropdown.querySelectorAll('.twitcher-inserted');
  for (var i = 0; i < twichers.length; i++) {
    var childNode = twichers[i];
    if (childNode.parentNode) {
      childNode.parentNode.removeChild(childNode);
    }
  }

  var target = dropdown.querySelector('.dropdown-divider');
  var parent = target.parentNode;
  var accountsAdded = false;
  var li, html;

  // Add divider
  li = document.createElement('li');
  li.className = 'dropdown-divider twitcher-inserted';
  parent.insertBefore(li, target);

  var handleDragStart = function (uid) {
    return function(event) {
      this.style.opacity = '0.4';
      this.getElementsByTagName('a')[0].style.background = 'red';

      // Store uid
      event.dataTransfer.effectAllowed = 'move';
      event.dataTransfer.setData('text/html', uid);
    };
  };

  var handleDragEnd = function (event) {
    this.style.opacity = '1';
    this.getElementsByTagName('a')[0].setAttribute('style', '');
  };

  // Add each account
  for (var uid in accounts) {
    var account = accounts[uid];

    if (uid == currentAccount.uid) continue;

    li = document.createElement('li');
    li.className = 'twitcher-inserted';
    li.setAttribute('data-user-id', uid);
    li.setAttribute('draggable', true);
    li.innerHTML = '' + account.name + '';
    li = parent.insertBefore(li, target);
    li.addEventListener('click', switchAccount, false);

    // Add drag shizzle
    li.addEventListener('dragstart', handleDragStart(uid), false);
    li.addEventListener('dragend', handleDragEnd, false);

    accountsAdded = true;
  }

  if (!accountsAdded) {
    li = document.createElement('li');
    li.className = 'twitcher-inserted';
    li.innerHTML = '
No other accounts
';
    li = parent.insertBefore(li, target);
  }
};

/**
 * Bind listeners to DOM
 */

var bindDropListeners = function () {
  var preventDefault = function (event) {
    event.preventDefault();
    return false;
  };

  // This stops it propogating when droped back inside the dropdown
  dropdown.addEventListener('dragover', preventDefault, false);
  dropdown.addEventListener('dragenter', preventDefault, false);
  dropdown.addEventListener('drop', function (event) {
    event.preventDefault();
    event.stopPropagation();
  }, false);

  // Removes it when it's dropped outside the dropdown
  document.body.addEventListener('dragover', preventDefault, false);
  document.body.addEventListener('dragenter', preventDefault, false);
  document.body.addEventListener('drop', function (event) {
    event.preventDefault();
    chrome.extension.sendMessage({type: 'removeAccount', uid: event.dataTransfer.getData('text/html')}, render);
  }, false);
};

currentAccount = getCurrentAccount();
if (currentAccount) {
  // Save latest version of current user
  chrome.extension.sendMessage({ type: 'currentAccount', currentAccount: currentAccount }, function () {
    // Boot
    bindDropListeners();
    chrome.extension.sendMessage({ type: 'getAccounts' }, render);
  });
}
<commit_msg>Fix account removal bug.<commit_after>/**
 * Copyright 2012-present Thom Seddon.
 *
 * 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.
 */

//Globals
var dropdown = document.querySelector('.global-nav .pull-right .nav .dropdown-menu');
var currentAccount;

/**
 * Get current account from DOM
 */

var getCurrentAccount = function () {
  // Get current uid and image from DOM
  var account = dropdown.querySelector('.account-group');
  var img = dropdown.querySelector('.account-group img');

  if (!account) return false;

  return {
      uid: account.getAttribute('data-user-id'),
      name: account.getAttribute('data-screen-name'),
      img: img.getAttribute('src')
  };
};

/**
 * Switch current account
 */

var switchAccount = function (event) {
  var target = event.target;
  var uid;
  while (target.tagName !== 'LI') {
    target = target.parentNode;
  }
  uid = target.getAttribute('data-user-id');

  chrome.extension.sendMessage({type: 'switchAccount', uid: uid});
};

/**
 * Inject accounts into DOM
 */

var render = function (accounts) {

  // Cleanup previous render
  var twichers = dropdown.querySelectorAll('.twitcher-inserted');
  for (var i = 0; i < twichers.length; i++) {
    var childNode = twichers[i];
    if (childNode.parentNode) {
      childNode.parentNode.removeChild(childNode);
    }
  }

  var target = dropdown.querySelector('.dropdown-divider');
  var parent = target.parentNode;
  var accountsAdded = false;
  var li, html;

  // Add divider
  li = document.createElement('li');
  li.className = 'dropdown-divider twitcher-inserted';
  parent.insertBefore(li, target);

  var handleDragStart = function (uid) {
    return function(event) {
      this.style.opacity = '0.4';
      this.getElementsByTagName('a')[0].style.background = 'red';

      // Store uid
      event.dataTransfer.effectAllowed = 'move';
      event.dataTransfer.setData('text', uid);
    };
  };

  var handleDragEnd = function (event) {
    this.style.opacity = '1';
    this.getElementsByTagName('a')[0].setAttribute('style', '');
  };

  // Add each account
  for (var uid in accounts) {
    var account = accounts[uid];

    if (uid == currentAccount.uid) continue;

    li = document.createElement('li');
    li.className = 'twitcher-inserted';
    li.setAttribute('data-user-id', uid);
    li.setAttribute('draggable', true);
    li.innerHTML = '' + account.name + '';
    li = parent.insertBefore(li, target);
    li.addEventListener('click', switchAccount, false);

    // Add drag shizzle
    li.addEventListener('dragstart', handleDragStart(uid), false);
    li.addEventListener('dragend', handleDragEnd, false);

    accountsAdded = true;
  }

  if (!accountsAdded) {
    li = document.createElement('li');
    li.className = 'twitcher-inserted';
    li.innerHTML = '
No other accounts
';
    li = parent.insertBefore(li, target);
  }
};

/**
 * Bind listeners to DOM
 */

var bindDropListeners = function () {
  var preventDefault = function (event) {
    event.preventDefault();
    return false;
  };

  // This stops it propogating when droped back inside the dropdown
  dropdown.addEventListener('dragover', preventDefault, false);
  dropdown.addEventListener('dragenter', preventDefault, false);
  dropdown.addEventListener('drop', function (event) {
    event.preventDefault();
    event.stopPropagation();
  }, false);

  // Removes it when it's dropped outside the dropdown
  document.body.addEventListener('dragover', preventDefault, false);
  document.body.addEventListener('dragenter', preventDefault, false);
  document.body.addEventListener('drop', function (event) {
    event.preventDefault();
    chrome.extension.sendMessage({type: 'removeAccount', uid: event.dataTransfer.getData('text')}, render);
  }, false);
};

currentAccount = getCurrentAccount();
if (currentAccount) {
  // Save latest version of current user
  chrome.extension.sendMessage({ type: 'currentAccount', currentAccount: currentAccount }, function () {
    // Boot
    bindDropListeners();
    chrome.extension.sendMessage({ type: 'getAccounts' }, render);
  });
}
<|endoftext|>


<commit_before>(function(){

const iconTypes = {
	'http://moodle.nottingham.ac.uk/theme/image.php/nottingham_arts/core/1457712810/f/pdf-24': 'PDF',
	'http://moodle.nottingham.ac.uk/theme/image.php/nottingham_arts/core/1457712810/f/document-24': 'Word',
	'http://moodle.nottingham.ac.uk/theme/image.php/nottingham_arts/core/1457712810/f/powerpoint-24': 'PPT',
	'http://moodle.nottingham.ac.uk/theme/image.php/nottingham_arts/core/1457712810/f/calc-24': 'Excel'
};

const acceptableTags = ['strong', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'];

function labelLevel (label) {
	for (let i = 0; i < acceptableTags.length; ++i) {
		if (label.querySelector(acceptableTags[i])) {
			return i + 1;
		}
	}
	return -1;
}

function createDirObj (name, level) {
	return {
		type: 'dir',
		name,
		icon: 'http://moodle.nottingham.ac.uk/theme/image.php/nottingham_arts/folder/1457712810/icon',
		files: [],
		level,
	}
}

function createFileObj (id, name, icon) {
	return {
		type: 'file',
		fileType: iconTypes[icon] || 'unknown',
		id,
		name,
		icon,
	};
}

function createFolderObj (id, name, icon) {
	return {
		type: 'folder',
		id,
		name,
		icon: icon || 'http://moodle.nottingham.ac.uk/theme/image.php/nottingham_arts/folder/1457712810/icon',
	}
}

function getIdByActivity (activity) {
	return activity.id.split('-')[1];
}

function getIconByActivity (activity) {
	return activity.querySelector('.activityinstance>a>.activityicon').src;
}

function getLabelByActivity (activity) {
	for (let tagName of acceptableTags) {
		let tag = activity.querySelector(tagName);
		if (tag) {
			return tag.textContent;
		}
	}
	return null;
}

function getNameByActivity (activity) {
	let name = '';
	let instancename = activity.querySelector('.activityinstance>a>.instancename').childNodes;
	for (let node of instancename) {
		if (node.nodeType === 3) {
			name += node.textContent;
		}
	}
	return name;
}

function cleanData (data) {
	delete data.level;
	delete data.parent;
	if (data.files) {
		for (let file of data.files) {
			cleanData(file);
		}
	}
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
	if (request === 'requestData') {

		let module = document.getElementById('course-header').textContent;
		let data = {
			module: module,
			files: [],
		};
		let sections = document.querySelectorAll('.section.main:not(.hidden)');
		for (let section of sections) {
			let content = section.getElementsByClassName('content')[0];
			let name = content.getElementsByClassName('sectionname')[0].textContent;
			let dir = createDirObj(name, 0);
			let currentDir = dir;
			let activities = content.getElementsByClassName('activity');
			for (let activity of activities) {
				let id = getIdByActivity(activity);
				if (activity.classList.contains('modtype_label')) {
					let name = getLabelByActivity(activity);
					if (name === null) {
						// not a catagory label
						continue;
					}
					let newDir = createDirObj(name, labelLevel(activity));
					console.log(name, newDir.level, currentDir.name, currentDir.level);
					while (currentDir.level >= newDir.level && currentDir !== dir) {
						currentDir = currentDir.parent;
					}
					newDir.parent = currentDir;
					currentDir.files.push(newDir);
					currentDir = newDir;
				} else {
					if (!activity.querySelector('.activityinstance>a')) {
						// link unavailable
						continue;
					}
					let icon = getIconByActivity(activity);
					let name = getNameByActivity(activity);
					if (activity.classList.contains('modtype_resource')) {
						let file = createFileObj(id, name, icon);
						currentDir.files.push(file);
					} else if (activity.classList.contains('modtype_folder')) {
						let folder = createFolderObj(id, name, icon);
						currentDir.files.push(folder);
					}
				}
				/*
					modtype_feedback
					modtype_url
					modtype_page
					modtype_quiz
					modtype_book
				*/
			}
			data.files.push(dir);
		}
		cleanData(data);
		sendResponse(data);
	}
});

})();

<commit_msg>better handling for section name<commit_after>(function(){

const iconTypes = {
	'http://moodle.nottingham.ac.uk/theme/image.php/nottingham_arts/core/1457712810/f/pdf-24': 'PDF',
	'http://moodle.nottingham.ac.uk/theme/image.php/nottingham_arts/core/1457712810/f/document-24': 'Word',
	'http://moodle.nottingham.ac.uk/theme/image.php/nottingham_arts/core/1457712810/f/powerpoint-24': 'PPT',
	'http://moodle.nottingham.ac.uk/theme/image.php/nottingham_arts/core/1457712810/f/calc-24': 'Excel'
};

const acceptableTags = ['strong', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'];

function labelLevel (label) {
	for (let i = 0; i < acceptableTags.length; ++i) {
		if (label.querySelector(acceptableTags[i])) {
			return i + 1;
		}
	}
	return -1;
}

function createDirObj (name, level) {
	return {
		type: 'dir',
		name,
		icon: 'http://moodle.nottingham.ac.uk/theme/image.php/nottingham_arts/folder/1457712810/icon',
		files: [],
		level,
	}
}

function createFileObj (id, name, icon) {
	return {
		type: 'file',
		fileType: iconTypes[icon] || 'unknown',
		id,
		name,
		icon,
	};
}

function createFolderObj (id, name, icon) {
	return {
		type: 'folder',
		id,
		name,
		icon: icon || 'http://moodle.nottingham.ac.uk/theme/image.php/nottingham_arts/folder/1457712810/icon',
	}
}

function getIdByActivity (activity) {
	return activity.id.split('-')[1];
}

function getIconByActivity (activity) {
	return activity.querySelector('.activityinstance>a>.activityicon').src;
}

function getLabelByActivity (activity) {
	for (let tagName of acceptableTags) {
		let tag = activity.querySelector(tagName);
		if (tag) {
			return tag.textContent;
		}
	}
	return null;
}

function getNameByActivity (activity) {
	let name = '';
	let instancename = activity.querySelector('.activityinstance>a>.instancename').childNodes;
	for (let node of instancename) {
		if (node.nodeType === 3) {
			name += node.textContent;
		}
	}
	return name;
}

function cleanData (data) {
	delete data.level;
	delete data.parent;
	if (data.files) {
		for (let file of data.files) {
			cleanData(file);
		}
	}
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
	if (request === 'requestData') {

		let module = document.getElementById('course-header').textContent;
		let data = {
			module: module,
			files: [],
		};
		let sections = document.querySelectorAll('.section.main:not(.hidden)');
		for (let section of sections) {
			let content = section.getElementsByClassName('content')[0];
			let name = content.getElementsByClassName('sectionname')[0].textContent;
			let summary = getLabelByActivity(content.getElementsByClassName('summary')[0]);
			if (summary && summary.length > 1) {
				name = summary;
			}
			let dir = createDirObj(name, 0);
			let currentDir = dir;
			let activities = content.getElementsByClassName('activity');
			for (let activity of activities) {
				let id = getIdByActivity(activity);
				if (activity.classList.contains('modtype_label')) {
					let name = getLabelByActivity(activity);
					if (name === null) {
						// not a catagory label
						continue;
					}
					let newDir = createDirObj(name, labelLevel(activity));
					while (currentDir.level >= newDir.level && currentDir !== dir) {
						currentDir = currentDir.parent;
					}
					newDir.parent = currentDir;
					currentDir.files.push(newDir);
					currentDir = newDir;
				} else {
					if (!activity.querySelector('.activityinstance>a')) {
						// link unavailable
						continue;
					}
					let icon = getIconByActivity(activity);
					let name = getNameByActivity(activity);
					if (activity.classList.contains('modtype_resource')) {
						let file = createFileObj(id, name, icon);
						currentDir.files.push(file);
					} else if (activity.classList.contains('modtype_folder')) {
						let folder = createFolderObj(id, name, icon);
						currentDir.files.push(folder);
					}
				}
				/*
					modtype_feedback
					modtype_url
					modtype_page
					modtype_quiz
					modtype_book
				*/
			}
			data.files.push(dir);
		}
		cleanData(data);
		sendResponse(data);
	}
});

})();

<|endoftext|>


<commit_before>(function () {
    var global = (function() {
        return this;
    })(), D = Deferred;

    var isEnabled = false;

    var requestAnimationFrame = global.requestAnimationFrame || global.webkitRequestAnimationFrame;

    var UNKNOWN_URL = "*UNKNOWN*";
    var NOT_AN_APNG = "*NOT_AN_APNG*";

    var loadBytes = function (url) {
        var d = D();
        if (inStopList(url)) {
            d.reject("Url in stop list");
        } else if (url.substr(0, 5) == "blob:") {
            d.reject("BLOB's not supported");
        } else if (url.substr(0, 5) == "data:") {
            var parts = url.substr(5).split(",", 2);
            parts[0] = parts[0].split(";");
            var data = parts[1], mime = parts[0][0], enc = parts[0][parts[0].length - 1];

            if (mime.indexOf("image/png") !== 0) {
                d.reject("not a PNG data");
            } else {
                var str = (enc == "base64") ? atob(data) : unescape(data);
                var bytes = new Uint8Array(str.length);
                for (var i = 0; i < str.length; i++) bytes[i] = str.charCodeAt(i);
                d.resolve(bytes);
            }
        } else {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.responseType = "arraybuffer";
            xhr.onload = function () {
                if (this.status == 200) {
                    d.resolve(new Uint8Array(this.response));
                } else {
                    d.reject(xhr.statusText);
                }
            };
            xhr.send();
        }
        return d.promise();
    };

    var checkUrl = function(url) {
        var d = D();
        chrome.extension.sendRequest(
                {"action":"checkUrl", "url":url},
                function (resp) {
                    if (resp == "yes") {
                        d.resolve(url);
                    } else if (resp == "no") {
                        d.reject(NOT_AN_APNG);
                    } else {
                        d.reject(UNKNOWN_URL);
                    }
                }
        );
        return d.promise();
    };

    var urlPromises = {};
    var allAnimations = [];
    var loadAndParseURL = function (url) {
        if (!(url in urlPromises)) {
            urlPromises[url] = D.pipeline(url)(
                    checkUrl,
                    loadBytes,
                    parseAPNG,
                    function (apng) {
                        return new Animation(apng);
                    },
                    function (a) {
                        allAnimations.push(a);
                        animationFound();
                        return a;
                    }
            );
        }
        return urlPromises[url];
    };

    var ctxNamePrefix = "apng-chrome-ext-css-", ctxNameCounter = 1;
    var Animation = function(apng) {
        this.isActive = false;
        this.nextRenderTime = 0;

        for (var k in apng) if (apng.hasOwnProperty(k)) this[k] = apng[k];

        var context = null;
        var contextName = null;
        this.getCanvasName = function() {
            if (!context) {
                contextName = ctxNamePrefix + (ctxNameCounter++);
                context = document.getCSSCanvasContext("2d", contextName, this.width, this.height);
                this.isActive = true;
            }
            return contextName;
        };

        var fNum = 0;
        var prevF = null;
        this.renderFrame = function(now) {
            if (!context) return;
            var f = fNum++ % this.frames.length;
            var frame = this.frames[f];

            if (f == 0) {
                context.clearRect(0, 0, this.width, this.height);
                prevF = null;
                if (frame.disposeOp == 2) frame.disposeOp = 1;
            }

            if (prevF && prevF.disposeOp == 1) {
                context.clearRect(prevF.left, prevF.top, prevF.width, prevF.height);
            } else if (prevF && prevF.disposeOp == 2) {
                context.putImageData(prevF.iData, prevF.left, prevF.top);
            }
            prevF = frame;
            prevF.iData = null;
            if (prevF.disposeOp == 2) {
                prevF.iData = context.getImageData(frame.left, frame.top, frame.width, frame.height);
            }
            if (frame.blendOp == 0) context.clearRect(frame.left, frame.top, frame.width, frame.height);
            context.drawImage(frame.img, frame.left, frame.top);

            if (this.numPlays == 0 || fNum / this.frames.length < this.numPlays) {
                if (this.nextRenderTime == 0) this.nextRenderTime = now;
                while (now > this.nextRenderTime + this.playTime) this.nextRenderTime += this.playTime;
                this.nextRenderTime += frame.delay;
            } else {
                this.isActive = false;
            }
        };
    };

    var onImageLoad = function () {
        var image = this, w = image.width, h = image.height;
        loadAndParseURL(image.src)
                .done(function (a) {
                    if (!image.hasAttribute("width") && (!image.style.width || image.style.width == "auto")) {
                        image.style.width = w + "px";
                        image.style.cssText = image.style.cssText.replace(/\bwidth:\s*\d+px/, "$& !important");
                    }
                    if (!image.hasAttribute("height") && (!image.style.height || image.style.height == "auto")) {
                        image.style.height = h + "px";
                        image.style.cssText = image.style.cssText.replace(/\bheight:\s*\d+px/, "$& !important");
                    }
                    var ctxName = a.getCanvasName();
                    image.apngContextName = ctxName;
                    image.style.content = "-webkit-canvas(" + ctxName + ")";
                })
                .fail(function (err) {
                    if (err != UNKNOWN_URL) {
                        chrome.extension.sendRequest({
                            "action":"isAnAPNG",
                            "url":image.src,
                            "isIt":false
                        });
                        if (err == NOT_AN_APNG) {
                            image.style.content = "";
                            delete(image.apngContextName);
                        }
                    }
                });
    };
    var checkImages = function () {
        for (var i = 0, l = document.images.length; i < l; i++) {
            var image = document.images[i];
            if (image.apngContextName && !image.style.content) {
                image.style.content = "-webkit-canvas(" + image.apngContextName + ")";
                continue;
            }
            if ("apngStatus" in image) continue;

            image.apngStatus = true;
            image.addEventListener("load", onImageLoad, false);
            if (image.complete) onImageLoad.apply(image);
        }
    };

    var checkInlineCSSImages = function () {
        var els = document.querySelectorAll("*[style*='url(']");
        for (var i = 0, l = els.length; i < l; i++) {
            var el = els[i];
            if ("apngStatus" in el) continue;
            el.apngStatus = true;
            var props = ["backgroundImage", "listStyleImage"], prop;
            while (prop = props.shift()) {
                if (prop in el.style) {
                    var matches = el.style[prop].match(/url\((['"]?)(.*?)\1\)/g) || [];
                    for (var mi = 0; mi < matches.length; mi++) {
                        var url = matches[mi].match(/url\((['"]?)(.*?)\1\)/)[2];
                        (function (url, el, prop, m) {
                            loadAndParseURL(url)
                                    .done(function (a) {
                                        el.style[prop] = el.style[prop]
                                                .replace(m, "-webkit-canvas(" + a.getCanvasName() + ")");
                                    });
                        })(url, el, prop, matches[mi]);
                    }
                }
            }
        }
    };

    chrome.extension.sendRequest(
            {"action":"checkHostname", "data":global.location.hostname},
            function (response) {
                if (response) {
                    isEnabled = true;
                    // main check loop
                    (function () {
                        checkImages();
                        checkInlineCSSImages();
                        setTimeout(arguments.callee, 1000);
                    })();
                }
            }
    );

    // Main animation loop
    var animationTick = function (t) {
        for (var i = 0; i < allAnimations.length; i++) {
            var a = allAnimations[i];
            while (a.isActive && a.nextRenderTime <= t) a.renderFrame(t);
        }
        requestAnimationFrame(animationTick);
    };

    var foundCount = 0;
    chrome.extension.onRequest.addListener(function(request, sender, callback) {
        if (request.action == "getInfo") {
            callback({
                "hostname": global.location.hostname,
                "enabled":  isEnabled,
                "found":    foundCount
            });
        }
    });

    var isAnimationFound = false;
    var animationFound = function() {
        if (!isAnimationFound) {
            isAnimationFound = true;
            requestAnimationFrame(animationTick);
        }
        foundCount++;
        chrome.extension.sendRequest({
            "action":   "apngFound",
            "data":     foundCount
        });

        if (document.images.length == 1 && document.images[0].src == location.href) {

            /**
             * Strange bug in Opera 15/Next
             */
            if (/Opera/.test(navigator['vendor'])) {
                var link = document.createElement("link");
                link.href = "about:blank";
                link.type = "text/css";
                link.rel = "stylesheet";
                document.body.appendChild(link);
            }

            var a = allAnimations[0];
            var cont = document.body.appendChild(document.createElement("div"));
            var cont2 = document.body.appendChild(document.createElement("div"));
            cont.className = "apng-frames-list";
            cont.innerHTML = "Show APNG frames";

            cont2.className = "apng-frames-list";
            cont2.style.display = "none";
            for (var i = 0, l = a.frames.length; i< l; i++) {
                var frame = a.frames[i], img = frame.img;
                var fc = cont2.appendChild(document.createElement("div"));
                fc.style.width = a.width + "px";
                fc.style.height = a.height + "px";
                img.style.left = frame.left+"px";
                img.style.top  = frame.top+"px";
                fc.appendChild(img);
            }

            var isHidden = true;
            cont.querySelector("span").addEventListener("click", function() {
                isHidden = !isHidden;
                if (isHidden) {
                    this.innerHTML = "Show APNG frames";
                    this.className = "";
                    cont2.style.display = "none";
                } else {
                    this.innerHTML = "Hide APNG frames";
                    this.className = "shown";
                    cont2.style.display = "block";
                }
            });
        }
    };

})();
<commit_msg>На стр. с одним изображением надо вручную передёргивать стили<commit_after>(function () {
    var global = (function() {
        return this;
    })(), D = Deferred;

    var isEnabled = false;

    var requestAnimationFrame = global.requestAnimationFrame || global.webkitRequestAnimationFrame;

    var UNKNOWN_URL = "*UNKNOWN*";
    var NOT_AN_APNG = "*NOT_AN_APNG*";

    var loadBytes = function (url) {
        var d = D();
        if (inStopList(url)) {
            d.reject("Url in stop list");
        } else if (url.substr(0, 5) == "blob:") {
            d.reject("BLOB's not supported");
        } else if (url.substr(0, 5) == "data:") {
            var parts = url.substr(5).split(",", 2);
            parts[0] = parts[0].split(";");
            var data = parts[1], mime = parts[0][0], enc = parts[0][parts[0].length - 1];

            if (mime.indexOf("image/png") !== 0) {
                d.reject("not a PNG data");
            } else {
                var str = (enc == "base64") ? atob(data) : unescape(data);
                var bytes = new Uint8Array(str.length);
                for (var i = 0; i < str.length; i++) bytes[i] = str.charCodeAt(i);
                d.resolve(bytes);
            }
        } else {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.responseType = "arraybuffer";
            xhr.onload = function () {
                if (this.status == 200) {
                    d.resolve(new Uint8Array(this.response));
                } else {
                    d.reject(xhr.statusText);
                }
            };
            xhr.send();
        }
        return d.promise();
    };

    var checkUrl = function(url) {
        var d = D();
        chrome.extension.sendRequest(
                {"action":"checkUrl", "url":url},
                function (resp) {
                    if (resp == "yes") {
                        d.resolve(url);
                    } else if (resp == "no") {
                        d.reject(NOT_AN_APNG);
                    } else {
                        d.reject(UNKNOWN_URL);
                    }
                }
        );
        return d.promise();
    };

    var urlPromises = {};
    var allAnimations = [];
    var loadAndParseURL = function (url) {
        if (!(url in urlPromises)) {
            urlPromises[url] = D.pipeline(url)(
                    checkUrl,
                    loadBytes,
                    parseAPNG,
                    function (apng) {
                        return new Animation(apng);
                    },
                    function (a) {
                        allAnimations.push(a);
                        animationFound();
                        return a;
                    }
            );
        }
        return urlPromises[url];
    };

    var ctxNamePrefix = "apng-chrome-ext-css-", ctxNameCounter = 1;
    var Animation = function(apng) {
        this.isActive = false;
        this.nextRenderTime = 0;

        for (var k in apng) if (apng.hasOwnProperty(k)) this[k] = apng[k];

        var context = null;
        var contextName = null;
        this.getCanvasName = function() {
            if (!context) {
                contextName = ctxNamePrefix + (ctxNameCounter++);
                context = document.getCSSCanvasContext("2d", contextName, this.width, this.height);
                this.isActive = true;
            }
            return contextName;
        };

        var fNum = 0;
        var prevF = null;
        this.renderFrame = function(now) {
            if (!context) return;
            var f = fNum++ % this.frames.length;
            var frame = this.frames[f];

            if (f == 0) {
                context.clearRect(0, 0, this.width, this.height);
                prevF = null;
                if (frame.disposeOp == 2) frame.disposeOp = 1;
            }

            if (prevF && prevF.disposeOp == 1) {
                context.clearRect(prevF.left, prevF.top, prevF.width, prevF.height);
            } else if (prevF && prevF.disposeOp == 2) {
                context.putImageData(prevF.iData, prevF.left, prevF.top);
            }
            prevF = frame;
            prevF.iData = null;
            if (prevF.disposeOp == 2) {
                prevF.iData = context.getImageData(frame.left, frame.top, frame.width, frame.height);
            }
            if (frame.blendOp == 0) context.clearRect(frame.left, frame.top, frame.width, frame.height);
            context.drawImage(frame.img, frame.left, frame.top);

            if (this.numPlays == 0 || fNum / this.frames.length < this.numPlays) {
                if (this.nextRenderTime == 0) this.nextRenderTime = now;
                while (now > this.nextRenderTime + this.playTime) this.nextRenderTime += this.playTime;
                this.nextRenderTime += frame.delay;
            } else {
                this.isActive = false;
            }
        };
    };

    var onImageLoad = function () {
        var image = this, w = image.width, h = image.height;
        loadAndParseURL(image.src)
                .done(function (a) {
                    if (!image.hasAttribute("width") && (!image.style.width || image.style.width == "auto")) {
                        image.style.width = w + "px";
                        image.style.cssText = image.style.cssText.replace(/\bwidth:\s*\d+px/, "$& !important");
                    }
                    if (!image.hasAttribute("height") && (!image.style.height || image.style.height == "auto")) {
                        image.style.height = h + "px";
                        image.style.cssText = image.style.cssText.replace(/\bheight:\s*\d+px/, "$& !important");
                    }
                    var ctxName = a.getCanvasName();
                    image.apngContextName = ctxName;
                    image.style.content = "-webkit-canvas(" + ctxName + ")";
                })
                .fail(function (err) {
                    if (err != UNKNOWN_URL) {
                        chrome.extension.sendRequest({
                            "action":"isAnAPNG",
                            "url":image.src,
                            "isIt":false
                        });
                        if (err == NOT_AN_APNG) {
                            image.style.content = "";
                            delete(image.apngContextName);
                        }
                    }
                });
    };
    var checkImages = function () {
        for (var i = 0, l = document.images.length; i < l; i++) {
            var image = document.images[i];
            if (image.apngContextName && !image.style.content) {
                image.style.content = "-webkit-canvas(" + image.apngContextName + ")";
                continue;
            }
            if ("apngStatus" in image) continue;

            image.apngStatus = true;
            image.addEventListener("load", onImageLoad, false);
            if (image.complete) onImageLoad.apply(image);
        }
    };

    var checkInlineCSSImages = function () {
        var els = document.querySelectorAll("*[style*='url(']");
        for (var i = 0, l = els.length; i < l; i++) {
            var el = els[i];
            if ("apngStatus" in el) continue;
            el.apngStatus = true;
            var props = ["backgroundImage", "listStyleImage"], prop;
            while (prop = props.shift()) {
                if (prop in el.style) {
                    var matches = el.style[prop].match(/url\((['"]?)(.*?)\1\)/g) || [];
                    for (var mi = 0; mi < matches.length; mi++) {
                        var url = matches[mi].match(/url\((['"]?)(.*?)\1\)/)[2];
                        (function (url, el, prop, m) {
                            loadAndParseURL(url)
                                    .done(function (a) {
                                        el.style[prop] = el.style[prop]
                                                .replace(m, "-webkit-canvas(" + a.getCanvasName() + ")");
                                    });
                        })(url, el, prop, matches[mi]);
                    }
                }
            }
        }
    };

    chrome.extension.sendRequest(
            {"action":"checkHostname", "data":global.location.hostname},
            function (response) {
                if (response) {
                    isEnabled = true;
                    // main check loop
                    (function () {
                        checkImages();
                        checkInlineCSSImages();
                        setTimeout(arguments.callee, 1000);
                    })();
                }
            }
    );

    // Main animation loop
    var animationTick = function (t) {
        for (var i = 0; i < allAnimations.length; i++) {
            var a = allAnimations[i];
            while (a.isActive && a.nextRenderTime <= t) a.renderFrame(t);
        }
        requestAnimationFrame(animationTick);
    };

    var foundCount = 0;
    chrome.extension.onRequest.addListener(function(request, sender, callback) {
        if (request.action == "getInfo") {
            callback({
                "hostname": global.location.hostname,
                "enabled":  isEnabled,
                "found":    foundCount
            });
        }
    });

    var isAnimationFound = false;
    var animationFound = function() {
        if (!isAnimationFound) {
            isAnimationFound = true;
            requestAnimationFrame(animationTick);
        }
        foundCount++;
        chrome.extension.sendRequest({
            "action":   "apngFound",
            "data":     foundCount
        });

        if (document.images.length == 1 && document.images[0].src == location.href) {

            var link = document.createElement("link");
            link.href = "about:blank";
            link.type = "text/css";
            link.rel = "stylesheet";
            document.body.appendChild(link);

            var a = allAnimations[0];
            var cont = document.body.appendChild(document.createElement("div"));
            var cont2 = document.body.appendChild(document.createElement("div"));
            cont.className = "apng-frames-list";
            cont.innerHTML = "Show APNG frames";

            cont2.className = "apng-frames-list";
            cont2.style.display = "none";
            for (var i = 0, l = a.frames.length; i< l; i++) {
                var frame = a.frames[i], img = frame.img;
                var fc = cont2.appendChild(document.createElement("div"));
                fc.style.width = a.width + "px";
                fc.style.height = a.height + "px";
                img.style.left = frame.left+"px";
                img.style.top  = frame.top+"px";
                fc.appendChild(img);
            }

            var isHidden = true;
            cont.querySelector("span").addEventListener("click", function(e) {
                var tgt = e.target;
                isHidden = !isHidden;
                if (isHidden) {
                    tgt.innerHTML = "Show APNG frames";
                    tgt.className = "";
                    cont2.style.display = "none";
                } else {
                    tgt.innerHTML = "Hide APNG frames";
                    tgt.className = "shown";
                    cont2.style.display = "block";
                }
            });
        }
    };

})();
<|endoftext|>


<commit_before>/**
 *
 * Copyright 2016 Yoshihiro Tanaka
 * 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.
 *
 * Author: Yoshihiro Tanaka <contact@cordea.jp>
 * date  : 2016-04-28
 */

content = {}

content.values = {}

content.init_ = function() {
    var title = document.getElementsByTagName("title")[0];
    title.innerText = constants.DEFAULT_TITLE;
    new MutationObserver(content.fixTitle_)
        .observe(title, {childList: true});

    var timeline = document.getElementById("_timeLine");
    new MutationObserver(content.fixTimelineLayout_)
        .observe(timeline, {childList: true});

    var rooms = document.getElementById("_roomListItems");
    new MutationObserver(content.hideUnnecessaryRoomItems_)
        .observe(rooms, {childList: true});

    var roomTitle = document.getElementById("_roomTitle");
    new MutationObserver(content.fixRoomLayout_)
        .observe(roomTitle, {childList: true});

    content.hideMenuIcon_();
    content.hideUnnecessaryRoomItems_();
    content.hideTopBarContents_();
    content.fixTimelineLayout_();
}

content.fixTitle_ = function(mutations) {
    var target = mutations[0].target;
    target.innerText = constants.DEFAULT_TITLE;
}

content.hideMenuIcon_ = function() {
    var chats = document.getElementsByClassName("_message chatTimeLineMessage chatTimeLineMessageAnim clearfix");
    var chatFilterList = document.getElementById("_chatFilterList");
    chatFilterList.className = "cwTextUnselectable _cwBB";
    chatFilterList.style = "position: absolute; top: 6px; left: 40px; right: 40px;"
    var icons = chatFilterList.childNodes;
    icons[0].style = "display: none";
    icons[2].style = "display: none";
    icons[1].style = "width: 100%; border-radius: 3px";
}

content.hideTopBarContents_ = function() {
    var info = document.getElementById("_openInfomation");
    info.style = "display: none";
    var contact = document.getElementById("_openContactWindow");
    contact.style = "display: none";
}

content.hideUnnecessaryRoomItems_ = function() {
    content.hideRoomIcons_();
    content.hideUnreadBadge_();
    content.hideRooms_();
}

content.hideRooms_ = function() {
    content.getValueFromStorage_(function(hideRooms) {
        if (hideRooms.length === 0) {
            return;
        }
        var rooms = content.getRooms_();
        for (var i in hideRooms) {
            if (hideRooms[i] in rooms) {
                if (!content.isMention_(rooms[hideRooms[i]])) {
                    rooms[hideRooms[i]].style = "display: none";
                }
            }
        }
    }, constants.StorageType.HIDE);
}

content.hideUnreadBadge_ = function() {
    content.getValueFromStorage_(function(ignoreRooms) {
        var rooms = content.getRooms_();
        content.changeUnreadBadge_(rooms, ignoreRooms);
        if (ignoreRooms.length === 0) {
            return;
        }
        for (var i in ignoreRooms) {
            if (ignoreRooms[i] in rooms) {
                var room = rooms[ignoreRooms[i]];
                var badge = room.getElementsByClassName("_unreadBadge unread");
                var mention = room.getElementsByClassName("_mentionLabel");
                room.style = "font-weight: 400";
                if (badge.length > 0) {
                    badge[0].style = "display: none";
                }
                if (mention.length > 0) {
                    mention[0].style = "margin: 0px";
                }
            }
        }
    }, constants.StorageType.IGNORE);
}

content.changeUnreadBadge_ = function(rooms, ignoreRooms) {
    for (var i in rooms) {
        if (ignoreRooms.indexOf(i) > -1) {
            continue;
        }
        var room = rooms[i];
        var badge = room.getElementsByClassName("_unreadBadge unread");
        var mention = room.getElementsByClassName("_mentionLabel");
        var add = "";
        if (badge.length > 0) {
            add = "*";
        }
        if (mention.length > 0) {
            add = "+";
        }
        if (add.length > 0) {
            var incomplete = room.getElementsByClassName("incomplete")[0];
            incomplete.style = "display: none";
        }

        var title = room.getElementsByClassName("chatListTitleArea");
        if (title.length > 0) {
            title[0].innerText = add + title[0].innerText;
            room.style = "font-weight: 400";
        }
    }
}

content.getValueFromStorage_ = function(func, type) {
    var c = constants;

    var HIDE = c.StorageType.HIDE
    var IGNORE = c.StorageType.IGNORE;
    var HIDE_ROOM = c.StorageType.HIDE_ROOM;
    var HIDE_USER = c.StorageType.HIDE_USER;
    var USER_COLOR = c.StorageType.USER_COLOR;
    var OWN_POST = c.StorageType.OWN_POST;

    if (content.values[type] !== undefined) {
        func(content.values[type]);
        return;
    }

    var get = c.getDefaultValues();

    chrome.storage.sync.get(get
            , function(items) {
                var hideListString = items[c.HIDE_LIST_KEY];
                var ignoreListString = items[c.IGNORE_LIST_KEY];

                content.values[HIDE] = hideListString.split("\n");
                content.values[IGNORE] = ignoreListString.split("\n");
                content.values[HIDE_USER] = items[c.HIDE_USER_ICON_KEY];
                content.values[HIDE_ROOM] = items[c.HIDE_ROOM_ICON_KEY];
                content.values[USER_COLOR] = items[c.USER_NAME_COLOR_KEY];
                content.values[OWN_POST] = items[c.GRAY_OWN_POST_KEY];

                func(content.values[type]);
            });
}

content.isMention_ = function(room) {
    var mention = room.getElementsByClassName("_mentionLabel");
    return mention.length > 0;
}

content.getRooms_ = function() {
    var rooms = document.getElementById("_roomListItems").childNodes;
    var validRooms = {};
    for (var i in rooms) {
        var room = rooms[i];
        if (room instanceof HTMLElement) {
            var name = room.getAttribute("aria-label");
            validRooms[name] = room;
        }
    }
    return validRooms;
}

content.hideRoomIcons_ = function() {
    content.getValueFromStorage_(function(isHideRoom) {
        if (!isHideRoom) {
            return;
        }
        var rooms = content.getRooms_();
        for (var k in rooms) {
            var room = rooms[k];
            var icon = room.getElementsByClassName("roomIcon");
            var meta = room.getElementsByClassName("chatListMeta");
            if (icon.length > 0) {
                icon[0].style = "display: none";
            }
            if (meta.length > 0) {
                meta[0].className = "";
            }
        }
    }, constants.StorageType.HIDE_ROOM);
}

content.fixTimelineLayout_ = function() {
    var timelines = document.getElementById("_timeLine").childNodes;
    for (var i in timelines) {
        var timeline = timelines[i];
        var name = timeline.className;
        if (name !== undefined && name.includes("chatTimeLineMessage")) {
            var nameContainer = timeline.getElementsByClassName("_speakerName chatName");
            content.hideUserIcon_(timeline);
            var org = timeline.getElementsByClassName("chatNameOrgname");
            var span = nameContainer[0].getElementsByTagName("span");
            if (org.length > 0) {
                org[0].style = "display: none";
            }
            if (timeline.className.includes("chatTimeLineMessageMine")) {
                content.changeGrayOfOwnPosts_(timeline, span);
            } else {
                content.changeNameColor_(span);
            }
        }
    }
}

content.hideUserIcon_ = function(timeline) {
    content.getValueFromStorage_(function(isHideUser) {
        if (!isHideUser) {
            return;
        }
        var message = timeline.getElementsByClassName("chatTimeLineMessageArea");
        var avator = timeline.getElementsByClassName("avatarSpeaker");
        if (avator.length > 0) {
            avator[0].style = "height: 0px; width: 0px";
            var image = avator[0].getElementsByTagName("img");
            image[0].style = "height: 0px; width: 0px";
        }
        message[0].style = "padding: 0px";
    }, constants.StorageType.HIDE_USER);
}

content.changeGrayOfOwnPosts_ = function(timeline, span) {
    content.getValueFromStorage_(function(isOwnPost) {
        if (!isOwnPost) {
            content.changeNameColor_(span);
            return;
        }
        if (span.length > 0) {
            span[0].style = "color: gray";
        }
        var pre = timeline.getElementsByTagName("pre");
        if (pre.length > 0) {
            pre[0].style = "color: gray";
            var repDiv = pre[0].getElementsByClassName("chatTimeLineReply _replyMessage");
            if (repDiv.length > 0) {
                repDiv[0].style = "background: gray";
            }
            var toSpan = pre[0].getElementsByClassName("chatTimeLineTo");
            if (toSpan.length > 0) {
                toSpan[0].style = "background: gray";
            }
        }
    }, constants.StorageType.OWN_POST);
}

content.changeNameColor_ = function(span) {
    content.getValueFromStorage_(function(userColor) {
        if (!userColor.startsWith("#")) {
            return;
        }
        if (span.length > 0) {
            span[0].style = "color: " + userColor;
        }
    }, constants.StorageType.USER_COLOR);
}

content.fixRoomLayout_ = function(mutations) {
    mutations.forEach(function(mutation) {
        var nodes = mutation.addedNodes;
        if (nodes.length > 0) {
            if (nodes[0].className.includes("_roomTitleText")) {
                nodes[0].style = "font-size: small";
            }
            if (nodes[1].className.includes("_pin")) {
                nodes[1].style = "display: none";
            }
        }
    });
}

content.init_();
<commit_msg>compress the list of room<commit_after>/**
 *
 * Copyright 2016 Yoshihiro Tanaka
 * 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.
 *
 * Author: Yoshihiro Tanaka <contact@cordea.jp>
 * date  : 2016-04-28
 */

content = {}

content.values = {}

content.init_ = function() {
    var title = document.getElementsByTagName("title")[0];
    title.innerText = constants.DEFAULT_TITLE;
    new MutationObserver(content.fixTitle_)
        .observe(title, {childList: true});

    var timeline = document.getElementById("_timeLine");
    new MutationObserver(content.fixTimelineLayout_)
        .observe(timeline, {childList: true});

    var rooms = document.getElementById("_roomListItems");
    new MutationObserver(content.hideUnnecessaryRoomItems_)
        .observe(rooms, {childList: true});

    var roomTitle = document.getElementById("_roomTitle");
    new MutationObserver(content.fixRoomLayout_)
        .observe(roomTitle, {childList: true});

    content.hideMenuIcon_();
    content.hideUnnecessaryRoomItems_();
    content.hideTopBarContents_();
    content.fixTimelineLayout_();
}

content.fixTitle_ = function(mutations) {
    var target = mutations[0].target;
    target.innerText = constants.DEFAULT_TITLE;
}

content.hideMenuIcon_ = function() {
    var chats = document.getElementsByClassName("_message chatTimeLineMessage chatTimeLineMessageAnim clearfix");
    var chatFilterList = document.getElementById("_chatFilterList");
    chatFilterList.className = "cwTextUnselectable _cwBB";
    chatFilterList.style = "position: absolute; top: 6px; left: 40px; right: 40px;"
    var icons = chatFilterList.childNodes;
    icons[0].style = "display: none";
    icons[2].style = "display: none";
    icons[1].style = "width: 100%; border-radius: 3px";
}

content.hideTopBarContents_ = function() {
    var info = document.getElementById("_openInfomation");
    info.style = "display: none";
    var contact = document.getElementById("_openContactWindow");
    contact.style = "display: none";
}

content.hideUnnecessaryRoomItems_ = function() {
    content.hideRoomIcons_();
    content.fixRoomListLayout_();
    content.hideRooms_();
}

content.hideRooms_ = function() {
    content.getValueFromStorage_(function(hideRooms) {
        if (hideRooms.length === 0) {
            return;
        }
        var rooms = content.getRooms_();
        for (var i in hideRooms) {
            if (hideRooms[i] in rooms) {
                if (!content.isMention_(rooms[hideRooms[i]])) {
                    rooms[hideRooms[i]].style = "display: none";
                }
            }
        }
    }, constants.StorageType.HIDE);
}

content.fixRoomListLayout_ = function() {
    content.getValueFromStorage_(function(ignoreRooms) {
        var rooms = content.getRooms_();
        content.compressRooms_(rooms, ignoreRooms);
        if (ignoreRooms.length === 0) {
            return;
        }
        for (var i in ignoreRooms) {
            if (ignoreRooms[i] in rooms) {
                var room = rooms[ignoreRooms[i]];
                var badge = room.getElementsByClassName("_unreadBadge unread");
                var mention = room.getElementsByClassName("_mentionLabel");
                if (badge.length > 0) {
                    badge[0].style = "display: none";
                }
                if (mention.length > 0) {
                    mention[0].style = "margin: 0px";
                }
            }
        }
    }, constants.StorageType.IGNORE);
}

content.compressRooms_ = function(rooms, ignoreRooms) {
    content.getValueFromStorage_(function(isCompressRooms) {
        if (!isCompressRooms) {
            return;
        }
        for (var i in rooms) {
            var room = rooms[i];
            room.style = "font-weight: 400; height: 16px; min-height: 0px";
            var pin = room.getElementsByClassName("chatListPin");
            if (pin.length > 0) {
                pin[0].style = "top: 1px";
            }
            var incomp = room.getElementsByClassName("incomplete");
            if (incomp.length > 0) {
                incomp.style = "display: none";
            }

            if (ignoreRooms.indexOf(i) > -1) {
                continue;
            }
            content.changeUnreadBadge_(room);
        }
    }, constants.StorageType.COMPRESS_ROOMS);
}

content.changeUnreadBadge_ = function(room) {
    var badge = room.getElementsByClassName("_unreadBadge unread");
    var mention = room.getElementsByClassName("_mentionLabel");
    var add = "";

    if (badge.length > 0) {
        add = "*";
    }
    if (mention.length > 0) {
        add = "+";
    }
    if (add.length > 0) {
        var incomplete = room.getElementsByClassName("incomplete")[0];
        incomplete.style = "display: none";
    }

    var title = room.getElementsByClassName("chatListTitleArea");
    if (title.length > 0) {
        title[0].innerText = add + title[0].innerText;
    }
}

content.getValueFromStorage_ = function(func, type) {
    var c = constants;

    var HIDE = c.StorageType.HIDE
    var IGNORE = c.StorageType.IGNORE;
    var HIDE_ROOM = c.StorageType.HIDE_ROOM;
    var HIDE_USER = c.StorageType.HIDE_USER;
    var USER_COLOR = c.StorageType.USER_COLOR;
    var OWN_POST = c.StorageType.OWN_POST;
    var COMPRESS_ROOMS = c.StorageType.COMPRESS_ROOMS;

    if (content.values[type] !== undefined) {
        func(content.values[type]);
        return;
    }

    var get = c.getDefaultValues();

    chrome.storage.sync.get(get
            , function(items) {
                var hideListString = items[c.HIDE_LIST_KEY];
                var ignoreListString = items[c.IGNORE_LIST_KEY];

                content.values[HIDE] = hideListString.split("\n");
                content.values[IGNORE] = ignoreListString.split("\n");
                content.values[HIDE_USER] = items[c.HIDE_USER_ICON_KEY];
                content.values[HIDE_ROOM] = items[c.HIDE_ROOM_ICON_KEY];
                content.values[USER_COLOR] = items[c.USER_NAME_COLOR_KEY];
                content.values[OWN_POST] = items[c.GRAY_OWN_POST_KEY];
                content.values[COMPRESS_ROOMS] = items[c.COMPRESS_ROOMS_KEY];

                func(content.values[type]);
            });
}

content.isMention_ = function(room) {
    var mention = room.getElementsByClassName("_mentionLabel");
    return mention.length > 0;
}

content.getRooms_ = function() {
    var rooms = document.getElementById("_roomListItems").childNodes;
    var validRooms = {};
    for (var i in rooms) {
        var room = rooms[i];
        if (room instanceof HTMLElement) {
            var name = room.getAttribute("aria-label");
            validRooms[name] = room;
        }
    }
    return validRooms;
}

content.hideRoomIcons_ = function() {
    content.getValueFromStorage_(function(isHideRoom) {
        if (!isHideRoom) {
            return;
        }
        var rooms = content.getRooms_();
        for (var k in rooms) {
            var room = rooms[k];
            var icon = room.getElementsByClassName("roomIcon");
            var meta = room.getElementsByClassName("chatListMeta");
            if (icon.length > 0) {
                icon[0].style = "display: none";
            }
            if (meta.length > 0) {
                meta[0].className = "";
            }
        }
    }, constants.StorageType.HIDE_ROOM);
}

content.fixTimelineLayout_ = function() {
    var timelines = document.getElementById("_timeLine").childNodes;
    for (var i in timelines) {
        var timeline = timelines[i];
        var name = timeline.className;
        if (name !== undefined && name.includes("chatTimeLineMessage")) {
            var nameContainer = timeline.getElementsByClassName("_speakerName chatName");
            content.hideUserIcon_(timeline);
            var org = timeline.getElementsByClassName("chatNameOrgname");
            var span = nameContainer[0].getElementsByTagName("span");
            if (org.length > 0) {
                org[0].style = "display: none";
            }
            if (timeline.className.includes("chatTimeLineMessageMine")) {
                content.changeGrayOfOwnPosts_(timeline, span);
            } else {
                content.changeNameColor_(span);
            }
        }
    }
}

content.hideUserIcon_ = function(timeline) {
    content.getValueFromStorage_(function(isHideUser) {
        if (!isHideUser) {
            return;
        }
        var message = timeline.getElementsByClassName("chatTimeLineMessageArea");
        var avator = timeline.getElementsByClassName("avatarSpeaker");
        if (avator.length > 0) {
            avator[0].style = "height: 0px; width: 0px";
            var image = avator[0].getElementsByTagName("img");
            image[0].style = "height: 0px; width: 0px";
        }
        message[0].style = "padding: 0px";
    }, constants.StorageType.HIDE_USER);
}

content.changeGrayOfOwnPosts_ = function(timeline, span) {
    content.getValueFromStorage_(function(isOwnPost) {
        if (!isOwnPost) {
            content.changeNameColor_(span);
            return;
        }
        if (span.length > 0) {
            span[0].style = "color: gray";
        }
        var pre = timeline.getElementsByTagName("pre");
        if (pre.length > 0) {
            pre[0].style = "color: gray";
            var repDiv = pre[0].getElementsByClassName("chatTimeLineReply _replyMessage");
            if (repDiv.length > 0) {
                repDiv[0].style = "background: gray";
            }
            var toSpan = pre[0].getElementsByClassName("chatTimeLineTo");
            if (toSpan.length > 0) {
                toSpan[0].style = "background: gray";
            }
        }
    }, constants.StorageType.OWN_POST);
}

content.changeNameColor_ = function(span) {
    content.getValueFromStorage_(function(userColor) {
        if (!userColor.startsWith("#")) {
            return;
        }
        if (span.length > 0) {
            span[0].style = "color: " + userColor;
        }
    }, constants.StorageType.USER_COLOR);
}

content.fixRoomLayout_ = function(mutations) {
    mutations.forEach(function(mutation) {
        var nodes = mutation.addedNodes;
        if (nodes.length > 0) {
            if (nodes[0].className.includes("_roomTitleText")) {
                nodes[0].style = "font-size: small";
            }
            if (nodes[1].className.includes("_pin")) {
                nodes[1].style = "display: none";
            }
        }
    });
}

content.init_();
<|endoftext|>