<commit_before>import Foo from './Foo';

export default new Foo();
<commit_msg>case sensitive filenames<commit_after>import Foo from './foo';

export default new Foo();
<|endoftext|>


<commit_before>import * as DS from './delaney';
import { seq } from '../common/lazyseq';
import { Partition } from '../common/unionFind';

const _assert = (condition, message) => {
  if (!condition)
    throw new Error(message || 'assertion error');
};

const _fold = (partition, a, b, matchP, spreadFn) => {
  const p = partition.clone();
  let q = [[a, b]];

  while (q.length) {
    const [x, y] = q.shift();

    if (!matchP(x, y))
      return;
    else if (p.find(x) == p.find(y))
      continue;
    else {
      p.union(x, y);
      q = q.concat(spreadFn(x, y));
    }
  }

  return p;
};

const _typeMap = ds => {
  const result = {};

  for (const D of ds.elements())
    result[D] = [];

  for (const i of ds.indices()) {
    for (const j of ds.indices()) {
      for (const D of DS.orbitReps2(ds, i, j)) {
        const m = DS.m(ds, i, j, D);
        for (const E of DS.orbit2(ds, i, j, D))
          result[E].push(m);
      }
    }
  }

  return result;
};

const typePartitionFolder = ds => {
  const tm = _typeMap(ds);
  const match  = (D, E) => tm[D] <= tm[E] && tm[D] >= tm[E];
  const spread = (D, E) => ds.indices().map(i => [ds.s(i, D), ds.s(i, E)]);

  return (p, D, E) => _fold(p, D, E, match, spread);
};

export const isMinimal = ds => {
  const folder = typePartitionFolder(ds);
  const p = new Partition();
  const D0 = ds.elements()[0];

  return ds.elements().slice(1).every(D => folder(p, D0, D) === undefined);
};

export const typePartition = ds => {
  const folder = typePartitionFolder(ds);
  const p = new Partition();
  const D0 = ds.elements()[0];

  return ds.elements().slice(1).reduce((p, D) => folder(p, D0, D) || p, p);
};

const Traversal = function*(ds, indices, seeds) {
  const seedsLeft = (seeds.constructor == Array) ? seeds.slice() : seeds.toJS();
  const todo = {};
  const seen = {};
  indices = (indices.constructor == Array) ? indices : indices.toJS();
  indices.forEach(i => { seen[i] = {}; todo[i] = [] });
  seen[root] = {};

  while (true) {
    let i = null;
    let D = null;
    for (const k in indices) {
      if (todo[indices[k]].length > 0) {
        i = indices[k];
        D = todo[i].shift();
        break;
      }
    }

    if (D == null && seedsLeft.length > 0)
      D = seedsLeft.pop();

    if (D == null)
      return;

    if (!seen[i][D]) {
      const Di = (i == root) ? D : ds.s(i, D);

      indices.forEach(i => {
        if (!seen[i][Di]) {
          if (i < 2)
            todo[i].unshift(Di);
          else
            todo[i].push(Di);
        }
      });

      seen[root][Di] = true;
      seen[i][D]     = true;
      seen[i][Di]    = true;

      yield [D, i, Di];
    }
  }
};

export const traversal = (ds, indices, seeds) =>
  seq(Traversal(ds, indices, seeds));

const root = traversal.root = null;

export const orbitReps = (ds, indices, seeds) =>
  traversal(ds, indices, seeds || ds.elements())
  .filter(e => e[1] == root)
  .map(e => e[2]);

export const orbits = (ds, indices, seeds) => {
  const seen = {};
  const result = [];

  for (const [_, i, D] of traversal(ds, indices, seeds || ds.elements())) {
    if (i == root)
      result.push([]);

    if (D && !seen[D]) {
      seen[D] = true;
      result[result.length - 1].push(D);
    }
  }

  return result;
};

export const isConnected = ds => orbitReps(ds, ds.indices()).length < 2;

export const orbit = (ds, indices, seed) => {
  const seen = {};
  const result = [];

  for (const [_, i, D] of traversal(ds, indices, [seed])) {
    if (D && !seen[D]) {
      seen[D] = true;
      result.push(D);
    }
  }

  return result;
};

export const partialOrientation = ds => {
  const ori = new Array(ds.size + 1);

  for (const [Di, i, D] of traversal(ds, ds.indices(), ds.elements())) {
    if (D && !ori[D])
      ori[D] = i == root ? 1 : -ori[Di];
  }

  return ori;
};

const _forAllEdges = (ds, test) =>
  ds.elements().every(D => ds.indices().every(i => test(D, i)));

export const isLoopless = ds => _forAllEdges(ds, (D, i) => D != ds.s(i, D));

export const isOriented = ds => {
  const ori = partialOrientation(ds);
  return _forAllEdges(ds, (D, i) => ori[D] != ori[ds.s(i, D)]);
};

export const isWeaklyOriented = ds => {
  const ori = partialOrientation(ds);
  const test = (D, Di) => D == Di || ori[D] != ori[Di];
  return _forAllEdges(ds, (D, i) => test(D, ds.s(i, D)));
};

const _protocol = (ds, idcs, gen) => {
  const buffer = [];
  const emap = {};
  let n = 1;

  const _advance = () => {
    const next = gen.next();
    if (next.done)
      return false;
    const entry = next.value;

    const Di = entry[0];
    const i = entry[1];
    const D = entry[2];
    const E = emap[D] || n;

    if (E == n)
      emap[D] = E;

    buffer.push(i == root ? -1 : i);
    buffer.push(emap[Di]);

    if (i != root)
      buffer.push(E);

    if (E == n) {
      for (let i = 0; i < idcs.length - 1; ++i)
        buffer.push(ds.v(idcs[i], idcs[i+1], D));
      ++n;
    }

    return true;
  };

  return {
    get(i) {
      while (buffer.length <= i && _advance())
        ;
      return buffer[i];
    },
    content(fn) {
      while (_advance())
        ;
      return buffer;
    }
  };
};

export const invariant = ds => {
  const idcs = DS.indices(ds);
  let best = null;

  ds.elements().forEach(D0 => {
    const trav = _protocol(ds, idcs, Traversal(ds, idcs, [D0]));

    if (best == null)
      best = trav;
    else {
      for (let i = 0; ; ++i) {
        const next = trav.get(i);
        if (next == undefined)
          break;

        const d = next - best.get(i);
        if (d != 0) {
          if (d < 0)
            best = trav;
          break;
        }
      }
    }
  });

  return best.content();
};

export const morphism = (src, srcD0, img, imgD0) => {
  _assert(isConnected(src), 'source symbol must be connected');
  _assert(src.dim == img.dim, 'dimensions must be equal');

  const idcs = src.indices();
  const tSrc = _typeMap(src);
  const tImg = _typeMap(img);
  const eq = (as, bs) => as <= bs && bs <= as;

  const q = [[srcD0, imgD0]];
  const m = new Array(src.size + 1);
  m[srcD0] = imgD0;

  while (q.length) {
    const [D, E] = q.shift();

    for (const i of idcs) {
      const Di = src.s(i, D);
      const Ei = img.s(i, E);

      if (Di != null || Ei != null) {
        if (m[Di] == null) {
          _assert(
            eq(tSrc[Di], tImg[Ei]),
            `expected type[${Ei}] to be ${tSrc[Di]}, got ${tImg[Ei]}`
          )

          q.push([Di, Ei]);
          m[Di] = Ei;
        }
        else
          _assert(
            m[Di] == Ei,
            `expected m[${Di}] to be ${Ei}, got ${m[Di]}`
          )
      }
    }
  }

  return m;
};

export const automorphisms = ds => {
  _assert(isConnected(ds), 'symbol must be connected');
  const elms = ds.elements();
  if (elms.length) {
    const D = elms[0];
    return elms.map(E => morphism(ds, D, ds, E)).filter(m => m != null);
  }
};

if (require.main == module) {
  Array.prototype.toString = function() {
    return '[ ' + this.map(x => x && x.toString()).join(', ') + ' ]';
  };

  const test = ds => {
    const is = fn => fn(ds) ? 'is' : 'is not';

    console.log(`ds = ${ds}`);
    console.log();

    console.log(`    symbol ${is(isConnected)} connected.`);
    console.log(`    symbol ${is(isMinimal)} minimal.`);
    console.log(`    symbol ${is(isLoopless)} loopless.`);
    console.log(`    symbol ${is(isOriented)} oriented.`);
    console.log(`    symbol ${is(isWeaklyOriented)} weakly oriented.`);
    console.log(`    type partition: ${typePartition(ds)}`);

    const trav = traversal(ds, ds.indices(), ds.elements());
    console.log(`    traversal: ${trav}`);
    console.log(`    invariant: ${invariant(ds)}`);
    console.log();

    console.log(`    0,1 orbit reps: ${orbitReps(ds, [0, 1])}`);
    console.log(`    1,2 orbit reps: ${orbitReps(ds, [1, 2])}`);
    console.log(`    0,2 orbit reps: ${orbitReps(ds, [0, 2])}`);
    console.log();

    console.log(`    0,1 orbits: ${orbits(ds, [0, 1])}`);
    console.log(`    1,2 orbits: ${orbits(ds, [1, 2])}`);
    console.log(`    0,2 orbits: ${orbits(ds, [0, 2])}`);
    console.log();

    console.log(`    0,1 orbit of 1: ${orbit(ds, [0, 1], 1)}`);
    console.log(`    1,2 orbit of 1: ${orbit(ds, [1, 2], 1)}`);
    console.log(`    0,2 orbit of 1: ${orbit(ds, [0, 2], 1)}`);
    console.log();

    const ori = partialOrientation(ds);
    console.log(`    partial orientation: ${ori}`);
    console.log();

    console.log(`    automorphisms: ${automorphisms(ds)}`);
    console.log();
    console.log();
  };

  test(DS.parse(`<1.1:24:
                2 4 6 8 10 12 14 16 18 20 22 24,
                16 3 5 7 9 11 13 15 24 19 21 23,
                10 9 20 19 14 13 22 21 24 23 18 17:
                8 4,3 3 3 3>`));

  test(DS.parse('<1.1:3:1 2 3,1 3,2 3:4 8,3>'));
  test(DS.parse('<1.1:2 3:2,1 2,1 2,2:6,3 2,6>'));
  test(DS.parse('<1.1:6:4 6 5,5 4 6,4 6 5:3,6>'));
}
<commit_msg>dsymbols/properties: do not throw exceptions if morphism() fails<commit_after>import * as DS from './delaney';
import { seq } from '../common/lazyseq';
import { Partition } from '../common/unionFind';

