<commit_before>/* global QuadTreeDemo, Random */
// ------------------------------------------------------------------
//
// This namespace holds the quad-tree demo model.
//
// ------------------------------------------------------------------
QuadTreeDemo.model = (function(components) {
	'use strict';

	var that = {},
		circles = [];

	// ------------------------------------------------------------------
	//
	// This function initializes the quad-tree demo model.
	//
	// ------------------------------------------------------------------
	that.initialize = function() {
		var circle = 0,
			addCircle = {},
			intersectsAny = false;
		//
		// Randomly generate a bunch of randomly sized circles.
		while (circles.length < components.Constants.NumberOfCircles) {
			addCircle = components.Circle( {
				center: { x: Random.nextDouble(), y: Random.nextDouble() },
				direction: Random.nextCircleVector(0.2),
				radius: Math.max(0.005, Math.abs(Random.nextGaussian(0.025, 0.015)))
			} );
			//
			// Don't allow the circle to start overlapped with the edges of the world
			addCircle.center.x = Math.max(addCircle.radius, addCircle.center.x);
			addCircle.center.x = Math.min(1.0 - addCircle.radius, addCircle.center.x);
			addCircle.center.y = Math.max(addCircle.radius, addCircle.center.y);
			addCircle.center.y = Math.min(1.0 - addCircle.radius, addCircle.center.y);
			//
			// Make sure this circle doesn't intersect/overlap with any of our existing
			// circles.
			intersectsAny = false;
			for (circle = 0; circle < circles.length; circle += 1) {
				if (circles[circle].intersects(addCircle)) {
					intersectsAny = true;
				}
			}
			if (intersectsAny === false) {
				circles.push(addCircle);

				console.log('x: ' + addCircle.center.x);
				console.log('y: ' + addCircle.center.y);
				console.log('direction: ' + addCircle.direction.x + ', ' + addCircle.direction.y);
				console.log('radius: ' + addCircle.radius);
			}
		}
	};

	// ------------------------------------------------------------------
	//
	// Perform an elastic collision between the two circles to determine
	// their new direction vectors.
	//
	// ------------------------------------------------------------------
	function bounce(c1, c2) {
		var v1 = { x: 0, y: 0 },
			v2 = { x: 0, y: 0 };

		v1.x = (c1.direction.x * (c1.radius - c2.radius) + 2 * c2.radius * c2.direction.x) / (c1.radius + c2.radius);
		v1.y = (c1.direction.y * (c1.radius - c2.radius) + 2 * c2.radius * c2.direction.y) / (c1.radius + c2.radius);

		v2.x = (c2.direction.x * (c2.radius - c1.radius) + 2 * c1.radius * c1.direction.x) / (c1.radius + c2.radius);
		v2.y = (c2.direction.y * (c2.radius - c1.radius) + 2 * c1.radius * c1.direction.y) / (c1.radius + c2.radius);

		c1.direction = v1;
		c2.direction = v2;
	}

	// ------------------------------------------------------------------
	//
	// This function is used to update the state of the demo model.
	//
	// ------------------------------------------------------------------
	that.update = function(elapsedTime) {
		var circle = 0,
			test = 0;
		//
		// Have all the circles update their positions
		for (circle = 0; circle < circles.length; circle += 1) {
			circles[circle].update(elapsedTime);
		}

		//
		// Check for collisions with other circles
		for (circle = 0; circle < circles.length; circle += 1) {
			for (test = circle; test < circles.length; test += 1) {
				//
				// Don't test against ourselves
				if (circle !== test) {
					if (circles[circle].intersects(circles[test])) {
						//
						// Bounce the circles, then do an update to move them away
						// from each other, so they don't get stuck overlapping.
						bounce(circles[circle], circles[test]);
						circles[circle].update(elapsedTime);
						circles[test].update(elapsedTime);
					}
				}
			}
		}
	};

	// ------------------------------------------------------------------
	//
	// This function renders the demo model.
	//
	// ------------------------------------------------------------------
	that.render = function(renderer) {
		var circle = 0;

		//
		// Draw a border around the unit world
		renderer.drawRectangle(0, 0, 1, 1);

		for (circle = 0; circle < circles.length; circle += 1) {
			renderer.drawCircle(circles[circle].center, circles[circle].radius);
		}
	};

	return that;

}(QuadTreeDemo.components));
<commit_msg>Updated the bounce function to move the circles until they no longer intersect.<commit_after>/* global QuadTreeDemo, Random */
// ------------------------------------------------------------------
//
// This namespace holds the quad-tree demo model.
//
// ------------------------------------------------------------------
QuadTreeDemo.model = (function(components) {
	'use strict';

	var that = {},
		circles = [];

	// ------------------------------------------------------------------
	//
	// This function initializes the quad-tree demo model.
	//
	// ------------------------------------------------------------------
	that.initialize = function() {
		var circle = 0,
			addCircle = {},
			intersectsAny = false;
		//
		// Randomly generate a bunch of randomly sized circles.
		while (circles.length < components.Constants.NumberOfCircles) {
			addCircle = components.Circle( {
				center: { x: Random.nextDouble(), y: Random.nextDouble() },
				direction: Random.nextCircleVector(0.2),
				radius: Math.max(0.005, Math.abs(Random.nextGaussian(0.025, 0.015)))
			} );
			//
			// Don't allow the circle to start overlapped with the edges of the world
			addCircle.center.x = Math.max(addCircle.radius, addCircle.center.x);
			addCircle.center.x = Math.min(1.0 - addCircle.radius, addCircle.center.x);
			addCircle.center.y = Math.max(addCircle.radius, addCircle.center.y);
			addCircle.center.y = Math.min(1.0 - addCircle.radius, addCircle.center.y);
			//
			// Make sure this circle doesn't intersect/overlap with any of our existing
			// circles.
			intersectsAny = false;
			for (circle = 0; circle < circles.length; circle += 1) {
				if (circles[circle].intersects(addCircle)) {
					intersectsAny = true;
				}
			}
			if (intersectsAny === false) {
				circles.push(addCircle);

				console.log('x: ' + addCircle.center.x);
				console.log('y: ' + addCircle.center.y);
				console.log('direction: ' + addCircle.direction.x + ', ' + addCircle.direction.y);
				console.log('radius: ' + addCircle.radius);
			}
		}
	};

	// ------------------------------------------------------------------
	//
	// Perform an elastic collision between the two circles to determine
	// their new direction vectors.
	//
	// ------------------------------------------------------------------
	function bounce(c1, c2, elapsedTime) {
		var v1 = { x: 0, y: 0 },
			v2 = { x: 0, y: 0 };

		v1.x = (c1.direction.x * (c1.radius - c2.radius) + 2 * c2.radius * c2.direction.x) / (c1.radius + c2.radius);
		v1.y = (c1.direction.y * (c1.radius - c2.radius) + 2 * c2.radius * c2.direction.y) / (c1.radius + c2.radius);

		v2.x = (c2.direction.x * (c2.radius - c1.radius) + 2 * c1.radius * c1.direction.x) / (c1.radius + c2.radius);
		v2.y = (c2.direction.y * (c2.radius - c1.radius) + 2 * c1.radius * c1.direction.y) / (c1.radius + c2.radius);

		c1.direction = v1;
		c2.direction = v2;

		//
		// Move them along their new direction vectors until they no longer intersect.
		while (c1.intersects(c2)) {
			c1.update(elapsedTime);
			c2.update(elapsedTime);
		}
	}

	// ------------------------------------------------------------------
	//
	// This function is used to update the state of the demo model.
	//
	// ------------------------------------------------------------------
	that.update = function(elapsedTime) {
		var circle = 0,
			test = 0;
		//
		// Have all the circles update their positions
		for (circle = 0; circle < circles.length; circle += 1) {
			circles[circle].update(elapsedTime);
		}

		//
		// Check for collisions with other circles
		for (circle = 0; circle < circles.length; circle += 1) {
			for (test = circle; test < circles.length; test += 1) {
				//
				// Don't test against ourselves
				if (circle !== test) {
					if (circles[circle].intersects(circles[test])) {
						//
						// Bounce the circles...this also moves them so they
						// no longer intersect.
						bounce(circles[circle], circles[test], elapsedTime);
					}
				}
			}
		}
	};

	// ------------------------------------------------------------------
	//
	// This function renders the demo model.
	//
	// ------------------------------------------------------------------
	that.render = function(renderer) {
		var circle = 0;

		//
		// Draw a border around the unit world
		renderer.drawRectangle(0, 0, 1, 1);

		for (circle = 0; circle < circles.length; circle += 1) {
			renderer.drawCircle(circles[circle].center, circles[circle].radius);
		}
	};

	return that;

}(QuadTreeDemo.components));
<|endoftext|>


