<commit_before>(function ()
{
    Kinetic.Link = function (config)
    {
        this.____init(config);
    };
    Kinetic.Link.prototype = {
        ____init: function (config)
        {
            this.className = "Link";
            Kinetic.Group.call(this, config);
            this.add(new Kinetic.Text(AgidoMockups.extend(config, {id: "text", x: 0, y: 0, draggable: false, fill: config.color, stroke: null})));
            this.add(new Kinetic.Line(AgidoMockups.extend(config, {id: "line", x: 0, y: 0, draggable: false, stroke: config.color})));
            //noinspection JSUnusedLocalSymbols
            this.add = function (ignore)
            {
                throw new Error("Cannot add children to Link");
            }
        }, drawScene: function (canvas)
        {
            var textChild = this.find("#text")[0];
            textChild.setText(this.getText());
            //noinspection JSUnresolvedFunction
            this.find("#line")[0].setPoints([
                {x: 0, y: textChild.getTextHeight()},
                {x: textChild.getWidth(), y: textChild.getTextHeight()}
            ]);
            return Kinetic.Container.prototype.drawScene.call(this, canvas);
        }, toObject: function ()
        {
            return Kinetic.Node.prototype.toObject.call(this);
        }
    };
    Kinetic.Util.extend(Kinetic.Link, Kinetic.Group);
    Kinetic.Factory.addGetterSetter(Kinetic.Link, 'text', "The link");
})();
<commit_msg>Link component performance<commit_after>(function ()
{
    function updateChildren(item)
    {
        var textChild = item.find(".text")[0];
        textChild.setText(item.getText());
        //noinspection JSUnresolvedFunction
        item.find(".line")[0].setPoints([
            {x: 0, y: textChild.getTextHeight()},
            {x: textChild.getWidth(), y: textChild.getTextHeight()}
        ]);
    }

    Kinetic.Link = function (config)
    {
        this.____init(config);
    };
    Kinetic.Link.prototype = {
        ____init: function (config)
        {
            this.className = "Link";
            Kinetic.Group.call(this, config);
            this.add(new Kinetic.Text(AgidoMockups.extend(config, {name: "text", x: 0, y: 0, draggable: false, fill: config.color, stroke: null})));
            this.add(new Kinetic.Line(AgidoMockups.extend(config, {name: "line", x: 0, y: 0, draggable: false, stroke: config.color})));
            //noinspection JSUnusedLocalSymbols
            this.add = function (ignore)
            {
                throw new Error("Cannot add children to Link");
            };
            this.on("textChange", function (event)
            {
                if (event.newVal != event.oldVal) {
                    updateChildren(this);
                }
            });
            updateChildren(this);
        },
        toObject: function ()
        {
            return Kinetic.Node.prototype.toObject.call(this);
        }
    };
    Kinetic.Util.extend(Kinetic.Link, Kinetic.Group);
    Kinetic.Factory.addGetterSetter(Kinetic.Link, 'text', "The link");
})();
<|endoftext|>


<commit_before>import React, {useState, useEffect} from 'react';
import {makeStyles} from '@material-ui/core/styles';
import {Typography, Breadcrumbs, Link, Box} from '@material-ui/core';
import Auth from '../auth.js';
import * as api from '../api.js';
import SearchList from './searchlist.js';

const useStyles = makeStyles((theme) => ({
  root: {
    background: '#fff',
  },
}));

/**
 * Main page for the app
 * @return {ReactElement}
 */