const _assert = (condition, message) => {
  if (!condition)
    throw new Error(message || 'assertion error');
};

const _fold = (partition, a, b, matchP, spreadFn) => {
  const p = partition.clone();
  let q = [[a, b]];

  while (q.length) {
    const [x, y] = q.shift();

    if (!matchP(x, y))
      return;
    else if (p.find(x) == p.find(y))
      continue;
    else {
      p.union(x, y);
      q = q.concat(spreadFn(x, y));
    }
  }

  return p;
};

const _typeMap = ds => {
  const result = {};

  for (const D of ds.elements())
    result[D] = [];

  for (const i of ds.indices()) {
    for (const j of ds.indices()) {
      for (const D of DS.orbitReps2(ds, i, j)) {
        const m = DS.m(ds, i, j, D);
        for (const E of DS.orbit2(ds, i, j, D))
          result[E].push(m);
      }
    }
  }

  return result;
};

const typePartitionFolder = ds => {
  const tm = _typeMap(ds);
  const match  = (D, E) => tm[D] <= tm[E] && tm[D] >= tm[E];
  const spread = (D, E) => ds.indices().map(i => [ds.s(i, D), ds.s(i, E)]);

  return (p, D, E) => _fold(p, D, E, match, spread);
};

export const isMinimal = ds => {
  const folder = typePartitionFolder(ds);
  const p = new Partition();
  const D0 = ds.elements()[0];

  return ds.elements().slice(1).every(D => folder(p, D0, D) === undefined);
};

export const typePartition = ds => {
  const folder = typePartitionFolder(ds);
  const p = new Partition();
  const D0 = ds.elements()[0];

  return ds.elements().slice(1).reduce((p, D) => folder(p, D0, D) || p, p);
};

const Traversal = function*(ds, indices, seeds) {
  const seedsLeft = (seeds.constructor == Array) ? seeds.slice() : seeds.toJS();
  const todo = {};
  const seen = {};
  indices = (indices.constructor == Array) ? indices : indices.toJS();
  indices.forEach(i => { seen[i] = {}; todo[i] = [] });
  seen[root] = {};

  while (true) {
    let i = null;
    let D = null;
    for (const k in indices) {
      if (todo[indices[k]].length > 0) {
        i = indices[k];
        D = todo[i].shift();
        break;
      }
    }

    if (D == null && seedsLeft.length > 0)
      D = seedsLeft.pop();

    if (D == null)
      return;

    if (!seen[i][D]) {
      const Di = (i == root) ? D : ds.s(i, D);

      indices.forEach(i => {
        if (!seen[i][Di]) {
          if (i < 2)
            todo[i].unshift(Di);
          else
            todo[i].push(Di);
        }
      });

      seen[root][Di] = true;
      seen[i][D]     = true;
      seen[i][Di]    = true;

      yield [D, i, Di];
    }
  }
};

export const traversal = (ds, indices, seeds) =>
  seq(Traversal(ds, indices, seeds));

const root = traversal.root = null;

export const orbitReps = (ds, indices, seeds) =>
  traversal(ds, indices, seeds || ds.elements())
  .filter(e => e[1] == root)
  .map(e => e[2]);

export const orbits = (ds, indices, seeds) => {
  const seen = {};
  const result = [];

  for (const [_, i, D] of traversal(ds, indices, seeds || ds.elements())) {
    if (i == root)
      result.push([]);

    if (D && !seen[D]) {
      seen[D] = true;
      result[result.length - 1].push(D);
    }
  }

  return result;
};

export const isConnected = ds => orbitReps(ds, ds.indices()).length < 2;

export const orbit = (ds, indices, seed) => {
  const seen = {};
  const result = [];

  for (const [_, i, D] of traversal(ds, indices, [seed])) {
    if (D && !seen[D]) {
      seen[D] = true;
      result.push(D);
    }
  }

  return result;
};

export const partialOrientation = ds => {
  const ori = new Array(ds.size + 1);

  for (const [Di, i, D] of traversal(ds, ds.indices(), ds.elements())) {
    if (D && !ori[D])
      ori[D] = i == root ? 1 : -ori[Di];
  }

  return ori;
};

const _forAllEdges = (ds, test) =>
  ds.elements().every(D => ds.indices().every(i => test(D, i)));

export const isLoopless = ds => _forAllEdges(ds, (D, i) => D != ds.s(i, D));

export const isOriented = ds => {
  const ori = partialOrientation(ds);
  return _forAllEdges(ds, (D, i) => ori[D] != ori[ds.s(i, D)]);
};

export const isWeaklyOriented = ds => {
  const ori = partialOrientation(ds);
  const test = (D, Di) => D == Di || ori[D] != ori[Di];
  return _forAllEdges(ds, (D, i) => test(D, ds.s(i, D)));
};

const _protocol = (ds, idcs, gen) => {
  const buffer = [];
  const emap = {};
  let n = 1;

  const _advance = () => {
    const next = gen.next();
    if (next.done)
      return false;
    const entry = next.value;

    const Di = entry[0];
    const i = entry[1];
    const D = entry[2];
    const E = emap[D] || n;

    if (E == n)
      emap[D] = E;

    buffer.push(i == root ? -1 : i);
    buffer.push(emap[Di]);

    if (i != root)
      buffer.push(E);

    if (E == n) {
      for (let i = 0; i < idcs.length - 1; ++i)
        buffer.push(ds.v(idcs[i], idcs[i+1], D));
      ++n;
    }

    return true;
  };

  return {
    get(i) {
      while (buffer.length <= i && _advance())
        ;
      return buffer[i];
    },
    content(fn) {
      while (_advance())
        ;
      return buffer;
    }
  };
};

export const invariant = ds => {
  const idcs = DS.indices(ds);
  let best = null;

  ds.elements().forEach(D0 => {
    const trav = _protocol(ds, idcs, Traversal(ds, idcs, [D0]));

    if (best == null)
      best = trav;
    else {
      for (let i = 0; ; ++i) {
        const next = trav.get(i);
        if (next == undefined)
          break;

        const d = next - best.get(i);
        if (d != 0) {
          if (d < 0)
            best = trav;
          break;
        }
      }
    }
  });

  return best.content();
};

export const morphism = (src, srcD0, img, imgD0) => {
  _assert(isConnected(src), 'source symbol must be connected');
  _assert(src.dim == img.dim, 'dimensions must be equal');

  const idcs = src.indices();
  const tSrc = _typeMap(src);
  const tImg = _typeMap(img);
  const eq = (as, bs) => as <= bs && bs <= as;

  const q = [[srcD0, imgD0]];
  const m = new Array(src.size + 1);
  m[srcD0] = imgD0;

  while (q.length) {
    const [D, E] = q.shift();

    for (const i of idcs) {
      const Di = src.s(i, D);
      const Ei = img.s(i, E);

      if (Di != null || Ei != null) {
        if (m[Di] == null && eq(tSrc[Di], tImg[Ei])) {
          q.push([Di, Ei]);
          m[Di] = Ei;
        }
        else if (m[Di] != Ei)
          return null;
      }
    }
  }

  return m;
};

export const automorphisms = ds => {
  _assert(isConnected(ds), 'symbol must be connected');
  const elms = ds.elements();
  if (elms.length) {
    const D = elms[0];
    return elms.map(E => morphism(ds, D, ds, E)).filter(m => m != null);
  }
};

if (require.main == module) {
  Array.prototype.toString = function() {
    return '[ ' + this.map(x => x && x.toString()).join(', ') + ' ]';
  };

  const test = ds => {
    const is = fn => fn(ds) ? 'is' : 'is not';

    console.log(`ds = ${ds}`);
    console.log();

    console.log(`    symbol ${is(isConnected)} connected.`);
    console.log(`    symbol ${is(isMinimal)} minimal.`);
    console.log(`    symbol ${is(isLoopless)} loopless.`);
    console.log(`    symbol ${is(isOriented)} oriented.`);
    console.log(`    symbol ${is(isWeaklyOriented)} weakly oriented.`);
    console.log(`    type partition: ${typePartition(ds)}`);

    const trav = traversal(ds, ds.indices(), ds.elements());
    console.log(`    traversal: ${trav}`);
    console.log(`    invariant: ${invariant(ds)}`);
    console.log();

    console.log(`    0,1 orbit reps: ${orbitReps(ds, [0, 1])}`);
    console.log(`    1,2 orbit reps: ${orbitReps(ds, [1, 2])}`);
    console.log(`    0,2 orbit reps: ${orbitReps(ds, [0, 2])}`);
    console.log();

    console.log(`    0,1 orbits: ${orbits(ds, [0, 1])}`);
    console.log(`    1,2 orbits: ${orbits(ds, [1, 2])}`);
    console.log(`    0,2 orbits: ${orbits(ds, [0, 2])}`);
    console.log();

    console.log(`    0,1 orbit of 1: ${orbit(ds, [0, 1], 1)}`);
    console.log(`    1,2 orbit of 1: ${orbit(ds, [1, 2], 1)}`);
    console.log(`    0,2 orbit of 1: ${orbit(ds, [0, 2], 1)}`);
    console.log();

    const ori = partialOrientation(ds);
    console.log(`    partial orientation: ${ori}`);
    console.log();

    console.log(`    automorphisms: ${automorphisms(ds)}`);
    console.log();
    console.log();
  };

  test(DS.parse(`<1.1:24:
                2 4 6 8 10 12 14 16 18 20 22 24,
                16 3 5 7 9 11 13 15 24 19 21 23,
                10 9 20 19 14 13 22 21 24 23 18 17:
                8 4,3 3 3 3>`));

  test(DS.parse('<1.1:3:1 2 3,1 3,2 3:4 8,3>'));
  test(DS.parse('<1.1:2 3:2,1 2,1 2,2:6,3 2,6>'));
  test(DS.parse('<1.1:6:4 6 5,5 4 6,4 6 5:3,6>'));
}
<|endoftext|>


<commit_before>import hasOwnProperty from './hasOwnProperty';