<commit_before>app.controller('CourseEditController', function ($scope, $filter, $http, $location, Upload, toastr) {
    $scope.createdDate = new Date();
    $scope.courseEdit = null;
    $scope.tagsRaw = [];
    $scope.files = [];
    $scope.filespicture = false;
    $scope.filesvideo = false;

    $scope.isLoading = false;
    $scope.errors = [];

    $scope.progressPercentage = 0;

    $scope.$on('onAfterInitCourse', function (event, course) {
        $scope.init(course);
    });

    $scope.init = function (course) {
        if (!course)
            return;

        $scope.tagsRaw = [];

        $scope.courseEdit = cloneSimpleObject(course);

        if ($scope.courseEdit)
            if ($scope.courseEdit.courseTags && $scope.courseEdit.courseTags.length > 0) {
                for (var i in $scope.courseEdit.courseTags) {
                    var t = $scope.courseEdit.courseTags[i];
                    $scope.tagsRaw.push({"text": t.name});
                }
            }
    };

    $scope.saveCourse = function () {
        if ($scope.tagsRaw) {
            $scope.courseEdit.tags = JSON.stringify($scope.tagsRaw);
        }

        var uploadParams = {
            url: '/api/course/' + $scope.courseEdit._id,
            fields: {
                name: $scope.courseEdit.name,
                description: $scope.courseEdit.description,
                smallDescription: $scope.courseEdit.smallDescription,
                tags: $scope.courseEdit.tags
            }
        };

        uploadParams.file = [];
        // we only take one picture file
        if ($scope.filespicture) {
            uploadParams.file.push($scope.filespicture);
        }
        // we only take one vid file
        if ($scope.filesvideo) {
            uploadParams.file.push($scope.filesvideo);
        }

        $scope.isLoading = true;
        $scope.upload = Upload.upload(
            uploadParams
            )
            .progress(function (evt) {
                if (!evt.config.file)
                    return;

                $scope.progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
            })

            .success(function (data) {
                $scope.$emit('onAfterEditCourse', data.course);

                $scope.filespicture = false;
                $scope.filesvideo = false;

                $scope.isLoading = false;
                $('#editView').modal('hide');

                $scope.progressPercentage = 0;

                var slg = data.course.slug;
                //window.location.href = '/course/' + slg + '/#/cid/' + data.course._id + '?tab=preview';
                window.location.reload();
            })

            .error(function (data) {
                $scope.isLoading = false;
                $scope.errors = data.errors;

                $scope.progressPercentage = 0;
            });
    };

    $scope.deleteVideo = function () {
        $http.post('/api/course/' + $scope.courseEdit._id, {
                video: "delete",
                name: $scope.courseEdit.name
            })
            .success(function (data) {
                $scope.courseEdit.video = false;
                $scope.$emit('onAfterEditCourse', data.course);
                toastr.success('Video deleted');
            })
            .error(function () {
                toastr.error('Video delete failed');
            });
    };

    $scope.deletePicture = function () {
        $http.post('/api/course/' + $scope.courseEdit._id, {
                picture: "delete",
                name: $scope.courseEdit.name
            })
            .success(function (data) {
                $scope.courseEdit.video = false;
                $scope.$emit('onAfterEditCourse', data.course);
                toastr.success('Picture deleted');
            })
            .error(function () {
                toastr.error('Picture delete failed');
            });
    };

    $scope.cancel = function () {
        $scope.courseEdit = cloneSimpleObject($scope.$parent.course);

        if ($scope.upload) {
            $scope.upload.abort();
        }
    };
});
<commit_msg>reload properly after edit a course<commit_after>app.controller('CourseEditController', function ($scope, $filter, $http, $location, Upload, toastr) {
    $scope.createdDate = new Date();
    $scope.courseEdit = null;
    $scope.tagsRaw = [];
    $scope.files = [];
    $scope.filespicture = false;
    $scope.filesvideo = false;

    $scope.isLoading = false;
    $scope.errors = [];

    $scope.progressPercentage = 0;

    $scope.$on('onAfterInitCourse', function (event, course) {
        $scope.init(course);
    });

    $scope.init = function (course) {
        if (!course)
            return;

        $scope.tagsRaw = [];

        $scope.courseEdit = cloneSimpleObject(course);

        if ($scope.courseEdit)
            if ($scope.courseEdit.courseTags && $scope.courseEdit.courseTags.length > 0) {
                for (var i in $scope.courseEdit.courseTags) {
                    var t = $scope.courseEdit.courseTags[i];
                    $scope.tagsRaw.push({"text": t.name});
                }
            }
    };

    $scope.saveCourse = function () {
        if ($scope.tagsRaw) {
            $scope.courseEdit.tags = JSON.stringify($scope.tagsRaw);
        }

        var uploadParams = {
            url: '/api/course/' + $scope.courseEdit._id,
            fields: {
                name: $scope.courseEdit.name,
                description: $scope.courseEdit.description,
                smallDescription: $scope.courseEdit.smallDescription,
                tags: $scope.courseEdit.tags
            }
        };

        uploadParams.file = [];
        // we only take one picture file
        if ($scope.filespicture) {
            uploadParams.file.push($scope.filespicture);
        }
        // we only take one vid file
        if ($scope.filesvideo) {
            uploadParams.file.push($scope.filesvideo);
        }

        $scope.isLoading = true;
        $scope.upload = Upload.upload(
            uploadParams
            )
            .progress(function (evt) {
                if (!evt.config.file)
                    return;

                $scope.progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
            })

            .success(function (data) {
                $scope.$emit('onAfterEditCourse', data.course);

                $scope.filespicture = false;
                $scope.filesvideo = false;

                $scope.isLoading = false;
                $('#editView').modal('hide');

                $scope.progressPercentage = 0;

                var slg = data.course.slug;
                if (data.course.name != $scope.$parent.course.name)
                    window.location.href = '/course/' + slg + '/#/cid/' + data.course._id + '?tab=preview';
                else
                    window.location.reload();
            })

            .error(function (data) {
                $scope.isLoading = false;
                $scope.errors = data.errors;

                $scope.progressPercentage = 0;
            });
    };

    $scope.deleteVideo = function () {
        $http.post('/api/course/' + $scope.courseEdit._id, {
                video: "delete",
                name: $scope.courseEdit.name
            })
            .success(function (data) {
                $scope.courseEdit.video = false;
                $scope.$emit('onAfterEditCourse', data.course);
                toastr.success('Video deleted');
            })
            .error(function () {
                toastr.error('Video delete failed');
            });
    };

    $scope.deletePicture = function () {
        $http.post('/api/course/' + $scope.courseEdit._id, {
                picture: "delete",
                name: $scope.courseEdit.name
            })
            .success(function (data) {
                $scope.courseEdit.video = false;
                $scope.$emit('onAfterEditCourse', data.course);
                toastr.success('Picture deleted');
            })
            .error(function () {
                toastr.error('Picture delete failed');
            });
    };

    $scope.cancel = function () {
        $scope.courseEdit = cloneSimpleObject($scope.$parent.course);

        if ($scope.upload) {
            $scope.upload.abort();
        }
    };
});
<|endoftext|>


<commit_before>/* eslint-env jest */

import React from 'react'
import { mount, shallow } from 'enzyme'
import { QueryRenderer } from 'react-relay'
import WidgetsSettingsView from 'js/components/Settings/Widgets/WidgetsSettingsView'
import WidgetsSettings from 'js/components/Settings/Widgets/WidgetsSettingsContainer'
import ErrorMessage from 'js/components/General/ErrorMessage'
import logger from 'js/utils/logger'

jest.mock('react-relay')
jest.mock('js/components/General/ErrorMessage')
jest.mock('js/components/General/withUser')
jest.mock('js/utils/logger')
jest.mock('js/components/Settings/Widgets/WidgetsSettingsContainer')

afterEach(() => {
  jest.clearAllMocks()
})

const getMockProps = () => ({
  showError: jest.fn(),
})

describe('WidgetsSettingsView', () => {
  it('renders without error', () => {
    const mockProps = getMockProps()
    shallow(<WidgetsSettingsView {...mockProps} />).dive()
  })

  it('sets a root style of 100% width and height', () => {
    const mockProps = getMockProps()
    shallow(<WidgetsSettingsView {...mockProps} />).dive()
  })

  it('includes a QueryRenderer', () => {
    const mockProps = getMockProps()
    const wrapper = shallow(<WidgetsSettingsView {...mockProps} />).dive()
    expect(wrapper.find(QueryRenderer).exists()).toBe(true)
  })

  it('passes the expected variables to the QueryRenderer', () => {
    const mockProps = getMockProps()
    const wrapper = mount(<WidgetsSettingsView {...mockProps} />)
    expect(wrapper.find(QueryRenderer).prop('variables')).toEqual({
      userId: 'abc123xyz456', // default value in `withUser` mock
    })
  })

  it('does not render the child component before data has returned', () => {
    // No QueryRenderer response set.
    const mockProps = getMockProps()
    const wrapper = mount(<WidgetsSettingsView {...mockProps} />)
    expect(wrapper.find(WidgetsSettings).exists()).toBe(false)
  })

  it('does not render the child component when there is no data', () => {
    QueryRenderer.__setQueryResponse({
      error: null,
      props: null,
      retry: jest.fn(),
    })
    const mockProps = getMockProps()
    const wrapper = mount(<WidgetsSettingsView {...mockProps} />)
    expect(wrapper.find(WidgetsSettings).exists()).toBe(false)
  })

  it('passes the expected props to the child component', () => {
    const fakeQueryRendererProps = {
      app: {
        some: 'value',
      },
      user: {
        id: 'abc123xyz456',
        vc: 233,
      },
    }
    QueryRenderer.__setQueryResponse({
      error: null,
      props: fakeQueryRendererProps,
      retry: jest.fn(),
    })
    const mockProps = getMockProps()
    const wrapper = mount(<WidgetsSettingsView {...mockProps} />)
    expect(wrapper.find(WidgetsSettings).props()).toEqual({
      app: fakeQueryRendererProps.app,
      user: fakeQueryRendererProps.user,
      showError: mockProps.showError,
    })
  })

  it('logs an error and renders an ErrorMessage if unexpected QueryRenderer errors occur', () => {
    QueryRenderer.__setQueryResponse({
      error: {
        name: 'RelayNetwork',
        type: 'mustfix',
        framesToPop: 2,
        source: {
          errors: [
            {
              message: 'Something went horribly wrong.',
              locations: [
                {
                  line: 8,
                  column: 3,
                },
              ],
              path: ['user'],
              code: 'HORRIBLY_WRONG_ERROR',
            },
          ],
          operation: { foo: 'bar' },
          variables: { foo: 'baz' },
        },
      },
      props: null,
      retry: jest.fn(),
    })

    const mockProps = getMockProps()
    const wrapper = mount(<WidgetsSettingsView {...mockProps} />)

    // An error should render instead of the view.
    expect(wrapper.find(WidgetsSettings).length).toBe(0)
    expect(wrapper.find(ErrorMessage).exists()).toBe(true)
    expect(wrapper.find(ErrorMessage).prop('message')).toBe(
      'We had a problem loading the widget settings :('
    )
    expect(logger.error).toHaveBeenCalled()
  })
})
<commit_msg>Add a test for withUser<commit_after>/* eslint-env jest */

import React from 'react'
import { mount, shallow } from 'enzyme'
import { QueryRenderer } from 'react-relay'
import WidgetsSettingsView from 'js/components/Settings/Widgets/WidgetsSettingsView'
import WidgetsSettings from 'js/components/Settings/Widgets/WidgetsSettingsContainer'
import ErrorMessage from 'js/components/General/ErrorMessage'
import logger from 'js/utils/logger'

jest.mock('react-relay')
jest.mock('js/components/General/ErrorMessage')
jest.mock('js/components/General/withUser')
jest.mock('js/utils/logger')
jest.mock('js/components/Settings/Widgets/WidgetsSettingsContainer')

afterEach(() => {
  jest.clearAllMocks()
})