export default function Main() {
  const classes = useStyles();

  // Declare state variables
  const [, setIsSignedIn] = useState(false);

  // Project state
  const [projects, setProjects] = useState([]);
  const [projectsLoading, setProjectsLoading] = useState(false);
  const [selectedProject, setSelectedProject] = useState(null);

  // Location state
  const [locations, setLocations] = useState([]);
  const [locationsLoading, setLocationsLoading] = useState(false);
  const [selectedLocation, setSelectedLocation] = useState(null);

  // Dataset state
  const [datasets, setDatasets] = useState([]);
  const [datasetsLoading, setDatasetsLoading] = useState(false);
  const [selectedDataset, setSelectedDataset] = useState(null);

  // DicomStore state
  const [dicomStores, setDicomStores] = useState([]);
  const [dicomStoresLoading, setDicomStoresLoading] = useState(false);
  const [selectedDicomStore, setSelectedDicomStore] = useState(null);

  // Study state
  const [studies, setStudies] = useState([]);
  const [studiesLoading, setStudiesLoading] = useState(false);
  const [selectedStudy, setSelectedStudy] = useState(null);

  // Series state
  const [series, setSeries] = useState([]);
  const [seriesLoading, setSeriesLoading] = useState(false);
  const [selectedSeries, setSelectedSeries] = useState(null);

  /* On mount, check if user is signed in already or not
  by checking for an access token in local storage */
  useEffect(() => {
    // Load GooglAuth library on mount
    Auth.initClient().then(() => {
      // Set up listener to listen to signed in state changes
      Auth.onSignedInChanged((isSignedIn) => {
        setIsSignedIn(isSignedIn);
      });

      // Check if user is already signed in on page load
      const signedIn = Auth.isSignedIn();
      setIsSignedIn(signedIn);

      if (signedIn) {
        loadProjects();
      } else {
        signIn();
      }
    });
  }, []);

  const signIn = () => {
    Auth.signIn();
  };

  // Generic flow for populating data into our react component
  const loadData = async (apiCall, setLoading, setData) => {
    setLoading(true);
    try {
      const data = await apiCall();
      setData(data);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  // Use loadData to generate functions for loading all state data
  const loadProjects = async () =>
    loadData(api.fetchProjects, setProjectsLoading, setProjects);

  const loadFilteredProjects = async (searchQuery) =>
    loadData(() => api.fetchProjects(searchQuery),
        setProjectsLoading, setProjects);

  const loadLocations = async (projectId) =>
    loadData(() => api.fetchLocations(projectId),
        setLocationsLoading, setLocations);

  const loadDatasets = async (projectId, location) =>
    loadData(() => api.fetchDatasets(projectId, location),
        setDatasetsLoading, setDatasets);

  const loadDicomStores = async (projectId, location, dataset) =>
    loadData(() => api.fetchDicomStores(projectId, location, dataset),
        setDicomStoresLoading, setDicomStores);

  const loadStudies = async (projectId, location, dataset, dicomStore) =>
    loadData(async () => {
      const data = await api.fetchStudies(projectId, location,
          dataset, dicomStore);

      // Add a new field "displayValue" to each study for the SearchList
      return data.map((study) => ({...study,
        displayValue: study['00100020'].Value[0]}));
    }, setStudiesLoading, setStudies);

  const loadSeries =
  async (projectId, location, dataset, dicomStore, studyId) =>
    loadData(async () => {
      const data = await api.fetchSeries(projectId, location,
          dataset, dicomStore, studyId);

      // Add a new field "displayValue" to each series for the SearchList
      return data.map((series) => ({...series,
        displayValue: series['0008103E'].Value[0]}));
    }, setSeriesLoading, setSeries);

  // Methods for selecting a list item and loading data for the next list
  /** @param {string} projectId Project to select */
  const selectProject = (projectId) => {
    setSelectedProject(projectId);
    loadLocations(projectId);
  };

  /** @param {string} locationId Location to select */
  const selectLocation = (locationId) => {
    setSelectedLocation(locationId);
    loadDatasets(selectedProject, locationId);
  };

  /** @param {string} dataset Dataset to select */
  const selectDataset = (dataset) => {
    setSelectedDataset(dataset);
    loadDicomStores(selectedProject, selectedLocation, dataset);
  };

  /** @param {string} dicomStore Dicom Store to select */
  const selectDicomStore = (dicomStore) => {
    setSelectedDicomStore(dicomStore);
    loadStudies(selectedProject, selectedLocation, selectedDataset, dicomStore);
  };

  /** @param {Object} study Study to select */
  const selectStudy = (study) => {
    setSelectedStudy(study);

    loadSeries(selectedProject, selectedLocation, selectedDataset,
        selectedDicomStore, study['0020000D'].Value[0]);
  };

  /** @param {Object} series Series to select */
  const selectSeries = (series) => {
    setSelectedSeries(series);
  };

  /**
   * Clears all state up to and including project and reloads
   * projects
   */
  const clearAndLoadProjects = () => {
    setSelectedProject(null);

    clearLocation();
    setLocations([]);

    loadProjects();
  };

  /** Clears all state up to and including location */
  const clearLocation = () => {
    setSelectedLocation(null);

    clearDataset();
    setDatasets([]);
  };
  /** Clears location state and reloads locations list */
  const clearAndLoadLocations = () => {
    clearLocation();
    loadLocations(selectedProject);
  };

  /** Clears all state up to and including dataset */
  const clearDataset = () => {
    setSelectedDataset(null);

    clearDicomStore();
    setDicomStores([]);
  };
  /** Clears dataset state and reloads dataset list */
  const clearAndLoadDatasets = () => {
    clearDataset();
    loadDatasets(selectedProject, selectedLocation);
  };

  /** Clears all state up to and including dicom store */
  const clearDicomStore = () => {
    setSelectedDicomStore(null);

    clearStudy();
    setStudies([]);
  };
  /** Clears dicomStore state and reloads dicomStore list */
  const clearAndLoadDicomStores = () => {
    clearDicomStore();
    loadDicomStores(selectedProject, selectedLocation, selectedDataset);
  };

  /** Clears all state up to and including study */
  const clearStudy = () => {
    setSelectedStudy(null);

    clearSeries();
    setSeries([]);
  };
  /** Clears study state and reloads study list */
  const clearAndLoadStudies = () => {
    clearStudy();
    loadStudies(selectedProject, selectedLocation,
        selectedDataset, selectedDicomStore);
  };

  /** Clears all state up to and including series */
  const clearSeries = () => {
    setSelectedSeries(null);
  };
  /** Clears series state and reloads series list */
  const clearAndLoadSeries = () => {
    clearSeries();
    loadSeries(selectedProject, selectedLocation,
        selectedDataset, selectedDicomStore,
        selectedStudy['0020000D'].Value[0]);
  };

  const handleProjectSearch = (searchQuery) => {
    loadFilteredProjects(searchQuery);
  };

  return (

      <Box m={2} display="flex" flexDirection="row">
        <Box flexGrow={1}>
          <Breadcrumbs>
            {selectedProject ?
              <Link color="inherit" href="#" onClick={clearAndLoadProjects}>
                {selectedProject}
              </Link> :
              <Typography color="textPrimary">
                Select Project
              </Typography>}
            {selectedLocation ?
              <Link color="inherit" href="#" onClick={clearAndLoadLocations}>
                {selectedLocation}
              </Link> :
              selectedProject ?
                <Typography color="textPrimary">
                  Select Location
                </Typography> : null}
            {selectedDataset ?
              <Link color="inherit" href="#" onClick={clearAndLoadDatasets}>
                {selectedDataset}
              </Link> :
              selectedLocation ?
                <Typography color="textPrimary">
                  Select Dataset
                </Typography> : null}
            {selectedDicomStore ?
              <Link color="inherit" href="#" onClick={clearAndLoadDicomStores}>
                {selectedDicomStore}
              </Link> :
              selectedDataset ?
                <Typography color="textPrimary">
                  Select Dicom Store
                </Typography> : null}
            {selectedStudy ?
              <Link color="inherit" href="#" onClick={clearAndLoadStudies}>
                {selectedStudy.displayValue}
              </Link> :
              selectedDicomStore ?
                <Typography color="textPrimary">
                  Select Study
                </Typography> : null}
            {selectedSeries ?
              <Link color="inherit" href="#" onClick={clearAndLoadSeries}>
                {selectedSeries.displayValue}
              </Link> :
              selectedStudy ?
                <Typography color="textPrimary">
                  Select Series
                </Typography> : null}
          </Breadcrumbs>
        </Box>
      </Box>

      {!selectedProject ?
        <SearchList
          items={projects}
          onClickItem={selectProject}
          isLoading={projectsLoading}
          onSearch={handleProjectSearch}
          searchDelay={200} /> : null}
      {(selectedProject && !selectedLocation) ?
        <SearchList
          items={locations}
          onClickItem={selectLocation}
          isLoading={locationsLoading} /> : null}
      {(selectedLocation && !selectedDataset) ?
        <SearchList
          items={datasets}
          onClickItem={selectDataset}
          isLoading={datasetsLoading} /> : null}
      {(selectedDataset && !selectedDicomStore) ?
        <SearchList
          items={dicomStores}
          onClickItem={selectDicomStore}
          isLoading={dicomStoresLoading} /> : null}
      {(selectedDicomStore && !selectedStudy) ?
        <SearchList
          items={studies}
          onClickItem={selectStudy}
          isLoading={studiesLoading} /> : null}
      {(selectedStudy && !selectedSeries) ?
        <SearchList
          items={series}
          onClickItem={selectSeries}
          isLoading={seriesLoading} /> : null}

  );
}
<commit_msg>Used modality as series display value<commit_after>import React, {useState, useEffect} from 'react';
import {makeStyles} from '@material-ui/core/styles';
import {Typography, Breadcrumbs, Link, Box} from '@material-ui/core';
import Auth from '../auth.js';
import * as api from '../api.js';
import SearchList from './searchlist.js';

const useStyles = makeStyles((theme) => ({
  root: {
    background: '#fff',
  },
}));

/**
 * Main page for the app
 * @return {ReactElement}
 */
export default function Main() {
  const classes = useStyles();

  // Declare state variables
  const [, setIsSignedIn] = useState(false);

  // Project state
  const [projects, setProjects] = useState([]);
  const [projectsLoading, setProjectsLoading] = useState(false);
  const [selectedProject, setSelectedProject] = useState(null);

  // Location state
  const [locations, setLocations] = useState([]);
  const [locationsLoading, setLocationsLoading] = useState(false);
  const [selectedLocation, setSelectedLocation] = useState(null);

  // Dataset state
  const [datasets, setDatasets] = useState([]);
  const [datasetsLoading, setDatasetsLoading] = useState(false);
  const [selectedDataset, setSelectedDataset] = useState(null);

  // DicomStore state
  const [dicomStores, setDicomStores] = useState([]);
  const [dicomStoresLoading, setDicomStoresLoading] = useState(false);
  const [selectedDicomStore, setSelectedDicomStore] = useState(null);

  // Study state
  const [studies, setStudies] = useState([]);
  const [studiesLoading, setStudiesLoading] = useState(false);
  const [selectedStudy, setSelectedStudy] = useState(null);

  // Series state
  const [series, setSeries] = useState([]);
  const [seriesLoading, setSeriesLoading] = useState(false);
  const [selectedSeries, setSelectedSeries] = useState(null);

  /* On mount, check if user is signed in already or not
  by checking for an access token in local storage */
  useEffect(() => {
    // Load GooglAuth library on mount
    Auth.initClient().then(() => {
      // Set up listener to listen to signed in state changes
      Auth.onSignedInChanged((isSignedIn) => {
        setIsSignedIn(isSignedIn);
      });

      // Check if user is already signed in on page load
      const signedIn = Auth.isSignedIn();
      setIsSignedIn(signedIn);

      if (signedIn) {
        loadProjects();
      } else {
        signIn();
      }
    });
  }, []);

  const signIn = () => {
    Auth.signIn();
  };

  // Generic flow for populating data into our react component
  const loadData = async (apiCall, setLoading, setData) => {
    setLoading(true);
    try {
      const data = await apiCall();
      setData(data);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  // Use loadData to generate functions for loading all state data
  const loadProjects = async () =>
    loadData(api.fetchProjects, setProjectsLoading, setProjects);

  const loadFilteredProjects = async (searchQuery) =>
    loadData(() => api.fetchProjects(searchQuery),
        setProjectsLoading, setProjects);

  const loadLocations = async (projectId) =>
    loadData(() => api.fetchLocations(projectId),
        setLocationsLoading, setLocations);

  const loadDatasets = async (projectId, location) =>
    loadData(() => api.fetchDatasets(projectId, location),
        setDatasetsLoading, setDatasets);

  const loadDicomStores = async (projectId, location, dataset) =>
    loadData(() => api.fetchDicomStores(projectId, location, dataset),
        setDicomStoresLoading, setDicomStores);

  const loadStudies = async (projectId, location, dataset, dicomStore) =>
    loadData(async () => {
      const data = await api.fetchStudies(projectId, location,
          dataset, dicomStore);

      // Add a new field "displayValue" to each study for the SearchList
      return data.map((study) => ({...study,
        displayValue: study['00100020'].Value[0]}));
    }, setStudiesLoading, setStudies);

  const loadSeries =
  async (projectId, location, dataset, dicomStore, studyId) =>
    loadData(async () => {
      const data = await api.fetchSeries(projectId, location,
          dataset, dicomStore, studyId);

      // Add a new field "displayValue" to each series for the SearchList
      return data.map((series) => ({...series,
        displayValue: series['00080060'].Value[0]}));
    }, setSeriesLoading, setSeries);

  // Methods for selecting a list item and loading data for the next list
  /** @param {string} projectId Project to select */
  const selectProject = (projectId) => {
    setSelectedProject(projectId);
    loadLocations(projectId);
  };

  /** @param {string} locationId Location to select */
  const selectLocation = (locationId) => {
    setSelectedLocation(locationId);
    loadDatasets(selectedProject, locationId);
  };

  /** @param {string} dataset Dataset to select */
  const selectDataset = (dataset) => {
    setSelectedDataset(dataset);
    loadDicomStores(selectedProject, selectedLocation, dataset);
  };

  /** @param {string} dicomStore Dicom Store to select */
  const selectDicomStore = (dicomStore) => {
    setSelectedDicomStore(dicomStore);
    loadStudies(selectedProject, selectedLocation, selectedDataset, dicomStore);
  };

  /** @param {Object} study Study to select */
  const selectStudy = (study) => {
    setSelectedStudy(study);

    loadSeries(selectedProject, selectedLocation, selectedDataset,
        selectedDicomStore, study['0020000D'].Value[0]);
  };

  /** @param {Object} series Series to select */
  const selectSeries = (series) => {
    setSelectedSeries(series);
  };

  /**
   * Clears all state up to and including project and reloads
   * projects
   */
  const clearAndLoadProjects = () => {
    setSelectedProject(null);

    clearLocation();
    setLocations([]);

    loadProjects();
  };

  /** Clears all state up to and including location */
  const clearLocation = () => {
    setSelectedLocation(null);

    clearDataset();
    setDatasets([]);
  };
  /** Clears location state and reloads locations list */
  const clearAndLoadLocations = () => {
    clearLocation();
    loadLocations(selectedProject);
  };

  /** Clears all state up to and including dataset */
  const clearDataset = () => {
    setSelectedDataset(null);

    clearDicomStore();
    setDicomStores([]);
  };
  /** Clears dataset state and reloads dataset list */
  const clearAndLoadDatasets = () => {
    clearDataset();
    loadDatasets(selectedProject, selectedLocation);
  };

  /** Clears all state up to and including dicom store */
  const clearDicomStore = () => {
    setSelectedDicomStore(null);

    clearStudy();
    setStudies([]);
  };
  /** Clears dicomStore state and reloads dicomStore list */
  const clearAndLoadDicomStores = () => {
    clearDicomStore();
    loadDicomStores(selectedProject, selectedLocation, selectedDataset);
  };

  /** Clears all state up to and including study */
  const clearStudy = () => {
    setSelectedStudy(null);

    clearSeries();
    setSeries([]);
  };
  /** Clears study state and reloads study list */
  const clearAndLoadStudies = () => {
    clearStudy();
    loadStudies(selectedProject, selectedLocation,
        selectedDataset, selectedDicomStore);
  };

  /** Clears all state up to and including series */
  const clearSeries = () => {
    setSelectedSeries(null);
  };
  /** Clears series state and reloads series list */
  const clearAndLoadSeries = () => {
    clearSeries();
    loadSeries(selectedProject, selectedLocation,
        selectedDataset, selectedDicomStore,
        selectedStudy['0020000D'].Value[0]);
  };

  const handleProjectSearch = (searchQuery) => {
    loadFilteredProjects(searchQuery);
  };

  return (

      <Box m={2} display="flex" flexDirection="row">
        <Box flexGrow={1}>
          <Breadcrumbs>
            {selectedProject ?
              <Link color="inherit" href="#" onClick={clearAndLoadProjects}>
                {selectedProject}
              </Link> :
              <Typography color="textPrimary">
                Select Project
              </Typography>}
            {selectedLocation ?
              <Link color="inherit" href="#" onClick={clearAndLoadLocations}>
                {selectedLocation}
              </Link> :
              selectedProject ?
                <Typography color="textPrimary">
                  Select Location
                </Typography> : null}
            {selectedDataset ?
              <Link color="inherit" href="#" onClick={clearAndLoadDatasets}>
                {selectedDataset}
              </Link> :
              selectedLocation ?
                <Typography color="textPrimary">
                  Select Dataset
                </Typography> : null}
            {selectedDicomStore ?
              <Link color="inherit" href="#" onClick={clearAndLoadDicomStores}>
                {selectedDicomStore}
              </Link> :
              selectedDataset ?
                <Typography color="textPrimary">
                  Select Dicom Store
                </Typography> : null}
            {selectedStudy ?
              <Link color="inherit" href="#" onClick={clearAndLoadStudies}>
                {selectedStudy.displayValue}
              </Link> :
              selectedDicomStore ?
                <Typography color="textPrimary">
                  Select Study
                </Typography> : null}
            {selectedSeries ?
              <Link color="inherit" href="#" onClick={clearAndLoadSeries}>
                {selectedSeries.displayValue}
              </Link> :
              selectedStudy ?
                <Typography color="textPrimary">
                  Select Series
                </Typography> : null}
          </Breadcrumbs>
        </Box>
      </Box>

      {!selectedProject ?
        <SearchList
          items={projects}
          onClickItem={selectProject}
          isLoading={projectsLoading}
          onSearch={handleProjectSearch}
          searchDelay={200} /> : null}
      {(selectedProject && !selectedLocation) ?
        <SearchList
          items={locations}
          onClickItem={selectLocation}
          isLoading={locationsLoading} /> : null}
      {(selectedLocation && !selectedDataset) ?
        <SearchList
          items={datasets}
          onClickItem={selectDataset}
          isLoading={datasetsLoading} /> : null}
      {(selectedDataset && !selectedDicomStore) ?
        <SearchList
          items={dicomStores}
          onClickItem={selectDicomStore}
          isLoading={dicomStoresLoading} /> : null}
      {(selectedDicomStore && !selectedStudy) ?
        <SearchList
          items={studies}
          onClickItem={selectStudy}
          isLoading={studiesLoading} /> : null}
      {(selectedStudy && !selectedSeries) ?
        <SearchList
          items={series}
          onClickItem={selectSeries}
          isLoading={seriesLoading} /> : null}

  );
}
<|endoftext|>


<commit_before>var assert = require('assert');
var mongoose = require('mongoose');
var async = require('async');
var fs = require('fs');
var crypto = require('crypto');
var supertest = require('supertest');
var httpStatus = require('http-status');
var path = require('path');
var chai = require('chai');
var expect = chai.expect;

// configs
var config = require('../config.js').serverConfig;
var User = require('../../models/user');
var Project = require('../../models/project');
var Layer = require('../../models/layer');
var File = require('../../models/file');
var helpers = require('../helpers');
var token = helpers.token;
var expected = require('../../shared/errors');
var httpStatus = require('http-status');
var endpoints = require('../endpoints.js');
var testData = require('../shared/upload/import_data.json');
var tmp = {};

// api
var domain = (process.env.MAPIC_DOMAIN == 'localhost') ? 'https://172.17.0.1' : 'https://' + process.env.MAPIC_DOMAIN;
var api = supertest(domain);

// Avoids DEPTH_ZERO_SELF_SIGNED_CERT error for self-signed certs
// See https://github.com/systemapic/pile/issues/38
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;

module.exports = function () {

    describe('Shapefile', function () {

        // prepare test
        before(function(callback) {
            // create tmp user, project
            async.series([helpers.create_project], callback);
        });
        after(function(callback) {
            // delete tmp user, project
            async.series([helpers.delete_project], callback);
        });

        describe('POST ' + endpoints.import.post, function () {
            this.slow(500);

            // context('shapefile.polygon.zip', function () {
                this.timeout(21000);

                it('upload shapefile.polygon.zip', function (done) {
                    token(function (err, access_token) {
                        api.post(endpoints.import.post)
                        .type('form')
                        .field('access_token', access_token)
                        .field('data', fs.createReadStream(path.resolve(__dirname, '../open-data/shapefile.polygon.zip')))
                        .expect(httpStatus.OK)
                        .end(function (err, res) {
                            assert.ifError(err);
                            var result = helpers.parse(res.text);
                            assert.ok(result.file_id);
                            assert.ok(result.user_id);
                            assert.ok(result.upload_success);
                            assert.equal(result.filename, 'shapefile.polygon.zip');
                            assert.equal(result.status, 'Processing');
                            assert.ifError(result.error_code);
                            assert.ifError(result.error_text);

                            tmp.file_id = result.file_id;
                            done();
                        });
                    });
                });

                it('get status', function (done) {
                    token(function (err, access_token) {
                        api.get(endpoints.import.status)
                        .query({file_id : tmp.file_id, access_token : access_token})
                        .expect(httpStatus.OK)
                        .end(function (err, res) {
                            assert.ifError(err);
                            var result = helpers.parse(res.text);
                            assert.ok(result.file_id);
                            assert.ok(result.user_id);
                            assert.ok(result.upload_success);
                            assert.equal(result.filename, 'shapefile.polygon.zip');
                            assert.equal(result.status, 'Processing');
                            assert.ifError(result.error_code);
                            assert.ifError(result.error_text);
                            done();
                        });
                    })
                });

            // });

        //     context.skip('shapefile.missing-prj.zip', function () {

        //         it('upload shapefile.missing-prj.zip', function (done) {
        //             token(function (err, access_token) {
        //                 api.post(endpoints.import.post)
        //                 .type('form')
        //                 .field('userUuid', util.test_user.uuid)
        //                 .field('access_token', access_token)
        //                 .field('data', fs.createReadStream(path.resolve(__dirname, '../open-data/shapefile.missing-prj.zip')))
        //                 .expect(httpStatus.OK)
        //                 .end(function (err, res) {
        //                     assert.ifError(err);
        //                     var result = helpers.parse(res.text);
        //                     assert.ok(result.file_id);
        //                     assert.ok(result.user_id);
        //                     assert.ok(result.upload_success);
        //                     assert.equal(result.filename, 'shapefile.missing-prj.zip');
        //                     assert.equal(result.status, 'Processing');
        //                     assert.ifError(result.error_code);
        //                     assert.ifError(result.error_text);

        //                     tmp.file_id = result.file_id;
        //                     done();
        //                 });
        //             });
        //         });

        //         it('get status', function (done) {
        //             token(function (err, access_token) {
        //                 api.get(endpoints.import.status)
        //                 .query({ file_id : tmp.file_id, access_token : access_token})
        //                 .expect(httpStatus.OK)
        //                 .end(function (err, res) {
        //                     assert.ifError(err);
        //                     var result = helpers.parse(res.text);
        //                     assert.ok(result.file_id);
        //                     assert.ok(result.user_id);
        //                     assert.ok(result.upload_success);
        //                     assert.equal(result.filename, 'shapefile.missing-prj.zip');
        //                     assert.equal(result.status, 'Processing');
        //                     assert.ifError(result.error_code);
        //                     assert.ifError(result.error_text);
        //                     done();
        //                 });
        //             })
        //         });
        //     });

        // // });

        // describe('Process', function () {
            this.slow(500);

            it('should be processed', function (done) {
                this.timeout(11000);
                this.slow(5000);

                token(function (err, access_token) {
                // check for processing status
                    var processingInterval = setInterval(function () {
                    process.stdout.write('.');
                        api.get(endpoints.import.status)
                        .query({ file_id : tmp.file_id, access_token : access_token})
                        .end(function (err, res) {
                            assert.ifError(err);
                            var status = helpers.parse(res.text);

                            // return when import done
                            if (status.processing_success) {
                                clearInterval(processingInterval);
                                done();
                            }
                        });
                    }, 500);
                });

            });

            it('should be processed without errors', function (done) {
                token(function (err, access_token) {
                    api.get(endpoints.import.status)
                    .query({file_id : tmp.file_id, access_token : access_token})
                    .expect(httpStatus.OK)
                    .end(function (err, res) {
                        assert.ifError(err);
                        var status = helpers.parse(res.text);
                        assert.ifError(err);
                        assert.ok(status.upload_success);
                        assert.ifError(status.error_code);
                        assert.ifError(status.error_text);
                        assert.equal(status.user_id, helpers.test_user.uuid);
                        assert.equal(status.data_type, 'vector');
                        assert.ok(status.processing_success);
                        assert.equal(status.status, 'Done');
                        assert.equal(status.rows_count, 13);
                        done();
                    });
                })
            });

        // });

        });

        describe('GET ' + endpoints.import.download, function () {
            this.slow(500);

            it("200 & download as file", function (done) {
                token(function (err, access_token) {
                    if (err) {
                        return done(err);
                    }

                    api.get(endpoints.import.download)
                        .query({file_id: tmp.file_id, access_token: access_token})
                        .expect(httpStatus.OK)
                        .end(function (err, res) {
                            if (err) {
                                return done(err);
                            }

                            var result = helpers.parse(res.text);

                            expect(result.file.type).to.be.equal('postgis');
                            expect(result.file.originalName).to.be.equal('shapefile.polygon.zip');
                            expect(result.file.name).to.be.equal('shapefile.polygon');
                            done();
                        });
                });
            });

        });

        describe('POST ' + endpoints.data.delete, function () {
            this.slow(500);

            var relatedLayer = testData.relatedLayer;
            var relatedProject = testData.relatedProject;

            before(function (done) {
                var ops = [];

                ops.push(function (callback) {

                    relatedLayer.data = {
                        postgis: {
                            table_name: tmp.file_id
                        }
                    };

                    helpers.create_layer_by_parameters(relatedLayer, function (err, res) {
                        if (err) {
                            callback(err);
                        }
                        relatedLayer = res;
                        callback(null, relatedLayer);
                    });
                });

                ops.push(function (options, callback) {
                    relatedProject.layers = [options];

                    helpers.create_project_by_info(relatedProject, function (err, res) {
                        if (err) {
                            callback(err);
                        }

                        relatedProject = res;
                        callback(null, relatedProject);
                    });
                });

                async.waterfall(ops, done);
            });

            after(function (done) {
                var ops = [];

                ops.push(function (callback) {
                    helpers.delete_project_by_id(relatedProject.uuid, callback);
                });

                ops.push(function (options, callback) {
                    helpers.delete_layer_by_id(relatedLayer.uuid, callback);
                });

                async.waterfall(ops, done);
            });

            it('should be able to delete file correctly', function (done) {
                var ops = [];

                ops.push(function (callback) {
                    token(function (err, access_token) {
                        api.post(endpoints.data.delete)
                        .send({file_id : tmp.file_id, access_token : access_token})
                        .expect(httpStatus.OK)
                        .end(function (err, res) {
                            if (err) {
                                return callback(err);
                            }

                            var result = helpers.parse(res.text);
                            expect(result.success).to.be.true;

                            callback(null, result);
                        });
                    });
                });

                ops.push(function (options, callback) {
                    Project.findOne({uuid: relatedProject.uuid})
                        .exec(function (err, updatedProject) {
                            if (err) {
                                return callback(err);
                            }
                            expect(updatedProject.layers).to.be.empty;
                            callback(null, updatedProject);
                        });
                });

                ops.push(function (options, callback) {
                    Layer.find({uuid: relatedLayer.uuid})
                        .exec(function (err, updatedLayer) {
                            if (err) {
                                return callback(err);
                            }
                            expect(updatedLayer).to.be.empty;
                            callback(null, updatedLayer);
                        });
                });

                ops.push(function (options, callback) {
                    File.find({uuid: tmp.file_id})
                        .exec(function (err, result) {
                            if (err) {
                                return callback(err);
                            }
                            expect(result).to.be.empty;
                            callback(null, result);
                        });
                });

                async.waterfall(ops, done);

            });

        });

    });

};
<commit_msg>fixed test<commit_after>var assert = require('assert');
var mongoose = require('mongoose');
var async = require('async');
var fs = require('fs');
var crypto = require('crypto');
var supertest = require('supertest');
var httpStatus = require('http-status');
var path = require('path');
var chai = require('chai');
var expect = chai.expect;

// configs
var config = require('../../config.js').serverConfig;
var User = require('../../models/user');
var Project = require('../../models/project');
var Layer = require('../../models/layer');
var File = require('../../models/file');
var helpers = require('../helpers');
var token = helpers.token;
var expected = require('../../shared/errors');
var httpStatus = require('http-status');
var endpoints = require('../endpoints.js');
var testData = require('../shared/upload/import_data.json');
var tmp = {};

// api
var domain = (process.env.MAPIC_DOMAIN == 'localhost') ? 'https://172.17.0.1' : 'https://' + process.env.MAPIC_DOMAIN;
var api = supertest(domain);

// Avoids DEPTH_ZERO_SELF_SIGNED_CERT error for self-signed certs
// See https://github.com/systemapic/pile/issues/38
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;

module.exports = function () {

    describe('Shapefile', function () {

        // prepare test
        before(function(callback) {
            // create tmp user, project
            async.series([helpers.create_project], callback);
        });
        after(function(callback) {
            // delete tmp user, project
            async.series([helpers.delete_project], callback);
        });

        describe('POST ' + endpoints.import.post, function () {
            this.slow(500);

            // context('shapefile.polygon.zip', function () {
                this.timeout(21000);

                it('upload shapefile.polygon.zip', function (done) {
                    token(function (err, access_token) {
                        api.post(endpoints.import.post)
                        .type('form')
                        .field('access_token', access_token)
                        .field('data', fs.createReadStream(path.resolve(__dirname, '../open-data/shapefile.polygon.zip')))
                        .expect(httpStatus.OK)
                        .end(function (err, res) {
                            assert.ifError(err);
                            var result = helpers.parse(res.text);
                            assert.ok(result.file_id);
                            assert.ok(result.user_id);
                            assert.ok(result.upload_success);
                            assert.equal(result.filename, 'shapefile.polygon.zip');
                            assert.equal(result.status, 'Processing');
                            assert.ifError(result.error_code);
                            assert.ifError(result.error_text);

                            tmp.file_id = result.file_id;
                            done();
                        });
                    });
                });

                it('get status', function (done) {
                    token(function (err, access_token) {
                        api.get(endpoints.import.status)
                        .query({file_id : tmp.file_id, access_token : access_token})
                        .expect(httpStatus.OK)
                        .end(function (err, res) {
                            assert.ifError(err);
                            var result = helpers.parse(res.text);
                            assert.ok(result.file_id);
                            assert.ok(result.user_id);
                            assert.ok(result.upload_success);
                            assert.equal(result.filename, 'shapefile.polygon.zip');
                            assert.equal(result.status, 'Processing');
                            assert.ifError(result.error_code);
                            assert.ifError(result.error_text);
                            done();
                        });
                    })
                });

            // });

        //     context.skip('shapefile.missing-prj.zip', function () {

        //         it('upload shapefile.missing-prj.zip', function (done) {
        //             token(function (err, access_token) {
        //                 api.post(endpoints.import.post)
        //                 .type('form')
        //                 .field('userUuid', util.test_user.uuid)
        //                 .field('access_token', access_token)
        //                 .field('data', fs.createReadStream(path.resolve(__dirname, '../open-data/shapefile.missing-prj.zip')))
        //                 .expect(httpStatus.OK)
        //                 .end(function (err, res) {
        //                     assert.ifError(err);
        //                     var result = helpers.parse(res.text);
        //                     assert.ok(result.file_id);
        //                     assert.ok(result.user_id);
        //                     assert.ok(result.upload_success);
        //                     assert.equal(result.filename, 'shapefile.missing-prj.zip');
        //                     assert.equal(result.status, 'Processing');
        //                     assert.ifError(result.error_code);
        //                     assert.ifError(result.error_text);

        //                     tmp.file_id = result.file_id;
        //                     done();
        //                 });
        //             });
        //         });

        //         it('get status', function (done) {
        //             token(function (err, access_token) {
        //                 api.get(endpoints.import.status)
        //                 .query({ file_id : tmp.file_id, access_token : access_token})
        //                 .expect(httpStatus.OK)
        //                 .end(function (err, res) {
        //                     assert.ifError(err);
        //                     var result = helpers.parse(res.text);
        //                     assert.ok(result.file_id);
        //                     assert.ok(result.user_id);
        //                     assert.ok(result.upload_success);
        //                     assert.equal(result.filename, 'shapefile.missing-prj.zip');
        //                     assert.equal(result.status, 'Processing');
        //                     assert.ifError(result.error_code);
        //                     assert.ifError(result.error_text);
        //                     done();
        //                 });
        //             })
        //         });
        //     });

        // // });

        // describe('Process', function () {
            this.slow(500);

            it('should be processed', function (done) {
                this.timeout(11000);
                this.slow(5000);

                token(function (err, access_token) {
                // check for processing status
                    var processingInterval = setInterval(function () {
                    process.stdout.write('.');
                        api.get(endpoints.import.status)
                        .query({ file_id : tmp.file_id, access_token : access_token})
                        .end(function (err, res) {
                            assert.ifError(err);
                            var status = helpers.parse(res.text);

                            // return when import done
                            if (status.processing_success) {
                                clearInterval(processingInterval);
                                done();
                            }
                        });
                    }, 500);
                });

            });

            it('should be processed without errors', function (done) {
                token(function (err, access_token) {
                    api.get(endpoints.import.status)
                    .query({file_id : tmp.file_id, access_token : access_token})
                    .expect(httpStatus.OK)
                    .end(function (err, res) {
                        assert.ifError(err);
                        var status = helpers.parse(res.text);
                        assert.ifError(err);
                        assert.ok(status.upload_success);
                        assert.ifError(status.error_code);
                        assert.ifError(status.error_text);
                        assert.equal(status.user_id, helpers.test_user.uuid);
                        assert.equal(status.data_type, 'vector');
                        assert.ok(status.processing_success);
                        assert.equal(status.status, 'Done');
                        assert.equal(status.rows_count, 13);
                        done();
                    });
                })
            });

        // });

        });

        describe('GET ' + endpoints.import.download, function () {
            this.slow(500);

            it("200 & download as file", function (done) {
                token(function (err, access_token) {
                    if (err) {
                        return done(err);
                    }

                    api.get(endpoints.import.download)
                        .query({file_id: tmp.file_id, access_token: access_token})
                        .expect(httpStatus.OK)
                        .end(function (err, res) {
                            if (err) {
                                return done(err);
                            }

                            var result = helpers.parse(res.text);

                            expect(result.file.type).to.be.equal('postgis');
                            expect(result.file.originalName).to.be.equal('shapefile.polygon.zip');
                            expect(result.file.name).to.be.equal('shapefile.polygon');
                            done();
                        });
                });
            });

        });

        describe('POST ' + endpoints.data.delete, function () {
            this.slow(500);

            var relatedLayer = testData.relatedLayer;
            var relatedProject = testData.relatedProject;

            before(function (done) {
                var ops = [];

                ops.push(function (callback) {

                    relatedLayer.data = {
                        postgis: {
                            table_name: tmp.file_id
                        }
                    };

                    helpers.create_layer_by_parameters(relatedLayer, function (err, res) {
                        if (err) {
                            callback(err);
                        }
                        relatedLayer = res;
                        callback(null, relatedLayer);
                    });
                });

                ops.push(function (options, callback) {
                    relatedProject.layers = [options];

                    helpers.create_project_by_info(relatedProject, function (err, res) {
                        if (err) {
                            callback(err);
                        }

                        relatedProject = res;
                        callback(null, relatedProject);
                    });
                });

                async.waterfall(ops, done);
            });

            after(function (done) {
                var ops = [];

                ops.push(function (callback) {
                    helpers.delete_project_by_id(relatedProject.uuid, callback);
                });

                ops.push(function (options, callback) {
                    helpers.delete_layer_by_id(relatedLayer.uuid, callback);
                });

                async.waterfall(ops, done);
            });

            it('should be able to delete file correctly', function (done) {
                var ops = [];

                ops.push(function (callback) {
                    token(function (err, access_token) {
                        api.post(endpoints.data.delete)
                        .send({file_id : tmp.file_id, access_token : access_token})
                        .expect(httpStatus.OK)
                        .end(function (err, res) {
                            if (err) {
                                return callback(err);
                            }

                            var result = helpers.parse(res.text);
                            expect(result.success).to.be.true;

                            callback(null, result);
                        });
                    });
                });

                ops.push(function (options, callback) {
                    Project.findOne({uuid: relatedProject.uuid})
                        .exec(function (err, updatedProject) {
                            if (err) {
                                return callback(err);
                            }
                            expect(updatedProject.layers).to.be.empty;
                            callback(null, updatedProject);
                        });
                });

                ops.push(function (options, callback) {
                    Layer.find({uuid: relatedLayer.uuid})
                        .exec(function (err, updatedLayer) {
                            if (err) {
                                return callback(err);
                            }
                            expect(updatedLayer).to.be.empty;
                            callback(null, updatedLayer);
                        });
                });

                ops.push(function (options, callback) {
                    File.find({uuid: tmp.file_id})
                        .exec(function (err, result) {
                            if (err) {
                                return callback(err);
                            }
                            expect(result).to.be.empty;
                            callback(null, result);
                        });
                });

                async.waterfall(ops, done);

            });

        });

    });

};
<|endoftext|>


<commit_before>'use strict'

const iceworm = require(__dirname + '/../index.js')
const should = require('chai').should()
const expect = require('chai').expect

before(() => {
  iceworm.Schema.create({a:'*string'}, 'inner')
  iceworm.Schema.create({a:'string', b:'*inner'}, 'outer')
})

describe("Embedded Types Validation", () => {
  it("Required", () => {
    // arrange
    let inner = iceworm.Schema.fromCache('inner')
    let outer = iceworm.Schema.fromCache('outer')
    let obj_valid = {a:'a', b:{a:'a'}}
    let obj_invalid = {a:'a'}
    // act
    let result_valid = iceworm.validate(obj_valid, outer)
    let result_invalid = iceworm.validate(obj_invalid, outer)
    // assert
    expect(result_valid.valid).to.equal(true)
    expect(result_invalid.valid).to.equal(false)
  })

  it("Embedded Has Required", () => {
    // arrange
    let inner = iceworm.Schema.fromCache('inner')
    let outer = iceworm.Schema.fromCache('outer')
    let obj_valid = {a:'a', b:{a:'a'}}
    let obj_invalid = {a:'a', b:{}}
    // act
    let result_valid = iceworm.validate(obj_valid, outer)
    let result_invalid = iceworm.validate(obj_invalid, outer)
    // assert
    expect(result_valid.valid).to.equal(true)
    expect(result_invalid.valid).to.equal(false)
  })
})

/*
 // arrange: create a schema to embed, and a schema having the embedded schema
 let animalSchema = iceworm.Schema.create({name: '*string'}, 'animal')
 let ownerSchema = iceworm.Schema.create({name: '*string', pet: '*animal'})
 // act
 let obj_valid = {name:'Marie', pet:{name:'Lamb'}}
 let obj_invalid_1 = {name:'Marie'}
 let obj_invalid_2 = {name:'Marie', pet:{age:4}}
 let validation_valid = iceworm.validate(obj_valid, ownerSchema)
 let validation_invalid_1 = iceworm.validate(obj_invalid_1, ownerSchema)
 let validation_invalid_2 = iceworm.validate(obj_invalid_2, ownerSchema)
 // assert
 validation_valid.valid.should.equal(true)
 */<commit_msg>test of schema with array of embedded types added<commit_after>'use strict'

const iceworm = require(__dirname + '/../index.js')
const should = require('chai').should()
const expect = require('chai').expect

before(() => {
  iceworm.Schema.create({a:'*string'}, 'inner')
  iceworm.Schema.create({a:'string', b:'*inner'}, 'outer')
  iceworm.Schema.create({a:'string', b:'*inner[]', 'outer_array'})
})

describe("Embedded Types Validation", () => {
  it("Required", () => {
    // arrange
    let inner = iceworm.Schema.fromCache('inner')
    let outer = iceworm.Schema.fromCache('outer')
    let obj_valid = {a:'a', b:{a:'a'}}
    let obj_invalid = {a:'a'}
    // act
    let result_valid = iceworm.validate(obj_valid, outer)
    let result_invalid = iceworm.validate(obj_invalid, outer)
    // assert
    expect(result_valid.valid).to.equal(true)
    expect(result_invalid.valid).to.equal(false)
  })

  it("Embedded Has Required", () => {
    // arrange
    let inner = iceworm.Schema.fromCache('inner')
    let outer = iceworm.Schema.fromCache('outer')
    let obj_valid = {a:'a', b:{a:'a'}}
    let obj_invalid = {a:'a', b:{}}
    // act
    let result_valid = iceworm.validate(obj_valid, outer)
    let result_invalid = iceworm.validate(obj_invalid, outer)
    // assert
    expect(result_valid.valid).to.equal(true)
    expect(result_invalid.valid).to.equal(false)
  })

  it("Array of Embedded Type", () => {
    // arrange
    let inner = iceworm.Schema.fromCache('inner')
    let outer = iceworm.Schema.fromCache('outer_array')
    let obj_valid = {a:'a', b:[{a:'a'},{a:'b'}]}
    let obj_invalid = {a:'a', b:[{something:'a'},{a:'b'}]}
    // act
    let result_valid = iceworm.validate(obj_valid, outer)
    let result_invalid = iceworm.validate(obj_invalid, outer)
    // assert
    expect(result_valid.valid).to.equal(true)
    expect(result_invalid.valid).to.equal(false)
  })
})

/*
 // arrange: create a schema to embed, and a schema having the embedded schema
 let animalSchema = iceworm.Schema.create({name: '*string'}, 'animal')
 let ownerSchema = iceworm.Schema.create({name: '*string', pet: '*animal'})
 // act
 let obj_valid = {name:'Marie', pet:{name:'Lamb'}}
 let obj_invalid_1 = {name:'Marie'}
 let obj_invalid_2 = {name:'Marie', pet:{age:4}}
 let validation_valid = iceworm.validate(obj_valid, ownerSchema)
 let validation_invalid_1 = iceworm.validate(obj_invalid_1, ownerSchema)
 let validation_invalid_2 = iceworm.validate(obj_invalid_2, ownerSchema)
 // assert
 validation_valid.valid.should.equal(true)
 */<|endoftext|>


<commit_before>'use strict';

var expect         = require('chai').expect;
var stub           = require('../../helpers/stub');
var commandOptions = require('../../factories/command-options');
var Task           = require('../../../lib/models/task');
var path           = require('path');

var safeRestore = stub.safeRestore;
stub = stub.stub;

describe('asset-sizes command', function () {
  var ShowCommand;
  var tasks;
  var options;
  var taskInstance;

  before(function () {
    ShowCommand = require('../../../lib/commands/asset-sizes');
  });

  beforeEach(function () {
    tasks = {
      ShowAssetSizes: Task.extend({
        init: function () {
          taskInstance = this;
        }
      })
    };

    options = commandOptions({
      tasks: tasks,
      settings: {}
    });

    stub(tasks.ShowAssetSizes.prototype, 'run');
  });

  after(function () {
    ShowCommand = null;
    taskInstance = null;
  });

  afterEach(function () {
    safeRestore(tasks.ShowAssetSizes.prototype, 'run');
  });

  it('has correct default value for output path', function() {
    return new ShowCommand(options).validateAndRun().then(function() {
      var run = tasks.ShowAssetSizes.prototype.run;
      var ops = run.calledWith[0][0];

      expect(run.called).to.equal(1, 'expected run to be called once');
      expect(ops.outputPath).to.equal('dist/', 'has correct output path option when not set');
    });
  });

  it('has correct options', function() {
    return new ShowCommand(options)
      .validateAndRun(['--output-path', path.join('some', 'path')])
      .then(function() {
        var run = tasks.ShowAssetSizes.prototype.run;
        var ops = run.calledWith[0][0];

        expect(run.called).to.equal(1, 'expected run to be called once');
        expect(ops.outputPath).to.equal(path.join(process.cwd(), 'some', 'path'), 'has correct asset path');
      });
  });
});

describe.skip('default options config file', function() {
  it('reads default options from .ember-cli file', function() {});
});
<commit_msg>tests/commands/show-asset-sizes: Use testdouble for mocks<commit_after>'use strict';

var expect         = require('chai').expect;
var commandOptions = require('../../factories/command-options');
var Task           = require('../../../lib/models/task');
var path           = require('path');
var td = require('testdouble');

describe('asset-sizes command', function () {
  var ShowCommand;
  var tasks;
  var options;
  var taskInstance;

  before(function () {
    ShowCommand = require('../../../lib/commands/asset-sizes');
  });

  beforeEach(function () {
    tasks = {
      ShowAssetSizes: Task.extend({
        init: function () {
          taskInstance = this;
        }
      })
    };

    options = commandOptions({
      tasks: tasks,
      settings: {}
    });

    td.replace(tasks.ShowAssetSizes.prototype, 'run', td.function());
  });

  after(function () {
    ShowCommand = null;
    taskInstance = null;
  });

  afterEach(function () {
    td.reset();
  });

  it('has correct default value for output path', function() {
    return new ShowCommand(options).validateAndRun().then(function() {
      var captor = td.matchers.captor();
      td.verify(tasks.ShowAssetSizes.prototype.run(captor.capture()), {times: 1});
      expect(captor.value.outputPath).to.equal('dist/', 'has correct output path option when not set');
    });
  });

  it('has correct options', function() {
    return new ShowCommand(options)
      .validateAndRun(['--output-path', path.join('some', 'path')])
      .then(function() {
        var captor = td.matchers.captor();
        td.verify(tasks.ShowAssetSizes.prototype.run(captor.capture()), {times: 1});
        expect(captor.value.outputPath).to.equal(path.join(process.cwd(), 'some', 'path'), 'has correct asset path');
      });
  });
});

describe.skip('default options config file', function() {
  it('reads default options from .ember-cli file', function() {});
});
<|endoftext|>


<commit_before>// 参考jsTree:  https://github.com/vakata/jstree
// 参考： https://github.com/leegent/leegent.github.io/blob/master/ife2016/task25/task25.js

function TreeNode(config) {
	this.container = config.container;
	this.initNode = config.core.data;
}

/**
 * 初始化函数
 * @return {[type]} [description]
 */
TreeNode.prototype.init = function () {
	var initNode = this.initNode;
	var tempArr = [];
	// 判断初始树结构是否为空
	if (initNode == null || initNode.length == 0) return alert("请创建初始节点");

	for(var i = 0;i < initNode.length;i++) {
		if (initNode[i].parent == "#") {
			// var div = document.createElement("div");
			// div.setAttribute("id", initNode[i].id);
			// div.innerText = initNode[i].text;
			// this.container.appendChild(div);

			this.addNode(this.container, initNode[i].id, initNode[i].text, true);

		} else {
			var parent = document.getElementById(initNode[i].parent);
			// 判断初始化节点的父节点是否已渲染到页面
			// 是 —— 添加节点到父节点
			if (parent) {
				// var div = document.createElement("div");
				// div.setAttribute("id", initNode[i].id);
				// div.innerText = initNode[i].text;
				// parent.appendChild(div);

				this.addNode(parent, initNode[i].id, initNode[i].text, false);
			} else {
				// 否 —— 将此节点信息推入栈
				tempArr.push(initNode[i]);
			}
		}
	}

	// 所有节点渲染完成后，判断是否有节点还未添加
	if (tempArr.length > 0) {
		// 遍历存储栈，再次判断未插入节点的父节点是否存在
		// 存在 —— 将节点添加到父节点后
		// 不存在 —— 输出提示信息
		for(var j = 0;j < tempArr.length;j++) {
			var tempParentNode = document.getElementById(tempArr[j].parent);
			if (tempParentNode) {
				// var temp_div = document.createElement("div");
				// temp_div.setAttribute("id", tempArr[i].id);
				// temp_div.innerText = tempArr[i].text;
				// tempParentNode.appendChild(temp_div);

				this.addNode(tempParentNode, tempArr[i].id, tempArr[i].text, false);
			} else {
				alert("未找到 " + tempArr[i].id + " 该节点的父节点");
			}
		}
	}

	bind(this.container, this.toggleFold);
}

TreeNode.prototype.addNode = function (targetNode, id, text, isRoot) {
	// 最外层节点
	var outside_node = document.createElement("div");
	// 节点中的文字内容
	var header_node = document.createElement("div");
	// 添加节点属性
	outside_node.setAttribute("id", id);
	if (isRoot) {
		outside_node.setAttribute("class", "outside_node actived");
	} else {
		outside_node.setAttribute("class", "outside_node hidden");
	}

	header_node.setAttribute("class", "header_node");
	header_node.innerText = text;

	outside_node.appendChild(header_node);
	targetNode.appendChild(outside_node);
}

// 此种DOM构建方法感觉不是很好
// 另外的一种构建的想法是 父节点下只包含两个节点，一个作为title展示，另一个保存所有的Child节点
TreeNode.prototype.toggleFold = function (elem) {
	var children = elem.children;

	for(var i = 1;i < children.length;i++) {
		if (children[i].className == "outside_node active") {
			children[i].className = "outside_node hidden";
		} else {
			children[i].className = "outside_node active";
		}
	}
}

// mouseenter -- 在鼠标从元素外部首次移动到元素范围之内时触发
//
// mouseover -- 在鼠标位于一个元素外部，首次移入另一个元素的边界之内时触发
//
// mousemove -- 在鼠标在元素内移动时重复地触发

// 当点击某一节点时，
function bind(container, toggleFold) {
	var headers = document.querySelectorAll(".header_node");
	var count = 0; // 测试click事件执行了多少次
	addHandler(container, 'mouseenter', function (event) {
		console.log(event.currentTarget);
		var parent = event.target.parentNode;
		if (parent.children.length > 1) {
			addHandler(event.target, 'click', function (event) {
				if (event.target.className == "header_node") {
					++count;
					console.log(count);
					console.log(event.target);
					toggleFold(event.target.parentNode);
				} else {
					return;
				}
			});
		}
	});
}

/**
 * data structure
 * 初始化节点结构
 */
/*var config = {
	'container': document.querySelector(".main"),
	'core': {
		'data': [
			// 根节点
			{"id": "root", "parent": "#", "text": "前端工程师"},
			// 二级节点
			{"id": "node_1", "parent": "root", "text": "技术"},
			{"id": "node_2", "parent": "root", "text": "IT公司"},
			{"id": "node_3", "parent": "root", "text": "技术"},
			// 三级节点
			// 技术
			{"id": "node_1_1", "parent": "node_1", "text": "HTML5"},
			{"id": "node_1_2", "parent": "node_1", "text": "JavaScript"},
			{"id": "node_1_3", "parent": "node_1", "text": "PHP"},
			{"id": "node_1_4", "parent": "node_1", "text": "Node.js"},
			// IT公司
			{"id": "node_2_1", "parent": "node_2", "text": "baidu"},
			{"id": "node_2_2", "parent": "node_2", "text": "meituan"},
			{"id": "node_2_3", "parent": "node_2", "text": "qunar"},
			// 生活
			{"id": "node_3_1", "parent": "node_3", "text": "美食"},
			{"id": "node_3_2", "parent": "node_3", "text": "旅游"},
			// 四级节点
			// Node.js
			{"id": "node_4_1", "parent": "node_1_4", "text": "grunt"},
			{"id": "node_4_2", "parent": "node_1_4", "text": "gulp"},
		]
	}
}

*/

function addHandler(element, type, handler) {
	if (element.addEventListener) {
		addHandler = function (element, type, handler) {
			element.addEventListener(type, handler, false);
		}
	} else if (element.attachEvent) {
		addHandler = function (element, type, handler) {
			element.attachEvent("on" +type, handler );
		}
	} else {
		addHandler = function (element, type, handler) {
			element["on" + type] = handler;
		}
	}

	return addHandler(element, type, handler);
}

(function () {
	/**
	 * data structure
	 * 初始化节点结构
	 */
	var config = {
		'container': document.querySelector(".main"),
		'core': {
			'data': [
				// 根节点
				{"id": "root", "parent": "#", "text": "前端工程师"},
				// 二级节点
				{"id": "node_1", "parent": "root", "text": "技术"},
				{"id": "node_2", "parent": "root", "text": "IT公司"},
				{"id": "node_3", "parent": "root", "text": "生活"},
				// 三级节点
				// 技术
				{"id": "node_1_1", "parent": "node_1", "text": "HTML5"},
				{"id": "node_1_2", "parent": "node_1", "text": "JavaScript"},
				{"id": "node_1_3", "parent": "node_1", "text": "PHP"},
				{"id": "node_1_4", "parent": "node_1", "text": "Node.js"},
				// IT公司
				{"id": "node_2_1", "parent": "node_2", "text": "baidu"},
				{"id": "node_2_2", "parent": "node_2", "text": "meituan"},
				{"id": "node_2_3", "parent": "node_2", "text": "qunar"},
				// 生活
				{"id": "node_3_1", "parent": "node_3", "text": "美食"},
				{"id": "node_3_2", "parent": "node_3", "text": "旅游"},
				// 四级节点
				// Node.js
				{"id": "node_4_1", "parent": "node_1_4", "text": "grunt"},
				{"id": "node_4_2", "parent": "node_1_4", "text": "gulp"},
			]
		}
	}

	var treeNode = new TreeNode(config);

	treeNode.init();
})();<commit_msg>添加解绑事件函数<commit_after>// 参考jsTree:  https://github.com/vakata/jstree
// 参考： https://github.com/leegent/leegent.github.io/blob/master/ife2016/task25/task25.js

function TreeNode(config) {
	this.container = config.container;
	this.initNode = config.core.data;
}

/**
 * 初始化函数
 * @return {[type]} [description]
 */
TreeNode.prototype.init = function () {
	var initNode = this.initNode;
	var tempArr = [];
	// 判断初始树结构是否为空
	if (initNode == null || initNode.length == 0) return alert("请创建初始节点");

	for(var i = 0;i < initNode.length;i++) {
		if (initNode[i].parent == "#") {
			// var div = document.createElement("div");
			// div.setAttribute("id", initNode[i].id);
			// div.innerText = initNode[i].text;
			// this.container.appendChild(div);

			this.addNode(this.container, initNode[i].id, initNode[i].text, true);

		} else {
			var parent = document.getElementById(initNode[i].parent);
			// 判断初始化节点的父节点是否已渲染到页面
			// 是 —— 添加节点到父节点
			if (parent) {
				// var div = document.createElement("div");
				// div.setAttribute("id", initNode[i].id);
				// div.innerText = initNode[i].text;
				// parent.appendChild(div);

				this.addNode(parent, initNode[i].id, initNode[i].text, false);
			} else {
				// 否 —— 将此节点信息推入栈
				tempArr.push(initNode[i]);
			}
		}
	}

	// 所有节点渲染完成后，判断是否有节点还未添加
	if (tempArr.length > 0) {
		// 遍历存储栈，再次判断未插入节点的父节点是否存在
		// 存在 —— 将节点添加到父节点后
		// 不存在 —— 输出提示信息
		for(var j = 0;j < tempArr.length;j++) {
			var tempParentNode = document.getElementById(tempArr[j].parent);
			if (tempParentNode) {
				// var temp_div = document.createElement("div");
				// temp_div.setAttribute("id", tempArr[i].id);
				// temp_div.innerText = tempArr[i].text;
				// tempParentNode.appendChild(temp_div);

				this.addNode(tempParentNode, tempArr[i].id, tempArr[i].text, false);
			} else {
				alert("未找到 " + tempArr[i].id + " 该节点的父节点");
			}
		}
	}

	bind(this.container, this.toggleFold);
}

TreeNode.prototype.addNode = function (targetNode, id, text, isRoot) {
	// 最外层节点
	var outside_node = document.createElement("div");
	// 节点中的文字内容
	var header_node = document.createElement("div");
	// 添加节点属性
	outside_node.setAttribute("id", id);
	if (isRoot) {
		outside_node.setAttribute("class", "outside_node actived");
	} else {
		outside_node.setAttribute("class", "outside_node hidden");
	}

	header_node.setAttribute("class", "header_node");
	header_node.innerText = text;

	outside_node.appendChild(header_node);
	targetNode.appendChild(outside_node);
}

// 此种DOM构建方法感觉不是很好
// 另外的一种构建的想法是 父节点下只包含两个节点，一个作为title展示，另一个保存所有的Child节点
TreeNode.prototype.toggleFold = function (elem) {
	var children = elem.children;

	for(var i = 1;i < children.length;i++) {
		if (children[i].className == "outside_node active") {
			children[i].className = "outside_node hidden";
		} else {
			children[i].className = "outside_node active";
		}
	}
}

// mouseenter -- 在鼠标从元素外部首次移动到元素范围之内时触发
//
// mouseover -- 在鼠标位于一个元素外部，首次移入另一个元素的边界之内时触发
//
// mousemove -- 在鼠标在元素内移动时重复地触发

// 当点击某一节点时，
function bind(container, toggleFold) {
	var headers = document.querySelectorAll(".header_node");
	var count = 0; // 测试click事件执行了多少次
	addHandler(container, 'mouseenter', function (event) {
		var parent = event.target.parentNode;
		if (parent.children.length > 1) {
			addHandler(event.target, 'click', function toggle(event) {
				if (event.target.className == "header_node") {
					++count;
					console.log(count);
					console.log(event.target);
					toggleFold(event.target.parentNode);
				} else {
					return;
				}
			});
		}
	});

	addHandler(container, 'mouseout', function (event) {
		var parent = event.target.parentNode;
		if (parent.children.length > 1) {
			removeHandler(event.target, 'click', toggle);
		}
	});
}

/**
 * data structure
 * 初始化节点结构
 */
/*var config = {
	'container': document.querySelector(".main"),
	'core': {
		'data': [
			// 根节点
			{"id": "root", "parent": "#", "text": "前端工程师"},
			// 二级节点
			{"id": "node_1", "parent": "root", "text": "技术"},
			{"id": "node_2", "parent": "root", "text": "IT公司"},
			{"id": "node_3", "parent": "root", "text": "技术"},
			// 三级节点
			// 技术
			{"id": "node_1_1", "parent": "node_1", "text": "HTML5"},
			{"id": "node_1_2", "parent": "node_1", "text": "JavaScript"},
			{"id": "node_1_3", "parent": "node_1", "text": "PHP"},
			{"id": "node_1_4", "parent": "node_1", "text": "Node.js"},
			// IT公司
			{"id": "node_2_1", "parent": "node_2", "text": "baidu"},
			{"id": "node_2_2", "parent": "node_2", "text": "meituan"},
			{"id": "node_2_3", "parent": "node_2", "text": "qunar"},
			// 生活
			{"id": "node_3_1", "parent": "node_3", "text": "美食"},
			{"id": "node_3_2", "parent": "node_3", "text": "旅游"},
			// 四级节点
			// Node.js
			{"id": "node_4_1", "parent": "node_1_4", "text": "grunt"},
			{"id": "node_4_2", "parent": "node_1_4", "text": "gulp"},
		]
	}
}

*/

function addHandler(element, type, handler) {
	if (element.addEventListener) {
		addHandler = function (element, type, handler) {
			element.addEventListener(type, handler, false);
		}
	} else if (element.attachEvent) {
		addHandler = function (element, type, handler) {
			element.attachEvent("on" +type, handler );
		}
	} else {
		addHandler = function (element, type, handler) {
			element["on" + type] = handler;
		}
	}

	return addHandler(element, type, handler);
}

function removeHandler(element, type, handler) {
	if (element.removeEventListener) {
		removeHandler = function (element, type, handler) {
			element.removeEventListener(type, handler, false);
		}
	} else if (element.detachEvent) {
		removeHandler = function (element, type, handler) {
			element.detachEvent("on" + type, handler);
		}
	} else {
		removeHandler = function (element, type, handler) {
			element["on" + type] = handler;
		}
	}

	return removeHandler(element, type, handler);
}

(function () {
	/**
	 * data structure
	 * 初始化节点结构
	 */
	var config = {
		'container': document.querySelector(".main"),
		'core': {
			'data': [
				// 根节点
				{"id": "root", "parent": "#", "text": "前端工程师"},
				// 二级节点
				{"id": "node_1", "parent": "root", "text": "技术"},
				{"id": "node_2", "parent": "root", "text": "IT公司"},
				{"id": "node_3", "parent": "root", "text": "生活"},
				// 三级节点
				// 技术
				{"id": "node_1_1", "parent": "node_1", "text": "HTML5"},
				{"id": "node_1_2", "parent": "node_1", "text": "JavaScript"},
				{"id": "node_1_3", "parent": "node_1", "text": "PHP"},
				{"id": "node_1_4", "parent": "node_1", "text": "Node.js"},
				// IT公司
				{"id": "node_2_1", "parent": "node_2", "text": "baidu"},
				{"id": "node_2_2", "parent": "node_2", "text": "meituan"},
				{"id": "node_2_3", "parent": "node_2", "text": "qunar"},
				// 生活
				{"id": "node_3_1", "parent": "node_3", "text": "美食"},
				{"id": "node_3_2", "parent": "node_3", "text": "旅游"},
				// 四级节点
				// Node.js
				{"id": "node_4_1", "parent": "node_1_4", "text": "grunt"},
				{"id": "node_4_2", "parent": "node_1_4", "text": "gulp"},
			]
		}
	}

	var treeNode = new TreeNode(config);

	treeNode.init();
})();<|endoftext|>


<commit_before>angular
  .module('app')
  .controller('ArtworkFormController', ArtworkFormController)

  function ArtworkFormController(artwork, $scope, movements, Artwork) {
    var vm = this;
    vm.data = null;
    vm.selection = [];
    vm.movements = movements.data.movements;
    vm.movementChecked =  movementChecked;
    vm.toggleSelection = toggleSelection;
    vm.submitArtwork = submitArtwork;

    defineArtwork()

    function defineArtwork() {
      if(Object.keys(artwork).length === 0) {
        vm.data = artwork;
        vm.data.movements = []
      } else {
        vm.data = artwork.data["artwork"];

        vm.data.movements.forEach(function(movement) {
          vm.selection.push(movement.id);
        });
      }
    }

    function movementChecked(id) {
      var value;

      vm.data.movements.forEach(function(movement) {
        if(id === movement.id) {value = movement.id}
      })
      return value
    }

    function toggleSelection(movementId) {
      var id = vm.selection.indexOf(movementId)
      if(id > -1){
        vm.selection.splice(id, 1)
      } else {
        vm.selection.push(movementId)
      }
    }

    function submitArtwork(artwork) {
      artwork.movements = vm.selection

      if(artwork.id === undefined) {
        Artwork.createArtwork(artwork)
      } else {
        Artwork.updateArtwork(artwork)
      }
    }
}
<commit_msg>remove defineArtwork function<commit_after>angular
  .module('app')
  .controller('ArtworkFormController', ArtworkFormController)

  function ArtworkFormController(artwork, $scope, movements, Artwork) {
    var vm = this;
    vm.selection = [];
    vm.movements = movements.data.movements;
    vm.movementChecked =  movementChecked;
    vm.toggleSelection = toggleSelection;
    vm.submitArtwork = submitArtwork;
    vm.data = artwork
    vm.data.movements = []

    function movementChecked(id) {
      var value;

      vm.data.movements.forEach(function(movement) {
        if(id === movement.id) {value = movement.id}
      })
      return value
    }

    function toggleSelection(movementId) {
      var id = vm.selection.indexOf(movementId)
      if(id > -1){
        vm.selection.splice(id, 1)
      } else {
        vm.selection.push(movementId)
      }
    }

    function submitArtwork(artwork) {
      artwork.movements = vm.selection

      if(artwork.id === undefined) {
        Artwork.createArtwork(artwork)
      } else {
        Artwork.updateArtwork(artwork)
      }
    }
}
<|endoftext|>


<commit_before>function candidateLineGraph(nationalData) {
  var parseDate = d3.time.format("%Y-%m-%d");
  nationalData.forEach(function(candidate) {
    candidate.minDate = d3.min(candidate.attributes.responses.map(function(d) { return parseDate.parse(d.date); }));
    candidate.maxDate = d3.max(candidate.attributes.responses.map(function(d) { return parseDate.parse(d.date); }));
    candidate.maxPercentage = d3.max(candidate.attributes.responses.map(function(d) { return d.percentage; }));
  });
  var graph = d3.select("#line-graph");
  var WIDTH = 1000;
  var HEIGHT = 500;
  var MARGINS = {
      top: 20,
      right: 20,
      bottom: 26,
      left: 50
    };
  var Xscale = d3.time.scale().range([MARGINS.left, WIDTH - MARGINS.right]);
  Xscale.domain([
      d3.min(nationalData.map(function(candidate) { return candidate.minDate; })),
      d3.max(nationalData.map(function(candidate) { return candidate.maxDate; }))
    ]);
  var Yscale = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([0,30]);

  var colorScale = d3.scale.category20();

  var Xaxis = d3.svg.axis()
      .scale(Xscale)
      .orient("bottom");

  var Yaxis = d3.svg.axis()
      .scale(Yscale)
      .orient("left");

  graph.append("svg:g")
    .attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
    .call(Xaxis);

  graph.append("svg:g")
    .attr("transform", "translate(" + (MARGINS.left) + ",0)")
    .call(Yaxis)

  var lineGen = d3.svg.line()
    .x(function(d) {
      return Xscale(parseDate.parse(d.date));
    })
    .y(function(d) {
      return Yscale(parseFloat(d.percentage));
    });

  nationalData.forEach(function(candidate, index) {
    graph.append("svg:path")
      .attr('d', lineGen(candidate.attributes.responses))
      .attr("stroke", colorScale(index))
      .attr("stroke-width", 3)
      .attr("fill", "none");
  });

  var yaxiscords = d3.range(26, HEIGHT, 45.4);
  var xaxiscords = d3.range(50, WIDTH, 25);

  graph.selectAll("line.vertical")
    .data(xaxiscords)
    .enter().append("svg:line")
    .attr("x1", function(d) {return d;})
    .attr("y1", 26)
    .attr("x2", function(d) {return d;})
    .attr("y2", HEIGHT - 25)
    .style("stroke", "rgb(192,192,192)")
    .style("opacity", 0.3)
    .style("stroke-width", 2);

  graph.selectAll("line.horizontal")
    .data(yaxiscords)
    .enter().append("svg:line")
    .attr("x1", 50)
    .attr("y1", function(d) {return d;})
    .attr("x2", WIDTH - 25)
    .attr("y2", function(d) {return d;})
    .style("stroke", "rgb(192,192,192)")
    .style("opacity", 0.3)
    .style("stroke-width", 2)
}

<commit_msg>Add animation functionality to GOP primary chart<commit_after>function candidateLineGraph(nationalData) {
  var parseDate = d3.time.format("%Y-%m-%d");
  nationalData.forEach(function(candidate) {
    candidate.minDate = d3.min(candidate.attributes.responses.map(function(d) { return parseDate.parse(d.date); }));
    candidate.maxDate = d3.max(candidate.attributes.responses.map(function(d) { return parseDate.parse(d.date); }));
    candidate.maxPercentage = d3.max(candidate.attributes.responses.map(function(d) { return d.percentage; }));
  });
  var graph = d3.select("#line-graph");
  var WIDTH = 1000;
  var HEIGHT = 500;
  var MARGINS = {
      top: 20,
      right: 20,
      bottom: 26,
      left: 50
    };
  var Xscale = d3.time.scale().range([MARGINS.left, WIDTH - MARGINS.right]);
  Xscale.domain([
      d3.min(nationalData.map(function(candidate) { return candidate.minDate; })),
      d3.max(nationalData.map(function(candidate) { return candidate.maxDate; }))
    ]);
  var Yscale = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([0,30]);

  var colorScale = d3.scale.category20();

  var Xaxis = d3.svg.axis()
      .scale(Xscale)
      .orient("bottom");

  var Yaxis = d3.svg.axis()
      .scale(Yscale)
      .orient("left");

  graph.append("svg:g")
    .attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
    .call(Xaxis);

  graph.append("svg:g")
    .attr("transform", "translate(" + (MARGINS.left) + ",0)")
    .call(Yaxis);

  var lineGen = d3.svg.line()
    .x(function(d) {
      return Xscale(parseDate.parse(d.date));
    })
    .y(function(d) {
      return Yscale(parseFloat(d.percentage));
    });

  nationalData.forEach(function(candidate, index) {
    var line = graph.append("svg:path")
      .attr("stroke", colorScale(index))
      .attr("stroke-width", 3)
      .attr("fill", "none");

    line.transition()
      .duration(4000)
      .delay(500 + index * 500)
      .ease("linear")
      .attr()
      .attr('d', lineGen(candidate.attributes.responses));
  });

  var yaxiscords = d3.range(26, HEIGHT, 45.4);
  var xaxiscords = d3.range(50, WIDTH, 25);

  graph.selectAll("line.vertical")
    .data(xaxiscords)
    .enter().append("svg:line")
    .attr("x1", function(d) {return d;})
    .attr("y1", 26)
    .attr("x2", function(d) {return d;})
    .attr("y2", HEIGHT - 25)
    .style("stroke", "rgb(192,192,192)")
    .style("opacity", 0.3)
    .style("stroke-width", 2);

  graph.selectAll("line.horizontal")
    .data(yaxiscords)
    .enter().append("svg:line")
    .attr("x1", 50)
    .attr("y1", function(d) {return d;})
    .attr("x2", WIDTH - 25)
    .attr("y2", function(d) {return d;})
    .style("stroke", "rgb(192,192,192)")
    .style("opacity", 0.3)
    .style("stroke-width", 2);
}

<|endoftext|>


<commit_before>import Presence from 'discourse/mixins/presence';
import searchForTerm from 'discourse/lib/search-for-term';

var _dontSearch = false;

export default Em.Controller.extend(Presence, {

  contextType: function(key, value){
    if(arguments.length > 1) {
      // a bit hacky, consider cleaning this up, need to work through all observers though
      var context = $.extend({}, this.get('searchContext'));
      context.type = value;
      this.set('searchContext', context);
    }
    return this.get('searchContext.type');
  }.property('searchContext'),

  contextChanged: function(){
    if (this.get('searchContextEnabled')) {
      _dontSearch = true;
      this.set('searchContextEnabled', false);
      _dontSearch = false;
    }
  }.observes('searchContext'),

  searchContextDescription: function(){
    var ctx = this.get('searchContext');
    if (ctx) {
      switch(Em.get(ctx, 'type')) {
        case 'topic':
          return I18n.t('search.context.topic');
        case 'user':
          return I18n.t('search.context.user', {username: Em.get(ctx, 'user.username')});
        case 'category':
          return I18n.t('search.context.category', {category: Em.get(ctx, 'category.name')});
        case 'private_messages':
          return I18n.t('search.context.private_messages');
      }
    }
  }.property('searchContext'),

  searchContextEnabledChanged: function(){
    if (_dontSearch) { return; }
    this.newSearchNeeded();
  }.observes('searchContextEnabled'),

  // If we need to perform another search
  newSearchNeeded: function() {
    this.set('noResults', false);
    var term = (this.get('term') || '').trim();
    if (term.length >= Discourse.SiteSettings.min_search_term_length) {
      this.set('loading', true);

      Ember.run.debounce(this, 'searchTerm', term, this.get('typeFilter'), 400);
    } else {
      this.setProperties({ content: null });
    }
    this.set('selectedIndex', 0);
  }.observes('term', 'typeFilter'),

  searchTerm: function(term, typeFilter) {
    var self = this;

    var context;
    if(this.get('searchContextEnabled')){
      context = this.get('searchContext');
    }

    searchForTerm(term, {
      typeFilter: typeFilter,
      searchContext: context
    }).then(function(results) {
      self.setProperties({ noResults: !results, content: results });
      self.set('loading', false);
    }).catch(function() {
      self.set('loading', false);
    });
  },

  showCancelFilter: function() {
    if (this.get('loading')) return false;
    return this.present('typeFilter');
  }.property('typeFilter', 'loading'),

  termChanged: function() {
    this.cancelTypeFilter();
  }.observes('term'),

  actions: {
    moreOfType: function(type) {
      if (type === 'topic') {
        var term = this.get('term');
        // TODO in topic and in category special handling
        Discourse.URL.routeTo("/search?q=" + encodeURIComponent(term));
      } else {
        this.set('typeFilter', type);
      }
    },

    cancelType: function() {
      this.cancelTypeFilter();
    }
  },

  cancelTypeFilter: function() {
    this.set('typeFilter', null);
  }
});
<commit_msg>more of type will not go to fullpage search if looking at a topic<commit_after>import Presence from 'discourse/mixins/presence';
import searchForTerm from 'discourse/lib/search-for-term';

var _dontSearch = false;

export default Em.Controller.extend(Presence, {

  contextType: function(key, value){
    if(arguments.length > 1) {
      // a bit hacky, consider cleaning this up, need to work through all observers though
      var context = $.extend({}, this.get('searchContext'));
      context.type = value;
      this.set('searchContext', context);
    }
    return this.get('searchContext.type');
  }.property('searchContext'),

  contextChanged: function(){
    if (this.get('searchContextEnabled')) {
      _dontSearch = true;
      this.set('searchContextEnabled', false);
      _dontSearch = false;
    }
  }.observes('searchContext'),

  searchContextDescription: function(){
    var ctx = this.get('searchContext');
    if (ctx) {
      switch(Em.get(ctx, 'type')) {
        case 'topic':
          return I18n.t('search.context.topic');
        case 'user':
          return I18n.t('search.context.user', {username: Em.get(ctx, 'user.username')});
        case 'category':
          return I18n.t('search.context.category', {category: Em.get(ctx, 'category.name')});
        case 'private_messages':
          return I18n.t('search.context.private_messages');
      }
    }
  }.property('searchContext'),

  searchContextEnabledChanged: function(){
    if (_dontSearch) { return; }
    this.newSearchNeeded();
  }.observes('searchContextEnabled'),

  // If we need to perform another search
  newSearchNeeded: function() {
    this.set('noResults', false);
    var term = (this.get('term') || '').trim();
    if (term.length >= Discourse.SiteSettings.min_search_term_length) {
      this.set('loading', true);

      Ember.run.debounce(this, 'searchTerm', term, this.get('typeFilter'), 400);
    } else {
      this.setProperties({ content: null });
    }
    this.set('selectedIndex', 0);
  }.observes('term', 'typeFilter'),

  searchTerm: function(term, typeFilter) {
    var self = this;

    var context;
    if(this.get('searchContextEnabled')){
      context = this.get('searchContext');
    }

    searchForTerm(term, {
      typeFilter: typeFilter,
      searchContext: context
    }).then(function(results) {
      self.setProperties({ noResults: !results, content: results });
      self.set('loading', false);
    }).catch(function() {
      self.set('loading', false);
    });
  },

  showCancelFilter: function() {
    if (this.get('loading')) return false;
    return this.present('typeFilter');
  }.property('typeFilter', 'loading'),

  termChanged: function() {
    this.cancelTypeFilter();
  }.observes('term'),

  actions: {
    moreOfType: function(type) {
      if (type === 'topic' && this.get('searchContext.type') !== 'topic') {
        var term = this.get('term');
        // TODO in topic and in category special handling
        Discourse.URL.routeTo("/search?q=" + encodeURIComponent(term));
      } else {
        this.set('typeFilter', type);
      }
    },

    cancelType: function() {
      this.cancelTypeFilter();
    }
  },

  cancelTypeFilter: function() {
    this.set('typeFilter', null);
  }
});
<|endoftext|>