export default (table, options) => {
  if (typeof options !== 'object') return table;

  let row = table;

  if (hasOwnProperty(options, 'filter')) {
    row = row.filter(options.filter);
  }

  if (hasOwnProperty(options, 'pluck')) {
    // always pluck the id
    row = row.pluck({
      ...options.include,
      id: true,
    });
  }

  if (hasOwnProperty(options, 'without')) {
    // disallow forgoing the id
    row = row.without({
      ...options.without,
      id: false,
    });
  }

  if (hasOwnProperty(options, 'between')) {
    row = row.between(options.between);
  }

  if (hasOwnProperty(options, 'skip')) {
    row = row.skip(options.skip);
  }

  if (hasOwnProperty(options, 'limit')) {
    row = row.limit(options.limit);
  }

  if (hasOwnProperty(options, 'orderBy')) {
    row = row.orderBy(options.orderBy);
  }

  return row;
};
<commit_msg>Refactor `without` option<commit_after>/* eslint-disable no-param-reassign */
import hasOwnProperty from './hasOwnProperty';

export default (table, options) => {
  if (typeof options !== 'object') return table;

  let row = table;

  if (hasOwnProperty(options, 'filter')) {
    row = row.filter(options.filter);
  }

  if (hasOwnProperty(options, 'pluck')) {
    // always pluck the id
    row = row.pluck({
      ...options.include,
      id: true,
    });
  }

  if (hasOwnProperty(options, 'without')) {
    // disallow forgoing the id
    delete options.without.id;
    row = row.without(options.without);
  }

  if (hasOwnProperty(options, 'between')) {
    row = row.between(options.between);
  }

  if (hasOwnProperty(options, 'skip')) {
    row = row.skip(options.skip);
  }

  if (hasOwnProperty(options, 'limit')) {
    row = row.limit(options.limit);
  }

  if (hasOwnProperty(options, 'orderBy')) {
    row = row.orderBy(options.orderBy);
  }

  return row;
};
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import Pixel from './Pixel';
import { EMPTY, OUTLINE, SHAPE } from './actions';
import styles from './Editor.css';
import fonts from '../utils/fonts';
import { Card, CardText, CardTitle } from 'react-toolbox/lib/card';

export default class Editor extends Component {
  static propTypes = {
    setPixel: PropTypes.func.isRequired,
    outline: PropTypes.arrayOf(PropTypes.number).isRequired,
    shape: PropTypes.arrayOf(PropTypes.number).isRequired,
    fontSize: PropTypes.number.isRequired,
  }

  _setPixel = (row, column, type) => {
    this.props.setPixel(row, column, type);
  }

  render() {
    const { height, width } = fonts.getFont(this.props.fontSize).dimensions;

    const pixels = [...Array(height)].map((_, row) => {
      const shape = this.props.shape[row];
      const outline = this.props.outline[row];

      const rowPixels = [...Array(width)].map((__, column) => {
        const key = `${row}${column}`;
        if (shape & outline & Math.pow(2, column)) {
          return (
            <Pixel key={key} setPixel={this._setPixel.bind(this, row, column)} type={OUTLINE} />
          );
        }
        if (shape & Math.pow(2, column)) {
          return <Pixel key={key} setPixel={this._setPixel.bind(this, row, column)} type={SHAPE} />;
        }
        return <Pixel key={key} setPixel={this._setPixel.bind(this, row, column)} type={EMPTY} />;
      });

      return (

          {rowPixels}

{row + 1}

      );
    });

    const columnNumbers = [...Array(width)].map((_, i) => (

{i + 1}

    ));

    return (
      <Card>
        <CardTitle
          title="pixler"
          subtitle="left click to set shape, right click to set outline, second click to clear"
        />
        <CardText>

            {columnNumbers}

          {pixels}
        </CardText>
      </Card>
    );
  }
}
<commit_msg>fix(pixler): mirror pixel rendering to match osd/preview<commit_after>import React, { Component, PropTypes } from 'react';
import Pixel from './Pixel';
import { EMPTY, OUTLINE, SHAPE } from './actions';
import styles from './Editor.css';
import fonts from '../utils/fonts';
import { Card, CardText, CardTitle } from 'react-toolbox/lib/card';

export default class Editor extends Component {
  static propTypes = {
    setPixel: PropTypes.func.isRequired,
    outline: PropTypes.arrayOf(PropTypes.number).isRequired,
    shape: PropTypes.arrayOf(PropTypes.number).isRequired,
    fontSize: PropTypes.number.isRequired,
  }

  _setPixel = (row, column, type) => {
    this.props.setPixel(row, column, type);
  }

  render() {
    const { height, width } = fonts.getFont(this.props.fontSize).dimensions;

    const pixels = [...Array(height)].map((_, row) => {
      const shape = this.props.shape[row];
      const outline = this.props.outline[row];

      const rowPixels = [...Array(width)].map((__, i) => {
        const column = width - i;
        const key = `${row}${column}`;
        let type = null;
        if (shape & outline & Math.pow(2, column)) {
          type = OUTLINE;
        } else if (shape & Math.pow(2, column)) {
          type = SHAPE;
        } else {
          type = EMPTY;
        }

        return (<Pixel key={key} setPixel={this._setPixel.bind(this, row, column)} type={type} />);
      });

      return (

          {rowPixels}

{row + 1}

      );
    });

    const columnNumbers = [...Array(width)].map((_, i) => (

{i + 1}

    ));

    return (
      <Card>
        <CardTitle
          title="pixler"
          subtitle="left click to set shape, right click to set outline, second click to clear"
        />
        <CardText>

            {columnNumbers}

          {pixels}
        </CardText>
      </Card>
    );
  }
}
<|endoftext|>


<commit_before>'use strict'

const fs = require('fs')
const os = require('os')
const path = require('path')

const solReader = require('xat-client/src/utils/sol-reader')

const mkdir = (dirName) => {
  try {
    fs.mkdirSync(dirName)
  } catch (e) {
    if (e.code !== 'EEXIST') {
      throw e
    }
  }
}

module.exports =
class ConfigurationManager {
  constructor() {
    this.innerProps = ['innerProps', 'fromSol', 'paths', 'save']

    const home = os.homedir()
    const configDir = path.join(home, '.xatclirc')
    const configFile = path.join(configDir, 'config.json')
    const profilesPath = path.join(configDir, 'profiles')

    mkdir(configDir)
    mkdir(profilesPath)

    let config = null
    try {
      fs.lstat(configFile)
      config = fs.readFileSync(configFile)
    } catch (e) {
      const defaultConfig = path.join(__dirname, '../config.json')
      const configData = fs.readFileSync(defaultConfig)

      fs.writeFileSync(configFile, configData)

      config = configData
    }

    this.paths = {
      profiles: profilesPath,
      configFile,
    }

    config = JSON.parse(config)
    for (const key in config) {
      this[key] = config[key]
    }

    if (this.user.todo.w_useroom == null) {
      this.user.todo.w_useroom = 1
    }
  }

  fromSol(fileName) {
    return new Promise((resolve, reject) => {
      fs.readFile(fileName, (err, data) => {
        if (err) return reject(err)
        const sol = solReader.read(data)

        this.user.todo = sol

        const storedName = path.join(this.paths.profiles, new Date().getTime() + '.json')
        fs.writeFile(storedName, JSON.stringify(sol), (err) => {
          if (err) return reject(err)
          resolve()
        })
      })
    })
  }
}
<commit_msg>Make "fromsol" fitting xat-client API<commit_after>'use strict'

const fs = require('fs')
const os = require('os')
const path = require('path')

const solReader = require('xat-client/src/utils/sol-reader')

const mkdir = (dirName) => {
  try {
    fs.mkdirSync(dirName)
  } catch (e) {
    if (e.code !== 'EEXIST') {
      throw e
    }
  }
}

module.exports =
class ConfigurationManager {
  constructor() {
    this.innerProps = ['innerProps', 'fromSol', 'paths', 'save']

    const home = os.homedir()
    const configDir = path.join(home, '.xatclirc')
    const configFile = path.join(configDir, 'config.json')
    const profilesPath = path.join(configDir, 'profiles')

    mkdir(configDir)
    mkdir(profilesPath)

    let config = null
    try {
      fs.lstat(configFile)
      config = fs.readFileSync(configFile)
    } catch (e) {
      const defaultConfig = path.join(__dirname, '../config.json')
      const configData = fs.readFileSync(defaultConfig)

      fs.writeFileSync(configFile, configData)

      config = configData
    }

    this.paths = {
      profiles: profilesPath,
      configFile,
    }

    config = JSON.parse(config)
    for (const key in config) {
      this[key] = config[key]
    }

    if (this.user.todo.w_useroom == null) {
      this.user.todo.w_useroom = 1
    }
  }

  fromSol(fileName) {
    return new Promise((resolve, reject) => {
      fs.readFile(fileName, (err, data) => {
        if (err) return reject(err)
        const sol = solReader.read(data)

        for (const key in sol) {
          let clientKey = key
          if (key === 'w_k1c') {
            clientKey = 'w_k1'
          }

          let value = sol[key]
          if (typeof value === 'number') {
            value = String(value)
          }

          this.user.todo[clientKey] = value
        }

        const storedName = path.join(this.paths.profiles, new Date().getTime() + '.json')
        fs.writeFile(storedName, JSON.stringify(sol), (err) => {
          if (err) return reject(err)
          resolve()
        })
      })
    })
  }
}
<|endoftext|>


<commit_before>/**
 * @class Denkmal_Component_HeaderBar
 * @extends Denkmal_Component_Abstract
 */
var Denkmal_Component_HeaderBar = Denkmal_Component_Abstract.extend({

	/** @type String */
	_class: 'Denkmal_Component_HeaderBar',

	events: {
		'click .menu.dates a': function(event) {
			var url = $(event.currentTarget).attr('href');
			return this.activateMenu(url);
		}
	},

	/**
	 * @param {String} url
	 */
	activateMenu: function(url) {
		var pageEvents = cm.findView('Denkmal_Page_Events');
		if (!pageEvents) {
			return true;
		}
		return !pageEvents.showPane(url);
	}
});
<commit_msg>use clickNoMeta in headerBar<commit_after>/**
 * @class Denkmal_Component_HeaderBar
 * @extends Denkmal_Component_Abstract
 */