const getMockProps = () => ({
  showError: jest.fn(),
})

describe('withUser HOC in WidgetsSettingsView', () => {
  beforeEach(() => {
    jest.resetModules()
  })

  it('is called with the expected options', () => {
    const withUser = require('js/components/General/withUser').default

    /* eslint-disable-next-line no-unused-expressions */
    require('js/components/Settings/Widgets/WidgetsSettingsView').default
    expect(withUser).toHaveBeenCalledWith()
  })

  // TODO: test it actually wraps the WidgetsSettingsView component
})

describe('WidgetsSettingsView', () => {
  it('renders without error', () => {
    const mockProps = getMockProps()
    shallow(<WidgetsSettingsView {...mockProps} />).dive()
  })

  it('sets a root style of 100% width and height', () => {
    const mockProps = getMockProps()
    shallow(<WidgetsSettingsView {...mockProps} />).dive()
  })

  it('includes a QueryRenderer', () => {
    const mockProps = getMockProps()
    const wrapper = shallow(<WidgetsSettingsView {...mockProps} />).dive()
    expect(wrapper.find(QueryRenderer).exists()).toBe(true)
  })

  it('passes the expected variables to the QueryRenderer', () => {
    const mockProps = getMockProps()
    const wrapper = mount(<WidgetsSettingsView {...mockProps} />)
    expect(wrapper.find(QueryRenderer).prop('variables')).toEqual({
      userId: 'abc123xyz456', // default value in `withUser` mock
    })
  })

  it('does not render the child component before data has returned', () => {
    // No QueryRenderer response set.
    const mockProps = getMockProps()
    const wrapper = mount(<WidgetsSettingsView {...mockProps} />)
    expect(wrapper.find(WidgetsSettings).exists()).toBe(false)
  })

  it('does not render the child component when there is no data', () => {
    QueryRenderer.__setQueryResponse({
      error: null,
      props: null,
      retry: jest.fn(),
    })
    const mockProps = getMockProps()
    const wrapper = mount(<WidgetsSettingsView {...mockProps} />)
    expect(wrapper.find(WidgetsSettings).exists()).toBe(false)
  })

  it('passes the expected props to the child component', () => {
    const fakeQueryRendererProps = {
      app: {
        some: 'value',
      },
      user: {
        id: 'abc123xyz456',
        vc: 233,
      },
    }
    QueryRenderer.__setQueryResponse({
      error: null,
      props: fakeQueryRendererProps,
      retry: jest.fn(),
    })
    const mockProps = getMockProps()
    const wrapper = mount(<WidgetsSettingsView {...mockProps} />)
    expect(wrapper.find(WidgetsSettings).props()).toEqual({
      app: fakeQueryRendererProps.app,
      user: fakeQueryRendererProps.user,
      showError: mockProps.showError,
    })
  })

  it('logs an error and renders an ErrorMessage if unexpected QueryRenderer errors occur', () => {
    QueryRenderer.__setQueryResponse({
      error: {
        name: 'RelayNetwork',
        type: 'mustfix',
        framesToPop: 2,
        source: {
          errors: [
            {
              message: 'Something went horribly wrong.',
              locations: [
                {
                  line: 8,
                  column: 3,
                },
              ],
              path: ['user'],
              code: 'HORRIBLY_WRONG_ERROR',
            },
          ],
          operation: { foo: 'bar' },
          variables: { foo: 'baz' },
        },
      },
      props: null,
      retry: jest.fn(),
    })

    const mockProps = getMockProps()
    const wrapper = mount(<WidgetsSettingsView {...mockProps} />)

    // An error should render instead of the view.
    expect(wrapper.find(WidgetsSettings).length).toBe(0)
    expect(wrapper.find(ErrorMessage).exists()).toBe(true)
    expect(wrapper.find(ErrorMessage).prop('message')).toBe(
      'We had a problem loading the widget settings :('
    )
    expect(logger.error).toHaveBeenCalled()
  })
})
<|endoftext|>