var Denkmal_Component_HeaderBar = Denkmal_Component_Abstract.extend({

	/** @type String */
	_class: 'Denkmal_Component_HeaderBar',

	events: {
		'clickNoMeta .menu.dates a': function(event) {
			var url = $(event.currentTarget).attr('href');
			return this.activateMenu(url);
		}
	},

	/**
	 * @param {String} url
	 */
	activateMenu: function(url) {
		var pageEvents = cm.findView('Denkmal_Page_Events');
		if (!pageEvents) {
			return true;
		}
		return !pageEvents.showPane(url);
	}
});
<|endoftext|>


<commit_before>'use strict';

// server-side socket behaviour
var ios = null; // io is already taken in express
var util = require('bitcore').util;
var mdb = require('../../lib/MessageDb').default();
var microtime = require('microtime');
var enableMessageBroker;

module.exports.init = function(io_ext, config) {
  enableMessageBroker = config ? config.enableMessageBroker : false;
  ios = io_ext;
  if (ios) {
    // when a new socket connects
    ios.sockets.on('connection', function(socket) {
      console.log("New connection from " + socket.request.connection.remoteAddress + ":" + socket.request.connection.remotePort);
      // when it subscribes, make it join the according room
      socket.on('subscribe', function(topic) {
        if (socket.rooms.length === 1) {
          console.log('subscribe to ' + topic);
          socket.join(topic);
        }
      });

      if (enableMessageBroker) {
        // when it requests sync, send him all pending messages
        socket.on('sync', function(ts) {
          var rooms = socket.rooms;
          if (rooms.length !== 2) {
            socket.emit('insight-error', 'Must subscribe with public key before syncing');
            return;
          }
          var to = rooms[1];
          var upper_ts = Math.round(microtime.now());
          mdb.getMessages(to, ts, upper_ts, function(err, messages) {
            if (err) {
              throw new Error('Couldn\'t get messages on sync request: ' + err);
            }
            for (var i = 0; i < messages.length; i++) {
              broadcastMessage(messages[i], socket);
            }
          });
        });

        // when it sends a message, add it to db
        socket.on('message', function(m) {
          mdb.addMessage(m, function(err) {
            if (err) {
              throw new Error('Couldn\'t add message to database: ' + err);
            }
          });
        });
      }
    });
    if (enableMessageBroker)
      mdb.on('message', broadcastMessage);
  }
};

var simpleTx = function(tx) {
  return {
    txid: tx
  };
};

var fullTx = function(tx) {
  var t = {
    txid: tx.txid,
    size: tx.size,
  };
  // Outputs
  var valueOut = 0;
  tx.vout.forEach(function(o) {
    valueOut += o.valueSat;
  });

  t.valueOut = (valueOut.toFixed(8) / util.COIN);
  return t;
};

module.exports.broadcastTx = function(tx) {
  if (ios) {
    var t = (typeof tx === 'string') ? simpleTx(tx) : fullTx(tx);
    ios.sockets.in('inv').emit('tx', t);
  }
};

module.exports.broadcastBlock = function(block) {
  if (ios)
    ios.sockets.in('inv').emit('block', block);
};

module.exports.broadcastAddressTx = function(txid, address) {
  if (ios) {
    ios.sockets.in(address).emit(address, txid);
  }
};

module.exports.broadcastSyncInfo = function(historicSync) {
  if (ios)
    ios.sockets.in('sync').emit('status', historicSync);
};

var broadcastMessage = module.exports.broadcastMessage = function(message, socket) {
  if (ios) {
    var s = socket || ios.sockets.in(message.to);
    s.emit('message', message);
  }

}
<commit_msg>add debug logs<commit_after>'use strict';

// server-side socket behaviour
var ios = null; // io is already taken in express
var util = require('bitcore').util;
var mdb = require('../../lib/MessageDb').default();
var microtime = require('microtime');
var enableMessageBroker;

module.exports.init = function(io_ext, config) {
  enableMessageBroker = config ? config.enableMessageBroker : false;
  ios = io_ext;
  if (ios) {
    // when a new socket connects
    ios.sockets.on('connection', function(socket) {
      console.log('New connection from ' + socket.request.connection.remotePort);
      // when it subscribes, make it join the according room
      socket.on('subscribe', function(topic) {
        if (socket.rooms.length === 1) {
          console.log('subscribe to ' + topic);
          socket.join(topic);
        }
      });

      if (enableMessageBroker) {
        // when it requests sync, send him all pending messages
        socket.on('sync', function(ts) {
          console.log('Sync requested by ' + socket.request.connection.remotePort);
          var rooms = socket.rooms;
          if (rooms.length !== 2) {
            socket.emit('insight-error', 'Must subscribe with public key before syncing');
            return;
          }
          var to = rooms[1];
          var upper_ts = Math.round(microtime.now());
          mdb.getMessages(to, ts, upper_ts, function(err, messages) {
            if (err) {
              throw new Error('Couldn\'t get messages on sync request: ' + err);
            }
            console.log('\tFound '+messages.length+' message'+(messages.length !== 1?'s':''));
            for (var i = 0; i < messages.length; i++) {
              broadcastMessage(messages[i], socket);
            }
          });
        });

        // when it sends a message, add it to db
        socket.on('message', function(m) {
          console.log('Message sent from ' + m.pubkey +' to '+m.to);
          mdb.addMessage(m, function(err) {
            if (err) {
              throw new Error('Couldn\'t add message to database: ' + err);
            }
          });
        });
      }
    });
    if (enableMessageBroker)
      mdb.on('message', broadcastMessage);
  }
};

var simpleTx = function(tx) {
  return {
    txid: tx
  };
};

var fullTx = function(tx) {
  var t = {
    txid: tx.txid,
    size: tx.size,
  };
  // Outputs
  var valueOut = 0;
  tx.vout.forEach(function(o) {
    valueOut += o.valueSat;
  });

  t.valueOut = (valueOut.toFixed(8) / util.COIN);
  return t;
};

module.exports.broadcastTx = function(tx) {
  if (ios) {
    var t = (typeof tx === 'string') ? simpleTx(tx) : fullTx(tx);
    ios.sockets.in('inv').emit('tx', t);
  }
};

module.exports.broadcastBlock = function(block) {
  if (ios)
    ios.sockets.in('inv').emit('block', block);
};

module.exports.broadcastAddressTx = function(txid, address) {
  if (ios) {
    ios.sockets.in(address).emit(address, txid);
  }
};

module.exports.broadcastSyncInfo = function(historicSync) {
  if (ios)
    ios.sockets.in('sync').emit('status', historicSync);
};

var broadcastMessage = module.exports.broadcastMessage = function(message, socket) {
  if (ios) {
    var s = socket || ios.sockets.in(message.to);
    s.emit('message', message);
  }

}
<|endoftext|>


<commit_before>// TODO: Make this a singleton module

// Make bson available
var BSON = bson().BSON;

// Definition for WebSocketLoader
function WebSocketLoader(wsuri) {
	// Create object if not instance of
	if (!(this instanceof WebSocketLoader)) return new WebSocketLoader(wsuri);

	this.queue = {};

    if ("WebSocket" in window) {
        this.sock = new WebSocket(wsuri);
    } else if ("MozWebSocket" in window) {
        this.sock = new MozWebSocket(wsuri);
    } else {
        console.log("Browser does not support WebSocket!");
    }

    if (this.sock) {
        this.sock.binaryType = "arraybuffer";
        this.sock.onopen = this.OnConnect;
        this.sock.onclose = this.OnClose;
        var that = this;
        this.sock.onmessage = function(e) {
  			var resp = BSON.deserialize(new Uint8Array(e.data));
		    if(resp.hasOwnProperty("success")) {
    			// console.log("Successful request" + resp);
    			if(resp.hasOwnProperty("image")){
        			var whichtile = resp["request"]["tile"]["name"] //  + resp["request"]["tile"]["image"]
        			that.queue[whichtile].src = "data:image/jpg;base64," + btoa(String.fromCharCode.apply(null, resp.image.buffer));
        			delete that.queue[whichtile];
			    }
			} else {
				console.log("Error in request" + resp);
				var whichtile = resp["request"]["tile"]["name"];
    			that.queue[whichtile].src = ''; //  + resp["request"]["tile"]["image"]
    			delete that.queue[whichtile];
			}
	    // console.log("Got: " + JSON.stringify(resp));
		};
        TILELOADER = "websocket";
	}
	else {
		TILELOADER = "http";
	}
};

WebSocketLoader.prototype.OnConnect = function(e) {
    console.log("WebSocketLoader connected ..");
};

WebSocketLoader.prototype.OnClose = function(e) {
    console.log("WebSocketLoader closed (wasClean = " + e.wasClean + ", code = " + e.code + ", reason = '" + e.reason + "')");
    this.sock = null;
    TILELOADER = "http";
};

WebSocketLoader.prototype.InitTileStore =function(tilestore) {
    var req = BSON.serialize({ init : {"db" : tilestore}});
	this.sock.send(req);
};

WebSocketLoader.prototype.FetchTile =function(name, image, cache, imgobj) {
	if(this.init === undefined) {
		this.InitTileStore(cache.Image.database)
	}

	// Send message
	console.log("Websocketloader fetching: "  + name + " " + image);
    var req = BSON.serialize({ tile : {"name" : name, "image" : image}});
    this.queue[name] = imgobj;
	this.sock.send(req);
};

ws = WebSocketLoader("ws://" + window.location.host + "/ws");
<commit_msg>Wesocket transport selected only after successful handshake, until then fallback to http<commit_after>// TODO: Make this a singleton module

// Make bson available
TILELOADER = "http";
var BSON = bson().BSON;

// Definition for WebSocketLoader
function WebSocketLoader(wsuri) {
	// Create object if not instance of
	if (!(this instanceof WebSocketLoader)) return new WebSocketLoader(wsuri);

	this.queue = {};

    if ("WebSocket" in window) {
        this.sock = new WebSocket(wsuri);
    } else if ("MozWebSocket" in window) {
        this.sock = new MozWebSocket(wsuri);
    } else {
        console.log("Browser does not support WebSocket!");
    }

    if (this.sock) {
        this.sock.binaryType = "arraybuffer";
        this.sock.onopen = this.OnConnect;
        this.sock.onclose = this.OnClose;
        var that = this;
        this.sock.onmessage = function(e) {
  			var resp = BSON.deserialize(new Uint8Array(e.data));
		    if(resp.hasOwnProperty("success")) {
    			// console.log("Successful request" + resp);
    			if(resp.hasOwnProperty("image")){
        			var whichtile = resp["request"]["tile"]["name"] //  + resp["request"]["tile"]["image"]
        			that.queue[whichtile].src = "data:image/jpg;base64," + btoa(String.fromCharCode.apply(null, resp.image.buffer));
        			delete that.queue[whichtile];
			    }
			} else {
				console.log("Error in request" + resp);
				var whichtile = resp["request"]["tile"]["name"];
    			that.queue[whichtile].src = ''; //  + resp["request"]["tile"]["image"]
    			delete that.queue[whichtile];
			}
	    // console.log("Got: " + JSON.stringify(resp));
		};
	}
	else {
		TILELOADER = "http";
	}
};

WebSocketLoader.prototype.OnConnect = function(e) {
    console.log("WebSocketLoader connected ..");
    TILELOADER = "websocket";
};

WebSocketLoader.prototype.OnClose = function(e) {
    console.log("WebSocketLoader closed (wasClean = " + e.wasClean + ", code = " + e.code + ", reason = '" + e.reason + "')");
    this.sock = null;
    TILELOADER = "http";
};

WebSocketLoader.prototype.InitTileStore =function(tilestore) {
    var req = BSON.serialize({ init : {"db" : tilestore}});
	this.sock.send(req);
};

WebSocketLoader.prototype.FetchTile =function(name, image, cache, imgobj) {
	if(this.init === undefined) {
		this.InitTileStore(cache.Image.database)
	}

	// Send message
	console.log("Websocketloader fetching: "  + name + " " + image);
    var req = BSON.serialize({ tile : {"name" : name, "image" : image}});
    this.queue[name] = imgobj;
	this.sock.send(req);
};

ws = WebSocketLoader("ws://" + window.location.host + "/ws");
<|endoftext|>


<commit_before>import { on, off } from 'wind-dom/src/event';

/**
 * v-clickoutside
 * @desc 点击元素外面才会触发的事件
 * @example
 * ```vue
 * <div v-element-clickoutside="handleClose">
 * ```
 */
const clickoutsideContext = '@@clickoutsideContext';

export default {
  bind(el, binding, vnode) {
    const documentHandler = function(e) {
      if (!vnode.context ||
        el.contains(e.target) ||
        !vnode.context.popperElm ||
        vnode.context.popperElm.contains(e.target)) return;
      if (binding.expression) {
        vnode.context[el[clickoutsideContext].methodName]();
      } else {
        el[clickoutsideContext].bindingFn();
      }
    };
    el[clickoutsideContext] = {
      documentHandler,
      methodName: binding.expression,
      bindingFn: binding.value
    };
    on(document, 'click', documentHandler);
  },

  update(el, binding) {
    el[clickoutsideContext].methodName = binding.expression;
    el[clickoutsideContext].bindingFn = binding.value;
  },

  unbind(el) {
    off(document, 'click', el[clickoutsideContext].documentHandler);
  },

  install(Vue) {
    Vue.directive('clickoutside', {
      bind: this.bind,
      unbind: this.unbind
    });
  }
};
<commit_msg>optimize clickoutside<commit_after>import { on } from 'wind-dom/src/event';

const nodeList = [];
on(document, 'click', e => {
  nodeList.forEach(node => node[clickoutsideContext].documentHandler(e));
});
/**
 * v-clickoutside
 * @desc 点击元素外面才会触发的事件
 * @example
 * ```vue
 * <div v-element-clickoutside="handleClose">
 * ```
 */
const clickoutsideContext = '@@clickoutsideContext';

export default {
  bind(el, binding, vnode) {
    const id = nodeList.push(el) - 1;
    const documentHandler = function(e) {
      if (!vnode.context ||
        el.contains(e.target) ||
        !vnode.context.popperElm ||
        vnode.context.popperElm.contains(e.target)) return;
      if (binding.expression) {
        vnode.context[el[clickoutsideContext].methodName]();
      } else {
        el[clickoutsideContext].bindingFn();
      }
    };
    el[clickoutsideContext] = {
      id,
      documentHandler,
      methodName: binding.expression,
      bindingFn: binding.value
    };
  },

  update(el, binding) {
    el[clickoutsideContext].methodName = binding.expression;
    el[clickoutsideContext].bindingFn = binding.value;
  },

  unbind(el) {
    nodeList.splice(el[clickoutsideContext].id, 1);
  },

  install(Vue) {
    Vue.directive('clickoutside', {
      bind: this.bind,
      unbind: this.unbind
    });
  }
};
<|endoftext|>