<commit_before>import React from 'react';
import { reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Typography from 'material-ui/Typography';
import * as fields from '../../../forms/fields/projectFields/commonFields';
import GridColumn from '../../../common/grid/gridColumn';
import SectorForm from '../../../forms/fields/projectFields/sectorField/sectorFieldArray';
import LocationForm from '../../../forms/fields/projectFields/locationField/locationFieldArray';
import CnFileSection from '../../details/submission/cnFileSection';
import FileForm from '../../../forms/fileForm';
import Agencies from '../../../forms/fields/projectFields/agencies';
import ProfileConfirmation from '../../../organizationProfile/common/profileConfirmation';
import { selectCfeiDetails, mapAgenciesNamesToSelection } from '../../../../store';

const messages = {
  cn: 'Concept Note',
  projectDetails: 'Project Details',
  cnLabel: 'Please ensure that you have used the concept note template provided by the UN agency to whom you are submitting this unsolicited concept note.',
};

const EditUcnForm = (props) => {
  const { handleSubmit, form, handleConfirmation } = props;
  return (
    <form onSubmit={handleSubmit}>
      <GridColumn>
        <Typography type="headline">
          {messages.projectDetails}
        </Typography>
        <Agencies fieldName="agency" />
        <fields.TitleField />
        <LocationForm formName="editUcn" />
        <SectorForm />
        <Typography type="headline">
          {messages.cn}
        </Typography>
        <CnFileSection
          component={<FileForm
            fieldName="cn"
          />}
          label={messages.cnLabel}
          displayHint={false}
        />
        <ProfileConfirmation onChange={handleConfirmation} />
      </GridColumn>
    </form >
  );
};

EditUcnForm.propTypes = {
  /**
   * callback for form submit
   */
  handleSubmit: PropTypes.func.isRequired,
  form: PropTypes.string,
  handleConfirmation: PropTypes.func,

};

const mapStateToProps = (state, ownProps) => {
  const ucn = selectCfeiDetails(state, ownProps.id);
  const title = ucn.title;
  const agency = ucn.agency_id;
  const countries = ucn.locations_edit;
  const specializations = ucn.specializations;
  const cn = ucn.cn;
  return {
    agency,
    initialValues: {
      title,
      agency,
      countries,
      specializations,
      cn,
    },
  };
};

const formEditUcn = reduxForm({
  form: 'editUcn',
})(EditUcnForm);

export default connect(
  mapStateToProps,
)(formEditUcn);
<commit_msg>#1334 UCN edit - upload file<commit_after>import React from 'react';
import { reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Typography from 'material-ui/Typography';
import * as fields from '../../../forms/fields/projectFields/commonFields';
import GridColumn from '../../../common/grid/gridColumn';
import SectorForm from '../../../forms/fields/projectFields/sectorField/sectorFieldArray';
import LocationForm from '../../../forms/fields/projectFields/locationField/locationFieldArray';
import CnFileSection from '../../details/submission/cnFileSection';
import FileForm from '../../../forms/fileForm';
import Agencies from '../../../forms/fields/projectFields/agencies';
import ProfileConfirmation from '../../../organizationProfile/common/profileConfirmation';
import { selectCfeiDetails, mapAgenciesNamesToSelection } from '../../../../store';

const messages = {
  cn: 'Concept Note',
  projectDetails: 'Project Details',
  cnLabel: 'Please ensure that you have used the concept note template provided by the UN agency to whom you are submitting this unsolicited concept note.',
};

const EditUcnForm = (props) => {
  const { handleSubmit, form, handleConfirmation } = props;
  return (
    <form onSubmit={handleSubmit}>
      <GridColumn>
        <Typography type="headline">
          {messages.projectDetails}
        </Typography>
        <Agencies fieldName="agency" />
        <fields.TitleField />
        <LocationForm formName="editUcn" />
        <SectorForm />
        <Typography type="headline">
          {messages.cn}
        </Typography>
        <CnFileSection
          showComponent
          component={<FileForm
            fieldName="cn"
          />}
          label={messages.cnLabel}
          displayHint={false}
        />
        <ProfileConfirmation onChange={handleConfirmation} />
      </GridColumn>
    </form >
  );
};

EditUcnForm.propTypes = {
  /**
   * callback for form submit
   */
  handleSubmit: PropTypes.func.isRequired,
  form: PropTypes.string,
  handleConfirmation: PropTypes.func,

};

const mapStateToProps = (state, ownProps) => {
  const ucn = selectCfeiDetails(state, ownProps.id);
  const title = ucn.title;
  const agency = ucn.agency_id;
  const countries = ucn.locations_edit;
  const specializations = ucn.specializations;
  const cn = ucn.cn;
  return {
    agency,
    initialValues: {
      title,
      agency,
      countries,
      specializations,
      cn,
    },
  };
};

const formEditUcn = reduxForm({
  form: 'editUcn',
})(EditUcnForm);

export default connect(
  mapStateToProps,
)(formEditUcn);
<|endoftext|>


<commit_before>goog.provide('ol.Feature');
goog.provide('ol.feature');

goog.require('goog.asserts');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.functions');
goog.require('ol.Object');
goog.require('ol.geom.Geometry');
goog.require('ol.style.Style');

/**
 * @enum {string}
 */
ol.FeatureProperty = {
  STYLE_FUNCTION: 'styleFunction'
};

/**
 * @constructor
 * @extends {ol.Object}
 * @param {ol.geom.Geometry|Object.<string, *>=} opt_geometryOrValues
 *     Values or geometry.
 * @todo stability experimental
 */
ol.Feature = function(opt_geometryOrValues) {

  goog.base(this);

  /**
   * @private
   * @type {number|string|undefined}
   */
  this.id_ = undefined;

  /**
   * @type {string}
   * @private
   */
  this.geometryName_ = 'geometry';

  /**
   * @private
   * @type {goog.events.Key}
   */
  this.geometryChangeKey_ = null;

  goog.events.listen(
      this, ol.Object.getChangeEventType(this.geometryName_),
      this.handleGeometryChanged_, false, this);
  goog.events.listen(
      this, ol.Object.getChangeEventType(ol.FeatureProperty.STYLE_FUNCTION),
      this.handleStyleFunctionChange_, false, this);

  if (goog.isDefAndNotNull(opt_geometryOrValues)) {
    if (opt_geometryOrValues instanceof ol.geom.Geometry) {
      var geometry = /** @type {ol.geom.Geometry} */ (opt_geometryOrValues);
      this.setGeometry(geometry);
    } else {
      goog.asserts.assert(goog.isObject(opt_geometryOrValues));
      var values = /** @type {Object.<string, *>} */ (opt_geometryOrValues);
      this.setValues(values);
    }
  } else {
    this.setGeometry(null);
  }
};
goog.inherits(ol.Feature, ol.Object);

/**
 * @return {ol.geom.Geometry|undefined} Geometry.
 * @todo stability experimental
 */
ol.Feature.prototype.getGeometry = function() {
  return /** @type {ol.geom.Geometry|undefined} */ (
      this.get(this.geometryName_));
};
goog.exportProperty(
    ol.Feature.prototype,
    'getGeometry',
    ol.Feature.prototype.getGeometry);

/**
 * @return {number|string|undefined} Id.
 * @todo stability experimental
 */
ol.Feature.prototype.getId = function() {
  return this.id_;
};

/**
 * @return {string} Geometry property name.
 * @todo stability experimental
 */
ol.Feature.prototype.getGeometryName = function() {
  return this.geometryName_;
};

/**
 * @return {ol.feature.FeatureStyleFunction|undefined} Style function.
 * @todo stability experimental
 */
ol.Feature.prototype.getStyleFunction = function() {
  return /** @type {ol.feature.FeatureStyleFunction|undefined} */ (
      this.get(ol.FeatureProperty.STYLE_FUNCTION));
};
goog.exportProperty(
    ol.Feature.prototype,
    'getStyleFunction',
    ol.Feature.prototype.getStyleFunction);

/**
 * @private
 */
ol.Feature.prototype.handleGeometryChange_ = function() {
  this.dispatchChangeEvent();
};

/**
 * @private
 */
ol.Feature.prototype.handleGeometryChanged_ = function() {
  if (!goog.isNull(this.geometryChangeKey_)) {
    goog.events.unlistenByKey(this.geometryChangeKey_);
    this.geometryChangeKey_ = null;
  }
  var geometry = this.getGeometry();
  if (goog.isDefAndNotNull(geometry)) {
    this.geometryChangeKey_ = goog.events.listen(geometry,
        goog.events.EventType.CHANGE, this.handleGeometryChange_, false, this);
  }
  this.dispatchChangeEvent();
};

/**
 * @private
 */
ol.Feature.prototype.handleStyleFunctionChange_ = function() {
  this.dispatchChangeEvent();
};

/**
 * @param {ol.geom.Geometry|undefined} geometry Geometry.
 * @todo stability experimental
 */
ol.Feature.prototype.setGeometry = function(geometry) {
  this.set(this.geometryName_, geometry);
};
goog.exportProperty(
    ol.Feature.prototype,
    'setGeometry',
    ol.Feature.prototype.setGeometry);

/**
 * @param {ol.feature.FeatureStyleFunction|undefined} styleFunction Style
 *     function
 * @todo stability experimental
 */
ol.Feature.prototype.setStyleFunction = function(styleFunction) {
  this.set(ol.FeatureProperty.STYLE_FUNCTION, styleFunction);
};
goog.exportProperty(
    ol.Feature.prototype,
    'setStyleFunction',
    ol.Feature.prototype.setStyleFunction);

/**
 * @param {number|string|undefined} id Id.
 * @todo stability experimental
 */
ol.Feature.prototype.setId = function(id) {
  this.id_ = id;
};

/**
 * @param {string} name Geometry property name.
 * @todo stability experimental
 */
ol.Feature.prototype.setGeometryName = function(name) {
  goog.events.unlisten(
      this, ol.Object.getChangeEventType(this.geometryName_),
      this.handleGeometryChanged_, false, this);
  this.geometryName_ = name;
  goog.events.listen(
      this, ol.Object.getChangeEventType(this.geometryName_),
      this.handleGeometryChanged_, false, this);
  this.handleGeometryChanged_();
};

/**
 * @typedef {function(this: ol.Feature, number): Array.<ol.style.Style>}
 * @todo stability experimental
 */
ol.feature.FeatureStyleFunction;

/**
 * @param {number} resolution Resolution.
 * @return {Array.<ol.style.Style>} Style.
 * @this {ol.Feature}
 * @todo stability experimental
 */
ol.feature.defaultFeatureStyleFunction = goog.functions.constant([]);

/**
 * @typedef {function(ol.Feature, number): Array.<ol.style.Style>}
 * @todo stability experimental
 */
ol.feature.StyleFunction;

/**
 * @param {ol.Feature} feature Feature.
 * @param {number} resolution Resolution.
 * @return {Array.<ol.style.Style>} Style.
 * @todo stability experimental
 */
ol.feature.defaultStyleFunction = function(feature, resolution) {
  var featureStyleFunction = feature.getStyleFunction();
  if (!goog.isDef(featureStyleFunction)) {
    featureStyleFunction = ol.feature.defaultFeatureStyleFunction;
  }
  return featureStyleFunction.call(feature, resolution);
};

/**
 * Convert the provided object into a style function.  Functions passed through
 * unchanged.  Arrays of ol.style.Style or single style objects wrapped in a
 * new style function.
 * @param {ol.feature.StyleFunction|Array.<ol.style.Style>|ol.style.Style} obj
 *     A style function, a single style, or an array of styles.
 * @return {ol.feature.StyleFunction} A style function.
 */
ol.feature.createStyleFunction = function(obj) {
  /**
   * @type {ol.feature.StyleFunction}
   */
  var styleFunction;

  if (goog.isFunction(obj)) {
    styleFunction = /** @type {ol.feature.StyleFunction} */ (obj);
  } else {
    /**
     * @type {Array.<ol.style.Style>}
     */
    var styles;
    if (goog.isArray(obj)) {
      styles = obj;
    } else {
      goog.asserts.assertInstanceof(obj, ol.style.Style);
      styles = [obj];
    }
    styleFunction = function(feature, resolution) {
      return styles;
    };
  }
  return styleFunction;
};
<commit_msg>Avoid clashing with user property names<commit_after>goog.provide('ol.Feature');
goog.provide('ol.feature');

goog.require('goog.asserts');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.functions');
goog.require('ol.Object');
goog.require('ol.geom.Geometry');
goog.require('ol.style.Style');

/**
 * @constructor
 * @extends {ol.Object}
 * @param {ol.geom.Geometry|Object.<string, *>=} opt_geometryOrValues
 *     Values or geometry.
 * @todo stability experimental
 */
ol.Feature = function(opt_geometryOrValues) {

  goog.base(this);

  /**
   * @private
   * @type {number|string|undefined}
   */
  this.id_ = undefined;

  /**
   * @type {string}
   * @private
   */
  this.geometryName_ = 'geometry';

  /**
   * @private
   * @type {ol.feature.FeatureStyleFunction|undefined}
   */
  this.styleFunction_;

  /**
   * @private
   * @type {goog.events.Key}
   */
  this.geometryChangeKey_ = null;

  goog.events.listen(
      this, ol.Object.getChangeEventType(this.geometryName_),
      this.handleGeometryChanged_, false, this);

  if (goog.isDefAndNotNull(opt_geometryOrValues)) {
    if (opt_geometryOrValues instanceof ol.geom.Geometry) {
      var geometry = /** @type {ol.geom.Geometry} */ (opt_geometryOrValues);
      this.setGeometry(geometry);
    } else {
      goog.asserts.assert(goog.isObject(opt_geometryOrValues));
      var values = /** @type {Object.<string, *>} */ (opt_geometryOrValues);
      this.setValues(values);
    }
  } else {
    this.setGeometry(null);
  }
};
goog.inherits(ol.Feature, ol.Object);

/**
 * @return {ol.geom.Geometry|undefined} Geometry.
 * @todo stability experimental
 */
ol.Feature.prototype.getGeometry = function() {
  return /** @type {ol.geom.Geometry|undefined} */ (
      this.get(this.geometryName_));
};
goog.exportProperty(
    ol.Feature.prototype,
    'getGeometry',
    ol.Feature.prototype.getGeometry);

/**
 * @return {number|string|undefined} Id.
 * @todo stability experimental
 */
ol.Feature.prototype.getId = function() {
  return this.id_;
};

/**
 * @return {string} Geometry property name.
 * @todo stability experimental
 */
ol.Feature.prototype.getGeometryName = function() {
  return this.geometryName_;
};

/**
 * @return {ol.feature.FeatureStyleFunction|undefined} Style function.
 * @todo stability experimental
 */
ol.Feature.prototype.getStyleFunction = function() {
  return this.styleFunction_;
};

/**
 * @private
 */
ol.Feature.prototype.handleGeometryChange_ = function() {
  this.dispatchChangeEvent();
};

/**
 * @private
 */
ol.Feature.prototype.handleGeometryChanged_ = function() {
  if (!goog.isNull(this.geometryChangeKey_)) {
    goog.events.unlistenByKey(this.geometryChangeKey_);
    this.geometryChangeKey_ = null;
  }
  var geometry = this.getGeometry();
  if (goog.isDefAndNotNull(geometry)) {
    this.geometryChangeKey_ = goog.events.listen(geometry,
        goog.events.EventType.CHANGE, this.handleGeometryChange_, false, this);
  }
  this.dispatchChangeEvent();
};

/**
 * @param {ol.geom.Geometry|undefined} geometry Geometry.
 * @todo stability experimental
 */
ol.Feature.prototype.setGeometry = function(geometry) {
  this.set(this.geometryName_, geometry);
};
goog.exportProperty(
    ol.Feature.prototype,
    'setGeometry',
    ol.Feature.prototype.setGeometry);

/**
 * @param {ol.feature.FeatureStyleFunction|undefined} styleFunction Style
 *     function.
 * @todo stability experimental
 */
ol.Feature.prototype.setStyleFunction = function(styleFunction) {
  this.styleFunction_ = styleFunction;
  this.dispatchChangeEvent();
};

/**
 * @param {number|string|undefined} id Id.
 * @todo stability experimental
 */
ol.Feature.prototype.setId = function(id) {
  this.id_ = id;
};

/**
 * @param {string} name Geometry property name.
 * @todo stability experimental
 */
ol.Feature.prototype.setGeometryName = function(name) {
  goog.events.unlisten(
      this, ol.Object.getChangeEventType(this.geometryName_),
      this.handleGeometryChanged_, false, this);
  this.geometryName_ = name;
  goog.events.listen(
      this, ol.Object.getChangeEventType(this.geometryName_),
      this.handleGeometryChanged_, false, this);
  this.handleGeometryChanged_();
};

/**
 * @typedef {function(this: ol.Feature, number): Array.<ol.style.Style>}
 * @todo stability experimental
 */
ol.feature.FeatureStyleFunction;

/**
 * @param {number} resolution Resolution.
 * @return {Array.<ol.style.Style>} Style.
 * @this {ol.Feature}
 * @todo stability experimental
 */
ol.feature.defaultFeatureStyleFunction = goog.functions.constant([]);

/**
 * @typedef {function(ol.Feature, number): Array.<ol.style.Style>}
 * @todo stability experimental
 */
ol.feature.StyleFunction;

/**
 * @param {ol.Feature} feature Feature.
 * @param {number} resolution Resolution.
 * @return {Array.<ol.style.Style>} Style.
 * @todo stability experimental
 */
ol.feature.defaultStyleFunction = function(feature, resolution) {
  var featureStyleFunction = feature.getStyleFunction();
  if (!goog.isDef(featureStyleFunction)) {
    featureStyleFunction = ol.feature.defaultFeatureStyleFunction;
  }
  return featureStyleFunction.call(feature, resolution);
};

/**
 * Convert the provided object into a style function.  Functions passed through
 * unchanged.  Arrays of ol.style.Style or single style objects wrapped in a
 * new style function.
 * @param {ol.feature.StyleFunction|Array.<ol.style.Style>|ol.style.Style} obj
 *     A style function, a single style, or an array of styles.
 * @return {ol.feature.StyleFunction} A style function.
 */
ol.feature.createStyleFunction = function(obj) {
  /**
   * @type {ol.feature.StyleFunction}
   */
  var styleFunction;

  if (goog.isFunction(obj)) {
    styleFunction = /** @type {ol.feature.StyleFunction} */ (obj);
  } else {
    /**
     * @type {Array.<ol.style.Style>}
     */
    var styles;
    if (goog.isArray(obj)) {
      styles = obj;
    } else {
      goog.asserts.assertInstanceof(obj, ol.style.Style);
      styles = [obj];
    }
    styleFunction = function(feature, resolution) {
      return styles;
    };
  }
  return styleFunction;
};
<|endoftext|>


<commit_before>;

import angular from 'angular';
import squareImageModule from '../components/square-image';
import won from '../won-es6';
import { attach } from '../utils';
import { actionCreators }  from '../actions/actions';
import { labels, relativeTime, } from '../won-label-utils';
import {
    selectAllOwnNeeds,
} from '../selectors';

const serviceDependencies = ['$scope', '$interval', '$ngRedux'];
function genComponentConf() {
    let template = `

                    <won-square-image
                        ng-class="{'inactive' : !self.isActive()}"
                        src="self.ownNeed.get('titleImgSrc')"
                        title="self.ownNeed.get('title')"
                        uri="self.needUri">
                    </won-square-image>

{{self.need.get('title')}}

{{self.relativeCreationDate}}

                             {{self.ownNeed.get('group')}}
                              –

                             {{self.labels.type[self.get('type')]}}

                            {{ self.unreadConversationsCount }}

                            {{ self.unreadRequestsCount }}

                            {{ self.unreadMatchesCount }}

             [DATA]
    `;

    class Controller {
        constructor() {
            attach(this, serviceDependencies, arguments);

            window.pil4dbg = this; //TODO deletme
            this.labels = labels;
            const self = this;

            const selectFromState = (state) => {
                const ownNeeds = selectAllOwnNeeds(state);
                const need = ownNeeds && ownNeeds.get(self.needUri);
                const allConnectionsByNeedUri = need.get("connections");

                const conversations = allConnectionsByNeedUri.filter(conn =>conn.get("state") === won.WON.Connected);
                const requests = allConnectionsByNeedUri.filter(conn => conn.get("state") === won.WON.RequestReceived);
                const matches = allConnectionsByNeedUri.filter(conn => conn.get("state") === won.WON.Suggested);

                const unreadConversationsCount = conversations && conversations.filter(conn => conn.get("newConnection")).size;
                const unreadRequestsCount = requests && requests.filter(conn => conn.get("newConnection")).size;
                const unreadMatchesCount = matches && matches.filter(conn => conn.get("newConnection")).size;

                return {
                    need,
                    ownNeed: need,
                    relativeCreationDate: need ?
                        relativeTime(state.get('lastUpdateTime'), need.get('creationDate')) :
                        "",
                    hasConversations: conversations && conversations.size > 0,
                    hasRequests: requests && requests.size > 0,
                    hasMatches: matches && matches.size > 0,
                    unreadConversationsCount: unreadConversationsCount > 0 ? unreadConversationsCount : undefined,
                    unreadRequestsCount: unreadRequestsCount > 0 ? unreadRequestsCount : undefined,
                    unreadMatchesCount: unreadMatchesCount > 0 ? unreadMatchesCount : undefined,
                    WON: won.WON,
                    debugmode: won.debugmode,
                };
            };

            const disconnect = this.$ngRedux.connect(selectFromState, actionCreators)(this);
            this.$scope.$on('$destroy', disconnect);
        }

        isActive() {
            return this.ownNeed && this.ownNeed.get("state") === won.WON.ActiveCompacted;
        }
    }
    Controller.$inject = serviceDependencies;

    return {
        restrict: 'E',
        controller: Controller,
        controllerAs: 'self',
        bindToController: true, //scope-bindings -> ctrl
        scope: {
            needUri: "=",
        },
        template: template
    }
}

export default angular.module('won.owner.components.postItemLine', [
    squareImageModule
])
    .directive('wonPostItemLine', genComponentConf)
    .name;

<commit_msg>added safeguards for post-item-line undefined<commit_after>;

import angular from 'angular';
import squareImageModule from '../components/square-image';
import won from '../won-es6';
import { attach } from '../utils';
import { actionCreators }  from '../actions/actions';
import { labels, relativeTime, } from '../won-label-utils';
import {
    selectAllOwnNeeds,
} from '../selectors';

const serviceDependencies = ['$scope', '$interval', '$ngRedux'];
function genComponentConf() {
    let template = `

                    <won-square-image
                        ng-class="{'inactive' : !self.isActive()}"
                        src="self.ownNeed.get('titleImgSrc')"
                        title="self.ownNeed.get('title')"
                        uri="self.needUri">
                    </won-square-image>

{{self.need.get('title')}}

{{self.relativeCreationDate}}

                             {{self.ownNeed.get('group')}}
                              –

                             {{self.labels.type[self.get('type')]}}

                            {{ self.unreadConversationsCount }}

                            {{ self.unreadRequestsCount }}

                            {{ self.unreadMatchesCount }}

             [DATA]
    `;

    class Controller {
        constructor() {
            attach(this, serviceDependencies, arguments);

            window.pil4dbg = this; //TODO deletme
            this.labels = labels;
            const self = this;

            const selectFromState = (state) => {
                const ownNeeds = selectAllOwnNeeds(state);
                const need = ownNeeds && ownNeeds.get(self.needUri);
                const allConnectionsByNeedUri = need && need.get("connections");

                const conversations = allConnectionsByNeedUri && allConnectionsByNeedUri.filter(conn =>conn.get("state") === won.WON.Connected);
                const requests = allConnectionsByNeedUri && allConnectionsByNeedUri.filter(conn => conn.get("state") === won.WON.RequestReceived);
                const matches = allConnectionsByNeedUri && allConnectionsByNeedUri.filter(conn => conn.get("state") === won.WON.Suggested);

                const unreadConversationsCount = conversations && conversations.filter(conn => conn.get("newConnection")).size;
                const unreadRequestsCount = requests && requests.filter(conn => conn.get("newConnection")).size;
                const unreadMatchesCount = matches && matches.filter(conn => conn.get("newConnection")).size;

                return {
                    need,
                    ownNeed: need,
                    relativeCreationDate: need ?
                        relativeTime(state.get('lastUpdateTime'), need.get('creationDate')) :
                        "",
                    hasConversations: conversations && conversations.size > 0,
                    hasRequests: requests && requests.size > 0,
                    hasMatches: matches && matches.size > 0,
                    unreadConversationsCount: unreadConversationsCount > 0 ? unreadConversationsCount : undefined,
                    unreadRequestsCount: unreadRequestsCount > 0 ? unreadRequestsCount : undefined,
                    unreadMatchesCount: unreadMatchesCount > 0 ? unreadMatchesCount : undefined,
                    WON: won.WON,
                    debugmode: won.debugmode,
                };
            };

            const disconnect = this.$ngRedux.connect(selectFromState, actionCreators)(this);
            this.$scope.$on('$destroy', disconnect);
        }

        isActive() {
            return this.ownNeed && this.ownNeed.get("state") === won.WON.ActiveCompacted;
        }
    }
    Controller.$inject = serviceDependencies;

    return {
        restrict: 'E',
        controller: Controller,
        controllerAs: 'self',
        bindToController: true, //scope-bindings -> ctrl
        scope: {
            needUri: "=",
        },
        template: template
    }
}

export default angular.module('won.owner.components.postItemLine', [
    squareImageModule
])
    .directive('wonPostItemLine', genComponentConf)
    .name;

<|endoftext|>


<commit_before>/* eslint-disable no-param-reassign, func-names, no-console */
import omit from 'lodash.omit';
import clone from 'lodash.clone';

export class DollarApollo {
    constructor(el) {
        this.el = el;
        this.subscriptions = {};
        this.queries = {};
        this._query = {};
        this._subscription = {};
        this.attached = false;
    }

    get client() {
        return this.el._apolloClient;
    }

    get query() {
        return this.client.query.bind(this.client);
    }
    get mutate() {
        return this.client.mutate.bind(this.client);
    }

    watchQuery(options, key) {
        const observable = this.client.watchQuery(options);
        return this._processObservable(observable, key, 'query');
    }

    subscribe(options, key) {
        const observable = this.client.subscribe(options);
        return this._processObservable(observable, key, 'subscription');
    }
    _processObservable(observable, key, type) {
        const self = this;
        const _subscribe = observable.subscribe.bind(observable);
        observable.subscribe = (function (opt) {
            const sub = _subscribe(opt);

            const _unsubscribe = sub.unsubscribe.bind(sub);
            sub.unsubscribe = function () {
                _unsubscribe();
                self[`_${type}`][key].sub = null;
            };
            self[`_${type}`][key].sub = sub;
            return sub;
        });
        return observable;
    }
    _getSubscribeCallbacks(key, type) {
        const el = this.el;
        const $apollo = this;
        const entry = this[`_${type}`][key];
        const loadingKey = entry.loadingKey;
        const loadingChangeCb = entry.watchLoading;
        this._changeLoader(loadingKey, true, loadingChangeCb);

        function nextResult(result) {
            $apollo._changeLoader(loadingKey, false, loadingChangeCb);
            $apollo._applyData(result.data);
            if (typeof entry.success === 'function') {
                entry.success.call(el, result);
            }
        }

        function catchError(error) {
            $apollo._changeLoader(loadingKey, false, loadingChangeCb);
            if (error.graphQLErrors && error.graphQLErrors.length !== 0) {
                console.error(`GraphQL execution errors for ${type} ${key}`);
                for (const e of error.graphQLErrors) {
                    console.error(e);
                }
            } else if (error.networkError) {
                console.error(`Error sending the ${type} ${key}`, error.networkError);
            } else {
                console.error(error);
            }
            if (typeof entry.error === 'function') {
                entry.error.call(el, error);
            }
        }
        return { next: nextResult, error: catchError };
    }
    _subscribeObservable(key, observable, type) {
        const opt = this._getSubscribeCallbacks(key, type);
        const sub = observable.subscribe(opt);
        return sub;
    }

    _applyData(data) {
        if (data) {
            for (const key of Object.keys(data)) {
                this.el.set([key], data[key]);
            }
        }
    }

    _changeLoader(loadingKey, value, loadingChangeCb) {
        if (loadingKey) {
            this.el[loadingKey] = value;
        }

        if (loadingChangeCb) {
            loadingChangeCb(value);
        }
    }

    _refetch(key, entry) {
        const options = entry._options;
        const observable = entry.observable;
        const variables = options.variables;
        const opt = this._getSubscribeCallbacks(key, 'query');
        if (observable) {
            observable.refetch(variables, {
                forceFetch: !!options.forceFetch,
            }).then(opt.next, opt.error);
        }
    }

    refetch(key) {
        const entry = this._query[key];
        if (entry) {
            this._refetch(key, entry);
        } else {
            console.error(`Unable to find a query with key : ${key}`);
        }
    }

    _generateApolloOptions(options) {
        const apolloOptions = omit(options, [
            'error',
            'loadingKey',
            'watchLoading',
            'skip',
            '_options',
            'options',
            'result',
        ]);
        return apolloOptions;
    }
    createApolloOptions(apollo) {
        if (apollo) {
            const queries = omit(apollo, [
                'subscribe',
                'onReady',
            ]);
            this._query = queries || {};
            this._subscription = apollo.subscribe || {};
            for (const key of Object.keys(this._query)) {
                this._createOptionsProp(key, 'query');
            }
            for (const key of Object.keys(this._subscription)) {
                this._createOptionsProp(key, 'subscription');
            }
        }
    }
    _createOptionsProp(key, type) {
        const options = this[`_${type}`][key].options;
        const rnd = Math.floor(1000000000 + (Math.random() * 9000000000));
        var rId = `__apollo_${rnd}`;
        this[`_${type}`][key]._key = rnd;
    }
    init(el) {
        this.el = el;
        for (const key of Object.keys(this._query)) {
            this._processOptions(key, 'query');
        }
        for (const key of Object.keys(this._subscription)) {
            this._processOptions(key, 'subscription');
        }
    }
    start(el) {
        for (const key of Object.keys(this._query)) {
            const entry = this._query[key];
            const options = entry._options || el[entry.options];
            this._polymerChange('query', key, options);
        }
        for (const key of Object.keys(this._subscription)) {
            const entry = this._subscription[key];
            const options = entry._options || el[entry.options];
            this._polymerChange('subscription', key, options);
        }
    }
    _processOptions(key, type) {
        const entry = this[`_${type}`][key];
        const rId = `__apollo_${entry._key}`;
        if (!this.el[`${rId}_callback`]) {
            if (typeof entry.options === 'string') {
                this._createPolymerObserver(rId, key, type);
            } else {
                entry._options = entry.options || { skip: false };
            }
            this[`_${type}`][key] = entry;
        }
    }
    _createPolymerObserver(rId, key, type) {
        const $apollo = this;
        // unique id for observer callback
        const cbId = `${rId}_callback`;
        this.el[cbId] = (n) => {
            $apollo._polymerChange(type, key, n);
        };
        this.el._createPropertyObserver(this[`_${type}`][key].options, cbId);
    }
    _polymerChange(type, key, options = {}) {
        if (this.attached) {
            const entry = this[`_${type}`][key];
            entry._options = options;
            const _observable = entry.observable;
            const skip = !!options.skip;
            const _sub = entry.sub;
            if (skip) {
                if (_sub) {
                    _sub.unsubscribe();
                    delete entry.sub;
                }
            } else if (_sub) {
                _observable.setOptions(options);
            } else {
                const processArg = Object.assign({}, entry, options);

                const { sub, observable } = this[`${type}Process`](key, processArg);
                entry.sub = sub;
                entry.observable = observable;
            }
            this[`_${type}`][key] = entry;
        }
    }
    queryProcess(key, options) {
        if (key && options) {
            // Create observer
            const observable = this.watchQuery(this._generateApolloOptions(options), key);
            this.queries[key] = observable;
            options.observable = observable;
            // subscribe observable
            const sub = this._subscribeObservable(key, observable, 'query');
            return { sub, observable };
        }
        return null;
    }
    subscriptionProcess(key, options) {
        if (key && options) {
            // Create observable
            const observable = this.subscribe(this._generateApolloOptions(options), key);
            this.subscriptions[key] = observable;
            options.observable = observable;
            this._subscription[key] = options;
            // subscribe observable
            const sub = this._subscribeObservable(key, observable, 'subscription');
            return { sub, observable };
        }
        return null;
    }
    unsubscribe(key, type) {
        const entry = this[`_${type}`][key];
        const sub = entry.sub;
        sub.unsubscribe();
        this[`${type}`][key] = omit(entry, 'sub');
    }
}
export const PolymerApolloMixin = (superclass, options) => class extends superclass {
    constructor() {
        super();
        this._apolloClient = options.apolloClient;
        this.$apollo = new DollarApollo(this);
        const apollo = this.apollo;
        if (apollo) {
            this.$apollo.createApolloOptions(apollo);
        }
    }
    connectedCallback() {
        super.connectedCallback();
        const apollo = this.apollo;
        this.$apollo = clone(this.$apollo);
        if (apollo) {
            this.$apollo.attached = true;
            this.$apollo.init(this);
        }
    }
    ready() {
        super.ready();
        const apollo = this.apollo;
        if (apollo) {
            this.$apollo.attached = true;
            this.$apollo.start(this);
        }
    }
    disconnectedCallback() {
        const apollo = this.apollo;
        if (apollo && !this.apollo.onReady) {
            this.$apollo.attached = false;
            const $apollo = this.$apollo;
            for (const key of Object.keys($apollo._query)) {
                $apollo.unsubscribe(key, 'query');
            }
            for (const key of Object.keys($apollo._subscription)) {
                $apollo.unsubscribe(key, 'subscription');
            }
        }
    }
}
<commit_msg>breaking changes - order of class instantiation<commit_after>/* eslint-disable no-param-reassign, func-names, no-console */
import omit from 'lodash.omit';
import clone from 'lodash.clone';

export class DollarApollo {
    constructor(el) {
        this.el = el;
        this.subscriptions = {};
        this.queries = {};
        this._query = {};
        this._subscription = {};
        this.attached = false;
    }

    get client() {
        return this.el._apolloClient;
    }

    get query() {
        return this.client.query.bind(this.client);
    }
    get mutate() {
        return this.client.mutate.bind(this.client);
    }

    watchQuery(options, key) {
        const observable = this.client.watchQuery(options);
        return this._processObservable(observable, key, 'query');
    }

    subscribe(options, key) {
        const observable = this.client.subscribe(options);
        return this._processObservable(observable, key, 'subscription');
    }
    _processObservable(observable, key, type) {
        const self = this;
        const _subscribe = observable.subscribe.bind(observable);
        observable.subscribe = (function (opt) {
            const sub = _subscribe(opt);

            const _unsubscribe = sub.unsubscribe.bind(sub);
            sub.unsubscribe = function () {
                _unsubscribe();
                self[`_${type}`][key].sub = null;
            };
            self[`_${type}`][key].sub = sub;
            return sub;
        });
        return observable;
    }
    _getSubscribeCallbacks(key, type) {
        const el = this.el;
        const $apollo = this;
        const entry = this[`_${type}`][key];
        const loadingKey = entry.loadingKey;
        const loadingChangeCb = entry.watchLoading;
        this._changeLoader(loadingKey, true, loadingChangeCb);

        function nextResult(result) {
            $apollo._changeLoader(loadingKey, false, loadingChangeCb);
            $apollo._applyData(result.data);
            if (typeof entry.success === 'function') {
                entry.success.call(el, result);
            }
        }

        function catchError(error) {
            $apollo._changeLoader(loadingKey, false, loadingChangeCb);
            if (error.graphQLErrors && error.graphQLErrors.length !== 0) {
                console.error(`GraphQL execution errors for ${type} ${key}`);
                for (const e of error.graphQLErrors) {
                    console.error(e);
                }
            } else if (error.networkError) {
                console.error(`Error sending the ${type} ${key}`, error.networkError);
            } else {
                console.error(error);
            }
            if (typeof entry.error === 'function') {
                entry.error.call(el, error);
            }
        }
        return { next: nextResult, error: catchError };
    }
    _subscribeObservable(key, observable, type) {
        const opt = this._getSubscribeCallbacks(key, type);
        const sub = observable.subscribe(opt);
        return sub;
    }

    _applyData(data) {
        if (data) {
            for (const key of Object.keys(data)) {
                this.el.set([key], data[key]);
            }
        }
    }

    _changeLoader(loadingKey, value, loadingChangeCb) {
        if (loadingKey) {
            this.el[loadingKey] = value;
        }

        if (loadingChangeCb) {
            loadingChangeCb(value);
        }
    }

    _refetch(key, entry) {
        const options = entry._options;
        const observable = entry.observable;
        const variables = options.variables;
        const opt = this._getSubscribeCallbacks(key, 'query');
        if (observable) {
            observable.refetch(variables, {
                forceFetch: !!options.forceFetch,
            }).then(opt.next, opt.error);
        }
    }

    refetch(key) {
        const entry = this._query[key];
        if (entry) {
            this._refetch(key, entry);
        } else {
            console.error(`Unable to find a query with key : ${key}`);
        }
    }

    _generateApolloOptions(options) {
        const apolloOptions = omit(options, [
            'error',
            'loadingKey',
            'watchLoading',
            'skip',
            '_options',
            'options',
            'result',
        ]);
        return apolloOptions;
    }
    createApolloOptions(apollo) {
        if (apollo) {
            const queries = omit(apollo, [
                'subscribe',
                'onReady',
            ]);
            this._query = queries || {};
            this._subscription = apollo.subscribe || {};
            for (const key of Object.keys(this._query)) {
                this._createOptionsProp(key, 'query');
            }
            for (const key of Object.keys(this._subscription)) {
                this._createOptionsProp(key, 'subscription');
            }
        }
    }
    _createOptionsProp(key, type) {
        const options = this[`_${type}`][key].options;
        const rnd = Math.floor(1000000000 + (Math.random() * 9000000000));
        var rId = `__apollo_${rnd}`;
        this[`_${type}`][key]._key = rnd;
    }
    init(el) {
        this.el = el;
        for (const key of Object.keys(this._query)) {
            this._processOptions(key, 'query');
        }
        for (const key of Object.keys(this._subscription)) {
            this._processOptions(key, 'subscription');
        }
    }
    start(el) {
        for (const key of Object.keys(this._query)) {
            const entry = this._query[key];
            const options = entry._options || el[entry.options];
            this._polymerChange('query', key, options);
        }
        for (const key of Object.keys(this._subscription)) {
            const entry = this._subscription[key];
            const options = entry._options || el[entry.options];
            this._polymerChange('subscription', key, options);
        }
    }
    _processOptions(key, type) {
        const entry = this[`_${type}`][key];
        const rId = `__apollo_${entry._key}`;
        if (!this.el[`${rId}_callback`]) {
            if (typeof entry.options === 'string') {
                this._createPolymerObserver(rId, key, type);
            } else {
                entry._options = entry.options || { skip: false };
            }
            this[`_${type}`][key] = entry;
        }
    }
    _createPolymerObserver(rId, key, type) {
        const $apollo = this;
        // unique id for observer callback
        const cbId = `${rId}_callback`;
        this.el[cbId] = (n) => {
            $apollo._polymerChange(type, key, n);
        };
        this.el._createPropertyObserver(this[`_${type}`][key].options, cbId);
    }
    _polymerChange(type, key, options = {}) {
        if (this.attached) {
            const entry = this[`_${type}`][key];
            entry._options = options;
            const _observable = entry.observable;
            const skip = !!options.skip;
            const _sub = entry.sub;
            if (skip) {
                if (_sub) {
                    _sub.unsubscribe();
                    delete entry.sub;
                }
            } else if (_sub) {
                _observable.setOptions(options);
            } else {
                const processArg = Object.assign({}, entry, options);

                const { sub, observable } = this[`${type}Process`](key, processArg);
                entry.sub = sub;
                entry.observable = observable;
            }
            this[`_${type}`][key] = entry;
        }
    }
    queryProcess(key, options) {
        if (key && options) {
            // Create observer
            const observable = this.watchQuery(this._generateApolloOptions(options), key);
            this.queries[key] = observable;
            options.observable = observable;
            // subscribe observable
            const sub = this._subscribeObservable(key, observable, 'query');
            return { sub, observable };
        }
        return null;
    }
    subscriptionProcess(key, options) {
        if (key && options) {
            // Create observable
            const observable = this.subscribe(this._generateApolloOptions(options), key);
            this.subscriptions[key] = observable;
            options.observable = observable;
            this._subscription[key] = options;
            // subscribe observable
            const sub = this._subscribeObservable(key, observable, 'subscription');
            return { sub, observable };
        }
        return null;
    }
    unsubscribe(key, type) {
        const entry = this[`_${type}`][key];
        const sub = entry.sub;
        sub.unsubscribe();
        this[`${type}`][key] = omit(entry, 'sub');
    }
}
export const PolymerApolloMixin = (options, superclass) => class extends superclass {
    constructor() {
        super();
        this._apolloClient = options.apolloClient;
        this.$apollo = new DollarApollo(this);
        const apollo = this.apollo;
        if (apollo) {
            this.$apollo.createApolloOptions(apollo);
        }
    }
    connectedCallback() {
        super.connectedCallback();
        const apollo = this.apollo;
        this.$apollo = clone(this.$apollo);
        if (apollo) {
            this.$apollo.attached = true;
            this.$apollo.init(this);
        }
    }
    ready() {
        super.ready();
        const apollo = this.apollo;
        if (apollo) {
            this.$apollo.attached = true;
            this.$apollo.start(this);
        }
    }
    disconnectedCallback() {
        const apollo = this.apollo;
        if (apollo && !this.apollo.onReady) {
            this.$apollo.attached = false;
            const $apollo = this.$apollo;
            for (const key of Object.keys($apollo._query)) {
                $apollo.unsubscribe(key, 'query');
            }
            for (const key of Object.keys($apollo._subscription)) {
                $apollo.unsubscribe(key, 'subscription');
            }
        }
    }
}
<|endoftext|>


<commit_before>/**
 * Patterns slides - Automatic and customised slideshows.
 *
 * Copyright 2013 Simplon B.V. - Wichert Akkerman
 */
define([
    "jquery",
    "../registry",
    "shower"
], function($, patterns) {
    var slides = {
        name: "slides",

        init: function($el) {
            return $el;
        }
    };

    patterns.register(slides);
    return slides;
});
<commit_msg>Slides: re-init shower after injection has happened.<commit_after>/**
 * Patterns slides - Automatic and customised slideshows.
 *
 * Copyright 2013 Simplon B.V. - Wichert Akkerman
 */
define([
    "jquery",
    "../registry",
    "shower"
], function($, patterns) {
    var slides = {
        name: "slides",

        init: function($el) {
            return $el;
        }
    };

    $(document).on("patterns-injected", function() {
        shower.init();
    });

    patterns.register(slides);
    return slides;
});
<|endoftext|>


<commit_before>/**
 * Patterns stacks
 *
 * Copyright 2013 Simplon B.V. - Wichert Akkerman
 */
define([
    "jquery",
    "../core/parser",
    "../core/logger",
    "../utils",
    "../registry"
], function($, Parser, logging, utils, registry) {
    var log = logging.getLogger("stacks"),
        parser = new Parser("stacks");

    parser.add_argument("selector", "> *[id]");
    parser.add_argument("transition", "none", ["none", "css", "fade", "slide"]);
    parser.add_argument("effect-duration", "fast");
    parser.add_argument("effect-easing", "swing");

    var stacks = {
        name: "stacks",
        trigger: ".pat-stacks",

        init: function($el, opts) {
            var fragment = this._currentFragment();

            return $el.each(function() {
                stacks._setupStack(this, opts, fragment);
            });
        },

        _setup: function() {
            $(document).on("click", "a", this._onClick);
        },

        _setupStack: function(container, options, selected) {
            var $container = $(container),
                $sheets, $visible, $invisible;
            options=parser.parse($container, options);
            $container.data("pat-stacks", options);
            $sheets=$container.find(options.selector);
            if ($sheets.length<2) {
                log.warn("Stacks pattern: must have more than one sheet.", $container[0]);
                return;
            }

            $visible=[];
            if (selected)
                $visible=$sheets.filter("#"+selected);
            if (!$visible.length) {
                $visible=$sheets.first();
                selected=$visible[0].id;
            }
            $invisible=$sheets.not($visible);
            utils.hideOrShow($visible, true, {transition: "none"}, stacks.name);
            utils.hideOrShow($invisible, false, {transition: "none"}, stacks.name);
            stacks._updateAnchors($container, selected);
        },

         _base_URL: function() {
            return document.URL.split("#")[0];
         },

        _currentFragment: function() {
            var parts = document.URL.split("#");
            if (parts.length===1)
                return null;
            return parts[parts.length-1];
        },

        _onClick: function(e) {
            var base_url = stacks._base_URL(),
                href_parts = e.target.href.split("#"),
                $stack;
            // Check if this is an in-document link and has a fragment
            if (base_url!==href_parts[0] || !href_parts[1])
                return;
            $stack=$(stacks.trigger+":has(#"+href_parts[1]+")");
            if (!$stack.length)
                return;
            e.preventDefault();
            stacks._updateAnchors($stack, href_parts[1]);
            stacks._switch($stack, href_parts[1]);
        },

        _updateAnchors: function($container, selected) {
            var options = $container.data("pat-stacks"),
                $sheets = $container.find(options.selector),
                base_url = stacks._base_URL();
            for (var i=0; i<$sheets.length; i++) {
                // This may appear odd, but: when querying a browser uses the
                // original href of an anchor as it appeared in the document
                // source, but when you access the href property you always
                // the fully qualified version.
                var sheet = $sheets[i],
                    $anchors = $("a[href=\""+base_url+"#"+sheet.id+"\"],a[href=\"#"+sheet.id+"\"]");
                if (sheet.id===selected)
                    $anchors.addClass("current");
                else
                    $anchors.removeClass("current");
            }
        },

        _switch: function($container, sheet_id) {
            var options = $container.data("pat-stacks"),
                $sheet = $container.find("#"+sheet_id),
                $invisible;
            if (!$sheet.length || $sheet.hasClass("visible"))
                return;
            $invisible=$container.find(options.selector).not($sheet);
            utils.hideOrShow($invisible, false, options, stacks.name);
            utils.hideOrShow($sheet, true, options, stacks.name);
        }
    };

    stacks._setup();
    registry.register(stacks);
    return stacks;
});
<commit_msg>stacks: fix handling of elements inside links.<commit_after>/**
 * Patterns stacks
 *
 * Copyright 2013 Simplon B.V. - Wichert Akkerman
 */
define([
    "jquery",
    "../core/parser",
    "../core/logger",
    "../utils",
    "../registry"
], function($, Parser, logging, utils, registry) {
    var log = logging.getLogger("stacks"),
        parser = new Parser("stacks");

    parser.add_argument("selector", "> *[id]");
    parser.add_argument("transition", "none", ["none", "css", "fade", "slide"]);
    parser.add_argument("effect-duration", "fast");
    parser.add_argument("effect-easing", "swing");

    var stacks = {
        name: "stacks",
        trigger: ".pat-stacks",

        init: function($el, opts) {
            var fragment = this._currentFragment();

            return $el.each(function() {
                stacks._setupStack(this, opts, fragment);
            });
        },

        _setup: function() {
            $(document).on("click", "a", this._onClick);
        },

        _setupStack: function(container, options, selected) {
            var $container = $(container),
                $sheets, $visible, $invisible;
            options=parser.parse($container, options);
            $container.data("pat-stacks", options);
            $sheets=$container.find(options.selector);
            if ($sheets.length<2) {
                log.warn("Stacks pattern: must have more than one sheet.", $container[0]);
                return;
            }

            $visible=[];
            if (selected)
                $visible=$sheets.filter("#"+selected);
            if (!$visible.length) {
                $visible=$sheets.first();
                selected=$visible[0].id;
            }
            $invisible=$sheets.not($visible);
            utils.hideOrShow($visible, true, {transition: "none"}, stacks.name);
            utils.hideOrShow($invisible, false, {transition: "none"}, stacks.name);
            stacks._updateAnchors($container, selected);
        },

         _base_URL: function() {
            return document.URL.split("#")[0];
         },

        _currentFragment: function() {
            var parts = document.URL.split("#");
            if (parts.length===1)
                return null;
            return parts[parts.length-1];
        },

        _onClick: function(e) {
            var base_url = stacks._base_URL(),
                href_parts = e.currentTarget.href.split("#"),
                $stack;
            // Check if this is an in-document link and has a fragment
            if (base_url!==href_parts[0] || !href_parts[1])
                return;
            $stack=$(stacks.trigger+":has(#"+href_parts[1]+")");
            if (!$stack.length)
                return;
            e.preventDefault();
            stacks._updateAnchors($stack, href_parts[1]);
            stacks._switch($stack, href_parts[1]);
        },

        _updateAnchors: function($container, selected) {
            var options = $container.data("pat-stacks"),
                $sheets = $container.find(options.selector),
                base_url = stacks._base_URL();
            for (var i=0; i<$sheets.length; i++) {
                // This may appear odd, but: when querying a browser uses the
                // original href of an anchor as it appeared in the document
                // source, but when you access the href property you always
                // the fully qualified version.
                var sheet = $sheets[i],
                    $anchors = $("a[href=\""+base_url+"#"+sheet.id+"\"],a[href=\"#"+sheet.id+"\"]");
                if (sheet.id===selected)
                    $anchors.addClass("current");
                else
                    $anchors.removeClass("current");
            }
        },

        _switch: function($container, sheet_id) {
            var options = $container.data("pat-stacks"),
                $sheet = $container.find("#"+sheet_id),
                $invisible;
            if (!$sheet.length || $sheet.hasClass("visible"))
                return;
            $invisible=$container.find(options.selector).not($sheet);
            utils.hideOrShow($invisible, false, options, stacks.name);
            utils.hideOrShow($sheet, true, options, stacks.name);
        }
    };

    stacks._setup();
    registry.register(stacks);
    return stacks;
});
<|endoftext|>


<commit_before>/**
 * @license
 * Patterns @VERSION@ toggle - toggle class on click
 *
 * Copyright 2012 Simplon B.V.
 * Copyright 2011 Humberto Sermeño
 * Copyright 2011 SYSLAB.COM GmbH
 */
define([
    "jquery",
    "../registry",
    "../core/logger",
    "../core/parser",
    "../core/store"
], function($, patterns, logger, Parser, store) {
    var log = logger.getLogger("pat.toggle"),
        parser = new Parser("toggle");

    parser.add_argument("selector");
    parser.add_argument("attr", "class");
    parser.add_argument("value");
    parser.add_argument("store", "none", ["none", "session", "local"]);

    var toggle = {
        name: "toggle",
        trigger: ".pat-toggle",

        init: function($el) {
            return $el.each(function() {
                var $trigger = $(this),
                    options = toggle._validateOptions(this, parser.parse($trigger, true)),
                    state = {toggled: false, options: options},
                    i, storage;

                if (!options.length)
                    return;

                if (options[0].store!=="none") {
                    storage=(options[0].store==="local" ? store.local : store.session)(toggle.name);
                    if (storage.get(this.id))
                        state.toggled=true;
                }

                if (state.toggled)
                    for (i=0; i<options.length; i++)
                        toggle._update(options[i].selector, options[i].attr, options[i].value, true);

                $trigger
                    .off(".toggle")
                    .data("patternToggle", state)
                    .on("click.toggle", toggle.onClick);
            });
        },

        _validateOptions: function(trigger, options) {
            var correct=[],
                i, option, store_error;

            if (!options.length)
                return correct;

            if (options[0].store!=="none") {
                if (!trigger.id) {
                    log.warn("state persistance requested, but element has no id");
                    options[0].store="none";
                } else if (!store.supported) {
                    store_error="browser does not support webstorage";
                    log.warn("state persistance requested, but browser does not support webstorage");
                    options[0].store="none";
                }
            }

            for (i=0; i<options.length; i++) {
                option=options[i];
                if (i && option.store!=="none") {
                    log.warn("store option can only be set on first argument");
                    option.store="none";
                }

                if (!option.selector || !option.attr || !option.value)
                    log.error("Toggle pattern requires selector, attr and value.");
                else
                    correct.push(option);
            }
            return correct;
        },

        onClick: function(event) {
            var $trigger = $(this),
                state = $trigger.data("patternToggle"),
                option, i;

            state.toggled=!state.toggled;
            $trigger.data("patternToggle", state);

            if (state.options[0].store!=="none") {
                var storage=(state.options[0].store==="local" ? store.local : store.session)(toggle.name);
                if (state.toggled)
                    storage.set(this.id, true);
                else
                    storage.remove(this.id);
            }

            for (i=0; i<state.options.length; i++) {
                option=state.options[i];
                toggle._update(option.selector, option.attr, option.value, false);
            }
            event.preventDefault();
        },

        _update: function(selector, attr, value, reset) {
            var $targets = $(selector),
                $target;

            if (!$targets.length)
                return;

            if (attr==="class") {
                $targets.toggleClass(value);
            } else {
                for (var i=0; i<$targets.length; i++) {
                    $target=$targets.eq(i);
                    if ($target.attr(attr)) {
                        if (reset)
                            $target.removeAttr(attr);
                        else
                            $target.prop(attr, false);
                    } else {
                        if (reset)
                            $target.attr(attr, attr);
                        else
                            $target.prop(attr, true);
                    }
                }
            }
        }
    };

    patterns.register(toggle);
    return toggle; // XXX for tests only
});

// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<commit_msg>Small header update<commit_after>/**
 * Patterns toggle - toggle class on click
 *
 * Copyright 2012 Simplon B.V. - Wichert Akkerman
 * Copyright 2011 Humberto Sermeño
 * Copyright 2011 SYSLAB.COM GmbH
 */
define([
    "jquery",
    "../registry",
    "../core/logger",
    "../core/parser",
    "../core/store"
], function($, patterns, logger, Parser, store) {
    var log = logger.getLogger("pat.toggle"),
        parser = new Parser("toggle");

    parser.add_argument("selector");
    parser.add_argument("attr", "class");
    parser.add_argument("value");
    parser.add_argument("store", "none", ["none", "session", "local"]);

    var toggle = {
        name: "toggle",
        trigger: ".pat-toggle",

        init: function($el) {
            return $el.each(function() {
                var $trigger = $(this),
                    options = toggle._validateOptions(this, parser.parse($trigger, true)),
                    state = {toggled: false, options: options},
                    i, storage;

                if (!options.length)
                    return;

                if (options[0].store!=="none") {
                    storage=(options[0].store==="local" ? store.local : store.session)(toggle.name);
                    if (storage.get(this.id))
                        state.toggled=true;
                }

                if (state.toggled)
                    for (i=0; i<options.length; i++)
                        toggle._update(options[i].selector, options[i].attr, options[i].value, true);

                $trigger
                    .off(".toggle")
                    .data("patternToggle", state)
                    .on("click.toggle", toggle.onClick);
            });
        },

        _validateOptions: function(trigger, options) {
            var correct=[],
                i, option, store_error;

            if (!options.length)
                return correct;

            if (options[0].store!=="none") {
                if (!trigger.id) {
                    log.warn("state persistance requested, but element has no id");
                    options[0].store="none";
                } else if (!store.supported) {
                    store_error="browser does not support webstorage";
                    log.warn("state persistance requested, but browser does not support webstorage");
                    options[0].store="none";
                }
            }

            for (i=0; i<options.length; i++) {
                option=options[i];
                if (i && option.store!=="none") {
                    log.warn("store option can only be set on first argument");
                    option.store="none";
                }

                if (!option.selector || !option.attr || !option.value)
                    log.error("Toggle pattern requires selector, attr and value.");
                else
                    correct.push(option);
            }
            return correct;
        },

        onClick: function(event) {
            var $trigger = $(this),
                state = $trigger.data("patternToggle"),
                option, i;

            state.toggled=!state.toggled;
            $trigger.data("patternToggle", state);

            if (state.options[0].store!=="none") {
                var storage=(state.options[0].store==="local" ? store.local : store.session)(toggle.name);
                if (state.toggled)
                    storage.set(this.id, true);
                else
                    storage.remove(this.id);
            }

            for (i=0; i<state.options.length; i++) {
                option=state.options[i];
                toggle._update(option.selector, option.attr, option.value, false);
            }
            event.preventDefault();
        },

        _update: function(selector, attr, value, reset) {
            var $targets = $(selector),
                $target;

            if (!$targets.length)
                return;

            if (attr==="class") {
                $targets.toggleClass(value);
            } else {
                for (var i=0; i<$targets.length; i++) {
                    $target=$targets.eq(i);
                    if ($target.attr(attr)) {
                        if (reset)
                            $target.removeAttr(attr);
                        else
                            $target.prop(attr, false);
                    } else {
                        if (reset)
                            $target.attr(attr, attr);
                        else
                            $target.prop(attr, true);
                    }
                }
            }
        }
    };

    patterns.register(toggle);
    return toggle; // XXX for tests only
});

// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<|endoftext|>