<commit_before>JSONEditor.defaults.editors.multiselect = JSONEditor.AbstractEditor.extend({
  preBuild: function() {
    this._super();
    var i;

    this.select_options = {};
    this.select_values = {};

    var items_schema = this.jsoneditor.expandRefs(this.schema.items || {});

    var e = items_schema["enum"] || [];
    var t = items_schema.options? items_schema.options.enum_titles || [] : [];
    this.option_keys = [];
    this.option_titles = [];
    for(i=0; i<e.length; i++) {
      // If the sanitized value is different from the enum value, don't include it
      if(this.sanitize(e[i]) !== e[i]) continue;

      this.option_keys.push(e[i]+"");
      this.option_titles.push((t[i]||e[i])+"");
      this.select_values[e[i]+""] = e[i];
    }
  },
  build: function() {
    var self = this, i;
    if(!this.options.compact) this.header = this.label = this.theme.getFormInputLabel(this.getTitle());
    if(this.schema.description) this.description = this.theme.getFormInputDescription(this.schema.description);

    if((!this.schema.format && this.option_keys.length < 8) || this.schema.format === "checkbox") {
      this.input_type = 'checkboxes';

      this.inputs = {};
      this.controls = {};
      for(i=0; i<this.option_keys.length; i++) {
        this.inputs[this.option_keys[i]] = this.theme.getCheckbox();
        this.select_options[this.option_keys[i]] = this.inputs[this.option_keys[i]];
        var label = this.theme.getCheckboxLabel(this.option_titles[i]);
        this.controls[this.option_keys[i]] = this.theme.getFormControl(label, this.inputs[this.option_keys[i]]);
      }

      this.control = this.theme.getMultiCheckboxHolder(this.controls,this.label,this.description);
    }
    else {
      this.input_type = 'select';
      this.input = this.theme.getSelectInput(this.option_keys);
      this.theme.setSelectOptions(this.input,this.option_keys,this.option_titles);
      this.input.multiple = true;
      this.input.size = Math.min(10,this.option_keys.length);

      for(i=0; i<this.option_keys.length; i++) {
        this.select_options[this.option_keys[i]] = this.input.children[i];
      }

      if(this.schema.readOnly || this.schema.readonly) {
        this.always_disabled = true;
        this.input.disabled = true;
      }

      this.control = this.theme.getFormControl(this.label, this.input, this.description);
    }

    this.container.appendChild(this.control);
    this.control.addEventListener('change',function(e) {
      e.preventDefault();
      e.stopPropagation();

      var new_value = [];
      for(i = 0; i<self.option_keys.length; i++) {
        if(self.select_options[self.option_keys[i]].selected || self.select_options[self.option_keys[i]].checked) new_value.push(self.select_values[self.option_keys[i]]);
      }

      self.updateValue(new_value);
      self.onChange(true);
    });
  },
  setValue: function(value, initial) {
    var i;
    value = value || [];
    if(typeof value !== "object") value = [value];
    else if(!(Array.isArray(value))) value = [];

    // Make sure we are dealing with an array of strings so we can check for strict equality
    for(i=0; i<value.length; i++) {
      if(typeof value[i] !== "string") value[i] += "";
    }

    // Update selected status of options
    for(i in this.select_options) {
      if(!this.select_options.hasOwnProperty(i)) continue;

      this.select_options[i][this.input_type === "select"? "selected" : "checked"] = (value.indexOf(i) !== -1);
    }

    this.updateValue(value);
    this.onChange();
  },
  setupSelect2: function() {
    if(window.jQuery && window.jQuery.fn && window.jQuery.fn.select2) {
        var options = window.jQuery.extend({},JSONEditor.plugins.select2);
        if(this.schema.options && this.schema.options.select2_options) options = $extend(options,this.schema.options.select2_options);
        this.select2 = window.jQuery(this.input).select2(options);
        this.select2v4 = this.select.hasOwnProperty("amd");
        var self = this;
        this.select2.on('select2-blur',function() {
            var val =self.select2.select2('val');
            self.value = val;
            self.onChange(true);
        });
    }
    else {
        this.select2 = null;
    }
  },
  onInputChange: function() {
      this.value = this.input.value;
      this.onChange(true);
  },
  postBuild: function() {
      this._super();
      this.setupSelect2();
  },
  register: function() {
    this._super();
    if(!this.input) return;
    this.input.setAttribute('name',this.formname);
  },
  unregister: function() {
    this._super();
    if(!this.input) return;
    this.input.removeAttribute('name');
  },
  getNumColumns: function() {
    var longest_text = this.getTitle().length;
    for(var i in this.select_values) {
      if(!this.select_values.hasOwnProperty(i)) continue;
      longest_text = Math.max(longest_text,(this.select_values[i]+"").length+4);
    }

    return Math.min(12,Math.max(longest_text/7,2));
  },
  updateValue: function(value) {
    var changed = false;
    var new_value = [];
    for(var i=0; i<value.length; i++) {
      if(!this.select_options[value[i]+""]) {
        changed = true;
        continue;
      }
      var sanitized = this.sanitize(this.select_values[value[i]]);
      new_value.push(sanitized);
      if(sanitized !== value[i]) changed = true;
    }
    this.value = new_value;
    if(this.select2) {
      if(this.select2v4)
        this.select2.val(this.value).trigger("change");
      else
        this.select2.select2('val',this.value);
    }
    return changed;
  },
  sanitize: function(value) {
    if(this.schema.items.type === "number") {
      return 1*value;
    }
    else if(this.schema.items.type === "integer") {
      return Math.floor(value*1);
    }
    else {
      return ""+value;
    }
  },
  enable: function() {
    if(!this.always_disabled) {
      if(this.input) {
        this.input.disabled = false;
      }
      else if(this.inputs) {
        for(var i in this.inputs) {
          if(!this.inputs.hasOwnProperty(i)) continue;
          this.inputs[i].disabled = false;
        }
      }
      if(this.select2) {
        if(this.select2v4)
          this.select2.prop("disabled",false);
        else
          this.select2.select2("enable",true);
      }
      this._super();
    }
  },
  disable: function(always_disabled) {
    if(always_disabled) this.always_disabled = true;
    if(this.input) {
      this.input.disabled = true;
    }
    else if(this.inputs) {
      for(var i in this.inputs) {
        if(!this.inputs.hasOwnProperty(i)) continue;
        this.inputs[i].disabled = true;
      }
    }
    if(this.select2) {
      if(this.select2v4)
        this.select2.prop("disabled",true);
      else
        this.select2.select2("enable",false);
    }
    this._super();
  },
  destroy: function() {
    if(this.select2) {
        this.select2.select2('destroy');
        this.select2 = null;
    }
    this._super();
  }
});
<commit_msg>Fixed multiselect v4 detection<commit_after>JSONEditor.defaults.editors.multiselect = JSONEditor.AbstractEditor.extend({
  preBuild: function() {
    this._super();
    var i;

    this.select_options = {};
    this.select_values = {};

    var items_schema = this.jsoneditor.expandRefs(this.schema.items || {});

    var e = items_schema["enum"] || [];
    var t = items_schema.options? items_schema.options.enum_titles || [] : [];
    this.option_keys = [];
    this.option_titles = [];
    for(i=0; i<e.length; i++) {
      // If the sanitized value is different from the enum value, don't include it
      if(this.sanitize(e[i]) !== e[i]) continue;

      this.option_keys.push(e[i]+"");
      this.option_titles.push((t[i]||e[i])+"");
      this.select_values[e[i]+""] = e[i];
    }
  },
  build: function() {
    var self = this, i;
    if(!this.options.compact) this.header = this.label = this.theme.getFormInputLabel(this.getTitle());
    if(this.schema.description) this.description = this.theme.getFormInputDescription(this.schema.description);

    if((!this.schema.format && this.option_keys.length < 8) || this.schema.format === "checkbox") {
      this.input_type = 'checkboxes';

      this.inputs = {};
      this.controls = {};
      for(i=0; i<this.option_keys.length; i++) {
        this.inputs[this.option_keys[i]] = this.theme.getCheckbox();
        this.select_options[this.option_keys[i]] = this.inputs[this.option_keys[i]];
        var label = this.theme.getCheckboxLabel(this.option_titles[i]);
        this.controls[this.option_keys[i]] = this.theme.getFormControl(label, this.inputs[this.option_keys[i]]);
      }

      this.control = this.theme.getMultiCheckboxHolder(this.controls,this.label,this.description);
    }
    else {
      this.input_type = 'select';
      this.input = this.theme.getSelectInput(this.option_keys);
      this.theme.setSelectOptions(this.input,this.option_keys,this.option_titles);
      this.input.multiple = true;
      this.input.size = Math.min(10,this.option_keys.length);

      for(i=0; i<this.option_keys.length; i++) {
        this.select_options[this.option_keys[i]] = this.input.children[i];
      }

      if(this.schema.readOnly || this.schema.readonly) {
        this.always_disabled = true;
        this.input.disabled = true;
      }

      this.control = this.theme.getFormControl(this.label, this.input, this.description);
    }

    this.container.appendChild(this.control);
    this.control.addEventListener('change',function(e) {
      e.preventDefault();
      e.stopPropagation();

      var new_value = [];
      for(i = 0; i<self.option_keys.length; i++) {
        if(self.select_options[self.option_keys[i]].selected || self.select_options[self.option_keys[i]].checked) new_value.push(self.select_values[self.option_keys[i]]);
      }

      self.updateValue(new_value);
      self.onChange(true);
    });
  },
  setValue: function(value, initial) {
    var i;
    value = value || [];
    if(typeof value !== "object") value = [value];
    else if(!(Array.isArray(value))) value = [];

    // Make sure we are dealing with an array of strings so we can check for strict equality
    for(i=0; i<value.length; i++) {
      if(typeof value[i] !== "string") value[i] += "";
    }

    // Update selected status of options
    for(i in this.select_options) {
      if(!this.select_options.hasOwnProperty(i)) continue;

      this.select_options[i][this.input_type === "select"? "selected" : "checked"] = (value.indexOf(i) !== -1);
    }

    this.updateValue(value);
    this.onChange();
  },
  setupSelect2: function() {
    if(window.jQuery && window.jQuery.fn && window.jQuery.fn.select2) {
        var options = window.jQuery.extend({},JSONEditor.plugins.select2);
        if(this.schema.options && this.schema.options.select2_options) options = $extend(options,this.schema.options.select2_options);
        this.select2 = window.jQuery(this.input).select2(options);
        this.select2v4 = this.select2.hasOwnProperty("amd");
        var self = this;
        this.select2.on('select2-blur',function() {
            var val =self.select2.select2('val');
            self.value = val;
            self.onChange(true);
        });
    }
    else {
        this.select2 = null;
    }
  },
  onInputChange: function() {
      this.value = this.input.value;
      this.onChange(true);
  },
  postBuild: function() {
      this._super();
      this.setupSelect2();
  },
  register: function() {
    this._super();
    if(!this.input) return;
    this.input.setAttribute('name',this.formname);
  },
  unregister: function() {
    this._super();
    if(!this.input) return;
    this.input.removeAttribute('name');
  },
  getNumColumns: function() {
    var longest_text = this.getTitle().length;
    for(var i in this.select_values) {
      if(!this.select_values.hasOwnProperty(i)) continue;
      longest_text = Math.max(longest_text,(this.select_values[i]+"").length+4);
    }

    return Math.min(12,Math.max(longest_text/7,2));
  },
  updateValue: function(value) {
    var changed = false;
    var new_value = [];
    for(var i=0; i<value.length; i++) {
      if(!this.select_options[value[i]+""]) {
        changed = true;
        continue;
      }
      var sanitized = this.sanitize(this.select_values[value[i]]);
      new_value.push(sanitized);
      if(sanitized !== value[i]) changed = true;
    }
    this.value = new_value;
    if(this.select2) {
      if(this.select2v4)
        this.select2.val(this.value).trigger("change");
      else
        this.select2.select2('val',this.value);
    }
    return changed;
  },
  sanitize: function(value) {
    if(this.schema.items.type === "number") {
      return 1*value;
    }
    else if(this.schema.items.type === "integer") {
      return Math.floor(value*1);
    }
    else {
      return ""+value;
    }
  },
  enable: function() {
    if(!this.always_disabled) {
      if(this.input) {
        this.input.disabled = false;
      }
      else if(this.inputs) {
        for(var i in this.inputs) {
          if(!this.inputs.hasOwnProperty(i)) continue;
          this.inputs[i].disabled = false;
        }
      }
      if(this.select2) {
        if(this.select2v4)
          this.select2.prop("disabled",false);
        else
          this.select2.select2("enable",true);
      }
      this._super();
    }
  },
  disable: function(always_disabled) {
    if(always_disabled) this.always_disabled = true;
    if(this.input) {
      this.input.disabled = true;
    }
    else if(this.inputs) {
      for(var i in this.inputs) {
        if(!this.inputs.hasOwnProperty(i)) continue;
        this.inputs[i].disabled = true;
      }
    }
    if(this.select2) {
      if(this.select2v4)
        this.select2.prop("disabled",true);
      else
        this.select2.select2("enable",false);
    }
    this._super();
  },
  destroy: function() {
    if(this.select2) {
        this.select2.select2('destroy');
        this.select2 = null;
    }
    this._super();
  }
});
<|endoftext|>


<commit_before>import { messages } from '../translations';

export const getActionMessage = (intl, activityItem) => {
  switch (activityItem.actionType) {
    case 'update_item':
      return intl.formatMessage(
        activityItem.history.length > 1 ? messages.updateItemIssue : messages.updateItem,
      );
    case 'post_issue':
      return intl.formatMessage(messages.postIssue);
    case 'link_issue':
      return intl.formatMessage(messages.linkIssue);
    case 'unlink_issue':
      return intl.formatMessage(messages.unlinkIssue);
    case 'analyze_item':
      return intl.formatMessage(messages.changedByAnalyzer);
    case 'link_issue_aa':
      return intl.formatMessage(messages.issueLoadByAnalyzer);
    default:
      return activityItem.actionType;
  }
};
<commit_msg>EPMRPP-39058. History of action. Fix activity message<commit_after>import { messages } from '../translations';

export const getActionMessage = (intl, activityItem) => {
  switch (activityItem.actionType) {
    case 'updateItem':
      return intl.formatMessage(
        activityItem.details.history.length > 1 ? messages.updateItemIssue : messages.updateItem,
      );
    case 'postIssue':
      return intl.formatMessage(messages.postIssue);
    case 'linkIssue':
      return intl.formatMessage(messages.linkIssue);
    case 'unlinkIssue':
      return intl.formatMessage(messages.unlinkIssue);
    case 'analyzeItem':
      return intl.formatMessage(messages.changedByAnalyzer);
    case 'linkIssueAa':
      return intl.formatMessage(messages.issueLoadByAnalyzer);
    default:
      return activityItem.actionType;
  }
};
<|endoftext|>


<commit_before>(function () {
  "use strict";

  function UserGroupEditController($scope, $timeout, $location, $routeParams, usersResource, localizationService, contentEditingHelper) {

    var vm = this;
    var localizeSaving = localizationService.localize("general_saving");

    vm.page = {};
    vm.userGroup = {};
    vm.labels = {};

    vm.goToPage = goToPage;
    vm.openSectionPicker = openSectionPicker;
    vm.openContentPicker = openContentPicker;
    vm.openMediaPicker = openMediaPicker;
    vm.openUserPicker = openUserPicker;
    vm.removeSelectedItem = removeSelectedItem;
    vm.clearStartNode = clearStartNode;
    vm.getUserStateType = getUserStateType;
    vm.save = save;
    vm.togglePermission = togglePermission;
    vm.openGranularPermissionsPicker = openGranularPermissionsPicker;

    function init() {

      vm.loading = true;

      localizationService.localize("general_cancel").then(function (name) {
        vm.labels.cancel = name;
      });

      if ($routeParams.create) {
        // get user group scaffold
        usersResource.getUserGroupScaffold().then(function (userGroup) {
          vm.userGroup = userGroup;
          setSectionIcon(vm.userGroup.sections);
          makeBreadcrumbs();
          vm.loading = false;
        });
      } else {
        // get user group
        usersResource.getUserGroup($routeParams.id).then(function (userGroup) {
          vm.userGroup = userGroup;
          setSectionIcon(vm.userGroup.sections);
          makeBreadcrumbs();
          vm.loading = false;
        });
      }

    }

    function save() {
      vm.page.saveButtonState = "busy";

      contentEditingHelper.contentEditorPerformSave({
        statusMessage: localizeSaving,
        saveMethod: usersResource.saveUserGroup,
        scope: $scope,
        content: vm.userGroup,
        // We do not redirect on failure for users - this is because it is not possible to actually save a user
        // when server side validation fails - as opposed to content where we are capable of saving the content
        // item if server side validation fails
        redirectOnFailure: false,
        rebindCallback: function (orignal, saved) { }
      }).then(function (saved) {

        vm.userGroup = saved;
        setSectionIcon(vm.userGroup.sections);
        makeBreadcrumbs();
        vm.page.saveButtonState = "success";

      }, function (err) {

        vm.page.saveButtonState = "error";

      });
    }

    function goToPage(ancestor) {
      $location.path(ancestor.path).search("subview", ancestor.subView);
    }

    function openSectionPicker() {
      vm.sectionPicker = {
        title: "Select sections",
        view: "sectionpicker",
        selection: vm.userGroup.sections,
        closeButtonLabel: vm.labels.cancel,
        show: true,
        submit: function (model) {
          vm.sectionPicker.show = false;
          vm.sectionPicker = null;
        },
        close: function (oldModel) {
          if (oldModel.selection) {
            vm.userGroup.sections = oldModel.selection;
          }
          vm.sectionPicker.show = false;
          vm.sectionPicker = null;
        }
      };
    }

    function openContentPicker() {
      vm.contentPicker = {
        title: "Select content start node",
        view: "contentpicker",
        hideSubmitButton: true,
        show: true,
        submit: function (model) {
          if (model.selection) {
            vm.userGroup.startContentId = model.selection[0];
          }
          vm.contentPicker.show = false;
          vm.contentPicker = null;
        },
        close: function (oldModel) {
          vm.contentPicker.show = false;
          vm.contentPicker = null;
        }
      };
    }

    function openMediaPicker() {
      vm.contentPicker = {
        title: "Select media start node",
        view: "treepicker",
        section: "media",
        treeAlias: "media",
        entityType: "media",
        hideSubmitButton: true,
        show: true,
        submit: function (model) {
          if (model.selection) {
            vm.userGroup.startMediaId = model.selection[0];
          }
          vm.contentPicker.show = false;
          vm.contentPicker = null;
        },
        close: function (oldModel) {
          vm.contentPicker.show = false;
          vm.contentPicker = null;
        }
      };
    }

    function openUserPicker() {
      vm.userPicker = {
        title: "Select users",
        view: "userpicker",
        selection: vm.userGroup.users,
        show: true,
        submit: function (model) {
          /*
          if(model.selection) {
              vm.userGroup.startNodesMedia = model.selection;
          }
          */
          vm.userPicker.show = false;
          vm.userPicker = null;
        },
        close: function (oldModel) {
          vm.userPicker.show = false;
          vm.userPicker = null;
        }
      };
    }

    function openGranularPermissionsPicker() {
      vm.contentPicker = {
        title: "Select node",
        view: "contentpicker",
        hideSubmitButton: true,
        show: true,
        submit: function (model) {
          if (model.selection) {
            setPermissionsForNode(model.selection[0]);
          }
        },
        close: function (oldModel) {
          vm.firstPicker.show = false;
          vm.firstPicker = null;
        }
      };
    }

    function setPermissionsForNode(node) {
      vm.nodePermissions = {
        title: "Set permissions for " + node.name,
        view: "nodepermissions",
        node: node,
        show: true,
        submit: function (model) {

          if (model && model.node && model.node.permissions) {
            // clear allowed permissions before we make the list
            // so we don't have deplicates
            node.allowedPermissions = [];

            // get list of checked permissions
            angular.forEach(model.node.permissions, function (permissionGroup) {
              angular.forEach(permissionGroup.permissions, function (permission) {
                if (permission.checked) {
                  node.allowedPermissions.push(permission);
                }
              });
            });

            if(!vm.userGroup.nodes) {
              vm.userGroup.nodes = [];
            }
            vm.userGroup.nodes.push(node);
          }

          // close node permisssions overlay
          vm.nodePermissions.show = false;
          vm.nodePermissions = null;
          // close content picker overlay
          vm.contentPicker.show = false;
          vm.contentPicker = null;
        },
        close: function (oldModel) {
          vm.nodePermissions.show = false;
          vm.nodePermissions = null;
        }
      };
    }

    function removeSelectedItem(index, selection) {
      if (selection && selection.length > 0) {
        selection.splice(index, 1);
      }
    }

    function clearStartNode(type) {
      if (type === "content") {
        vm.userGroup.startContentId = null;
      } else if (type === "media") {
        vm.userGroup.startMediaId = null;
      }
    }

    function getUserStateType(state) {
      switch (state) {
        case "disabled" || "umbracoDisabled":
          return "danger";
        case "pending":
          return "warning";
        default:
          return "success";
      }
    }

        function togglePermission(permission) {
            permission.checked = !permission.checked;
        }

    function makeBreadcrumbs() {
      vm.breadcrumbs = [
        {
          "name": "Groups",
          "path": "/users/users/overview",
          "subView": "groups"
        },
        {
          "name": vm.userGroup.name
                }
            ];
        }

    function setSectionIcon(sections) {
      angular.forEach(sections, function (section) {
        section.icon = "icon-section " + section.cssclass;
      });
    }

    init();

  }

  angular.module("umbraco").controller("Umbraco.Editors.Users.GroupController", UserGroupEditController);

})();
<commit_msg>fix line indention<commit_after>(function () {
    "use strict";

    function UserGroupEditController($scope, $timeout, $location, $routeParams, usersResource, localizationService, contentEditingHelper) {

        var vm = this;
        var localizeSaving = localizationService.localize("general_saving");

        vm.page = {};
        vm.userGroup = {};
        vm.labels = {};

        vm.goToPage = goToPage;
        vm.openSectionPicker = openSectionPicker;
        vm.openContentPicker = openContentPicker;
        vm.openMediaPicker = openMediaPicker;
        vm.openUserPicker = openUserPicker;
        vm.removeSelectedItem = removeSelectedItem;
        vm.clearStartNode = clearStartNode;
        vm.getUserStateType = getUserStateType;
        vm.save = save;
        vm.togglePermission = togglePermission;
        vm.openGranularPermissionsPicker = openGranularPermissionsPicker;

        function init() {

            vm.loading = true;

            localizationService.localize("general_cancel").then(function (name) {
                vm.labels.cancel = name;
            });

            if ($routeParams.create) {
                // get user group scaffold
                usersResource.getUserGroupScaffold().then(function (userGroup) {
                    vm.userGroup = userGroup;
                    setSectionIcon(vm.userGroup.sections);
                    makeBreadcrumbs();
                    vm.loading = false;
                });
            } else {
                // get user group
                usersResource.getUserGroup($routeParams.id).then(function (userGroup) {
                    vm.userGroup = userGroup;
                    setSectionIcon(vm.userGroup.sections);
                    makeBreadcrumbs();
                    vm.loading = false;
                });
            }

        }

        function save() {
            vm.page.saveButtonState = "busy";

            contentEditingHelper.contentEditorPerformSave({
                statusMessage: localizeSaving,
                saveMethod: usersResource.saveUserGroup,
                scope: $scope,
                content: vm.userGroup,
                // We do not redirect on failure for users - this is because it is not possible to actually save a user
                // when server side validation fails - as opposed to content where we are capable of saving the content
                // item if server side validation fails
                redirectOnFailure: false,
                rebindCallback: function (orignal, saved) { }
            }).then(function (saved) {

                vm.userGroup = saved;
                setSectionIcon(vm.userGroup.sections);
                makeBreadcrumbs();
                vm.page.saveButtonState = "success";

            }, function (err) {

                vm.page.saveButtonState = "error";

            });
        }

        function goToPage(ancestor) {
            $location.path(ancestor.path).search("subview", ancestor.subView);
        }

        function openSectionPicker() {
            vm.sectionPicker = {
                title: "Select sections",
                view: "sectionpicker",
                selection: vm.userGroup.sections,
                closeButtonLabel: vm.labels.cancel,
                show: true,
                submit: function (model) {
                    vm.sectionPicker.show = false;
                    vm.sectionPicker = null;
                },
                close: function (oldModel) {
                    if (oldModel.selection) {
                        vm.userGroup.sections = oldModel.selection;
                    }
                    vm.sectionPicker.show = false;
                    vm.sectionPicker = null;
                }
            };
        }

        function openContentPicker() {
            vm.contentPicker = {
                title: "Select content start node",
                view: "contentpicker",
                hideSubmitButton: true,
                show: true,
                submit: function (model) {
                    if (model.selection) {
                        vm.userGroup.startContentId = model.selection[0];
                    }
                    vm.contentPicker.show = false;
                    vm.contentPicker = null;
                },
                close: function (oldModel) {
                    vm.contentPicker.show = false;
                    vm.contentPicker = null;
                }
            };
        }

        function openMediaPicker() {
            vm.contentPicker = {
                title: "Select media start node",
                view: "treepicker",
                section: "media",
                treeAlias: "media",
                entityType: "media",
                hideSubmitButton: true,
                show: true,
                submit: function (model) {
                    if (model.selection) {
                        vm.userGroup.startMediaId = model.selection[0];
                    }
                    vm.contentPicker.show = false;
                    vm.contentPicker = null;
                },
                close: function (oldModel) {
                    vm.contentPicker.show = false;
                    vm.contentPicker = null;
                }
            };
        }

        function openUserPicker() {
            vm.userPicker = {
                title: "Select users",
                view: "userpicker",
                selection: vm.userGroup.users,
                show: true,
                submit: function (model) {
                    /*
                    if(model.selection) {
                        vm.userGroup.startNodesMedia = model.selection;
                    }
                    */
                    vm.userPicker.show = false;
                    vm.userPicker = null;
                },
                close: function (oldModel) {
                    vm.userPicker.show = false;
                    vm.userPicker = null;
                }
            };
        }

        function openGranularPermissionsPicker() {
            vm.contentPicker = {
                title: "Select node",
                view: "contentpicker",
                hideSubmitButton: true,
                show: true,
                submit: function (model) {
                    if (model.selection) {
                        setPermissionsForNode(model.selection[0]);
                    }
                },
                close: function (oldModel) {
                    vm.firstPicker.show = false;
                    vm.firstPicker = null;
                }
            };
        }

        function setPermissionsForNode(node) {
            vm.nodePermissions = {
                title: "Set permissions for " + node.name,
                view: "nodepermissions",
                node: node,
                show: true,
                submit: function (model) {

                    if (model && model.node && model.node.permissions) {
                        // clear allowed permissions before we make the list
                        // so we don't have deplicates
                        node.allowedPermissions = [];

                        // get list of checked permissions
                        angular.forEach(model.node.permissions, function (permissionGroup) {
                            angular.forEach(permissionGroup.permissions, function (permission) {
                                if (permission.checked) {
                                    node.allowedPermissions.push(permission);
                                }
                            });
                        });

                        if (!vm.userGroup.nodes) {
                            vm.userGroup.nodes = [];
                        }
                        vm.userGroup.nodes.push(node);
                    }

                    // close node permisssions overlay
                    vm.nodePermissions.show = false;
                    vm.nodePermissions = null;
                    // close content picker overlay
                    vm.contentPicker.show = false;
                    vm.contentPicker = null;
                },
                close: function (oldModel) {
                    vm.nodePermissions.show = false;
                    vm.nodePermissions = null;
                }
            };
        }

        function removeSelectedItem(index, selection) {
            if (selection && selection.length > 0) {
                selection.splice(index, 1);
            }
        }

        function clearStartNode(type) {
            if (type === "content") {
                vm.userGroup.startContentId = null;
            } else if (type === "media") {
                vm.userGroup.startMediaId = null;
            }
        }

        function getUserStateType(state) {
            switch (state) {
                case "disabled" || "umbracoDisabled":
                    return "danger";
                case "pending":
                    return "warning";
                default:
                    return "success";
            }
        }

        function togglePermission(permission) {
            permission.checked = !permission.checked;
        }

        function makeBreadcrumbs() {
            vm.breadcrumbs = [
                {
                    "name": "Groups",
                    "path": "/users/users/overview",
                    "subView": "groups"
                },
                {
                    "name": vm.userGroup.name
                }
            ];
        }

        function setSectionIcon(sections) {
            angular.forEach(sections, function (section) {
                section.icon = "icon-section " + section.cssclass;
            });
        }

        init();

    }

    angular.module("umbraco").controller("Umbraco.Editors.Users.GroupController", UserGroupEditController);

})();
<|endoftext|>


<commit_before>/**
 * `modules/analytics-4` data store: settings.
 *
 * Site Kit by Google, Copyright 2021 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.
 */

/**
 * External dependencies
 */
import invariant from 'invariant';

/**
 * Internal dependencies
 */
import API from 'googlesitekit-api';
import { createStrictSelect } from '../../../googlesitekit/data/utils';
import { isValidPropertySelection, isValidWebDataStreamID, isValidWebDataStreamSelection } from '../utils/validation';
import { INVARIANT_DOING_SUBMIT_CHANGES, INVARIANT_SETTINGS_NOT_CHANGED } from '../../../googlesitekit/data/create-settings-store';
import { MODULES_ANALYTICS } from '../../analytics/datastore/constants';
import { STORE_NAME, PROPERTY_CREATE, WEBDATASTREAM_CREATE } from './constants';

// Invariant error messages.
export const INVARIANT_INVALID_PROPERTY_SELECTION = 'a valid propertyID is required to submit changes';
export const INVARIANT_INVALID_WEBDATASTREAM_ID = 'a valid webDataStreamID is required to submit changes';

export async function submitChanges( { select, dispatch } ) {
	let propertyID = select( STORE_NAME ).getPropertyID();
	if ( propertyID === PROPERTY_CREATE ) {
		const accountID = select( MODULES_ANALYTICS ).getAccountID();
		const { response: property, error } = await dispatch( STORE_NAME ).createProperty( accountID );
		if ( error ) {
			return { error };
		}

		propertyID = property._id;
		dispatch( STORE_NAME ).setPropertyID( propertyID );
		dispatch( STORE_NAME ).setWebDataStreamID( WEBDATASTREAM_CREATE );
		dispatch( STORE_NAME ).setMeasurementID( '' );
	}

	const webDataStreamID = select( STORE_NAME ).getWebDataStreamID();
	if ( webDataStreamID === WEBDATASTREAM_CREATE || ! isValidWebDataStreamID( webDataStreamID ) ) {
		const { response: webdatastream, error } = await dispatch( STORE_NAME ).createWebDataStream( propertyID );
		if ( error ) {
			return { error };
		}

		dispatch( STORE_NAME ).setWebDataStreamID( webdatastream._id );
		dispatch( STORE_NAME ).setMeasurementID( webdatastream.measurementId ); // eslint-disable-line sitekit/acronym-case
	}

	if ( select( STORE_NAME ).haveSettingsChanged() ) {
		const { error } = await dispatch( STORE_NAME ).saveSettings();
		if ( error ) {
			return { error };
		}
	}

	await API.invalidateCache( 'modules', 'analytics-4' );

	return {};
}

export function validateCanSubmitChanges( select ) {
	if ( select( STORE_NAME ).isAdminAPIWorking() === false ) {
		return;
	}

	const {
		haveSettingsChanged: haveGA4SettingsChanged,
		isDoingSubmitChanges,
		getPropertyID,
		getWebDataStreamID,
	} = createStrictSelect( select )( STORE_NAME );

	const {
		haveSettingsChanged: haveUASettingsChanged,
	} = createStrictSelect( select )( MODULES_ANALYTICS );

	// Check if we have GA4 settings changed only if we are sure that there is no UA changes.
	if ( ! haveUASettingsChanged() ) {
		invariant( haveGA4SettingsChanged(), INVARIANT_SETTINGS_NOT_CHANGED );
	}

	invariant( ! isDoingSubmitChanges(), INVARIANT_DOING_SUBMIT_CHANGES );

	const propertyID = getPropertyID();
	invariant( isValidPropertySelection( propertyID ), INVARIANT_INVALID_PROPERTY_SELECTION );
	if ( propertyID !== PROPERTY_CREATE ) {
		invariant( isValidWebDataStreamSelection( getWebDataStreamID() ), INVARIANT_INVALID_WEBDATASTREAM_ID );
	}
}
<commit_msg>Update submitChanges function to not create a web data store for an empty propertyID.<commit_after>/**
 * `modules/analytics-4` data store: settings.
 *
 * Site Kit by Google, Copyright 2021 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.
 */

/**
 * External dependencies
 */
import invariant from 'invariant';

/**
 * Internal dependencies
 */
import API from 'googlesitekit-api';
import { createStrictSelect } from '../../../googlesitekit/data/utils';
import { isValidPropertySelection, isValidWebDataStreamID, isValidWebDataStreamSelection } from '../utils/validation';
import { INVARIANT_DOING_SUBMIT_CHANGES, INVARIANT_SETTINGS_NOT_CHANGED } from '../../../googlesitekit/data/create-settings-store';
import { MODULES_ANALYTICS } from '../../analytics/datastore/constants';
import { STORE_NAME, PROPERTY_CREATE, WEBDATASTREAM_CREATE } from './constants';

// Invariant error messages.
export const INVARIANT_INVALID_PROPERTY_SELECTION = 'a valid propertyID is required to submit changes';
export const INVARIANT_INVALID_WEBDATASTREAM_ID = 'a valid webDataStreamID is required to submit changes';

export async function submitChanges( { select, dispatch } ) {
	let propertyID = select( STORE_NAME ).getPropertyID();
	if ( propertyID === PROPERTY_CREATE ) {
		const accountID = select( MODULES_ANALYTICS ).getAccountID();
		const { response: property, error } = await dispatch( STORE_NAME ).createProperty( accountID );
		if ( error ) {
			return { error };
		}

		propertyID = property._id;
		dispatch( STORE_NAME ).setPropertyID( propertyID );
		dispatch( STORE_NAME ).setWebDataStreamID( WEBDATASTREAM_CREATE );
		dispatch( STORE_NAME ).setMeasurementID( '' );
	}

	const webDataStreamID = select( STORE_NAME ).getWebDataStreamID();
	if ( propertyID && ( webDataStreamID === WEBDATASTREAM_CREATE || ! isValidWebDataStreamID( webDataStreamID ) ) ) {
		const { response: webdatastream, error } = await dispatch( STORE_NAME ).createWebDataStream( propertyID );
		if ( error ) {
			return { error };
		}

		dispatch( STORE_NAME ).setWebDataStreamID( webdatastream._id );
		dispatch( STORE_NAME ).setMeasurementID( webdatastream.measurementId ); // eslint-disable-line sitekit/acronym-case
	}

	if ( select( STORE_NAME ).haveSettingsChanged() ) {
		const { error } = await dispatch( STORE_NAME ).saveSettings();
		if ( error ) {
			return { error };
		}
	}

	await API.invalidateCache( 'modules', 'analytics-4' );

	return {};
}

export function validateCanSubmitChanges( select ) {
	if ( select( STORE_NAME ).isAdminAPIWorking() === false ) {
		return;
	}

	const {
		haveSettingsChanged: haveGA4SettingsChanged,
		isDoingSubmitChanges,
		getPropertyID,
		getWebDataStreamID,
	} = createStrictSelect( select )( STORE_NAME );

	const {
		haveSettingsChanged: haveUASettingsChanged,
	} = createStrictSelect( select )( MODULES_ANALYTICS );

	// Check if we have GA4 settings changed only if we are sure that there is no UA changes.
	if ( ! haveUASettingsChanged() ) {
		invariant( haveGA4SettingsChanged(), INVARIANT_SETTINGS_NOT_CHANGED );
	}

	invariant( ! isDoingSubmitChanges(), INVARIANT_DOING_SUBMIT_CHANGES );

	const propertyID = getPropertyID();
	invariant( isValidPropertySelection( propertyID ), INVARIANT_INVALID_PROPERTY_SELECTION );
	if ( propertyID !== PROPERTY_CREATE ) {
		invariant( isValidWebDataStreamSelection( getWebDataStreamID() ), INVARIANT_INVALID_WEBDATASTREAM_ID );
	}
}
<|endoftext|>


<commit_before><commit_msg>Fix for jQuery<commit_after><|endoftext|>