<commit_before>import externalRequest from 'request';

import { MOCK_API_PROBLEM } from 'meetup-web-mocks/lib/app';
import { MOCK_GROUP } from 'meetup-web-mocks/lib/api';

import { getServer, MOCK_LOGGER } from '../../../util/testUtils';

import { API_PROXY_PLUGIN_NAME } from '../';
import {
	makeApiResponseToQueryResponse,
	makeInjectResponseCookies,
	makeLogResponse,
	// getExternalRequestOpts,
	makeParseApiResponse,
	parseApiValue,
	parseMetaHeaders,
	parseVariantsHeader,
} from './receive';

describe('makeInjectResponseCookies', () => {
	const request = {
		plugins: {
			[API_PROXY_PLUGIN_NAME]: {
				setState() {},
			},
		},
		server: getServer(),
	};
	const responseObj = {
		request: {
			uri: {
				href: 'http://example.com',
			},
		},
	};
	const response = {
		toJSON() {
			return responseObj;
		},
	};

	it('does nothing without a cookie jar', () => {
		spyOn(response, 'toJSON');
		makeInjectResponseCookies(request)([response, null, null]);
		expect(response.toJSON).not.toHaveBeenCalled();
	});
	it('sets the provided cookies on the reply state', () => {
		const mockJar = externalRequest.jar();
		spyOn(request.plugins[API_PROXY_PLUGIN_NAME], 'setState');

		// set up mock cookie jar with a dummy cookie for the response.request.uri
		const key = 'foo';
		const value = 'bar';
		mockJar.setCookie(`${key}=${value}`, responseObj.request.uri.href);

		makeInjectResponseCookies(request)([response, null, mockJar]);
		expect(
			request.plugins[API_PROXY_PLUGIN_NAME].setState
		).toHaveBeenCalledWith(
			key,
			value,
			jasmine.any(Object) // don't actually care about the cookie options
		);
	});
});

describe('parseApiValue', () => {
	const MOCK_RESPONSE = {
		headers: {},
		statusCode: 200,
	};
	it('converts valid JSON into an equivalent object', () => {
		const validJSON = JSON.stringify(MOCK_GROUP);
		expect(parseApiValue([MOCK_RESPONSE, validJSON])).toEqual(
			jasmine.any(Object)
		);
		expect(parseApiValue([MOCK_RESPONSE, validJSON])).toEqual({
			value: MOCK_GROUP,
		});
	});
	it('returns an object with a string "error" value for invalid JSON', () => {
		const invalidJSON = 'not valid';
		expect(parseApiValue([MOCK_RESPONSE, invalidJSON]).error).toEqual(
			jasmine.any(String)
		);
	});
	it('returns an object with a string "error" value for API response with "problem"', () => {
		const responeWithProblem = JSON.stringify(MOCK_API_PROBLEM);
		expect(parseApiValue([MOCK_RESPONSE, responeWithProblem]).error).toEqual(
			jasmine.any(String)
		);
	});
	it('returns an object with a string "error" value for a not-ok response', () => {
		const noContentStatus = {
			statusCode: 204,
			statusMessage: 'No Content',
		};
		const noContentResponse = { ...MOCK_RESPONSE, ...noContentStatus };
		expect(parseApiValue([noContentResponse, '']).value).toBeNull();
	});
	it('returns an object with a string "error" value for a not-ok response', () => {
		const badStatus = {
			statusCode: 500,
			statusMessage: 'Problems',
		};
		const nonOkReponse = { ...MOCK_RESPONSE, ...badStatus };
		expect(parseApiValue([nonOkReponse, '{}']).error).toEqual(
			badStatus.statusMessage
		);
	});
	it('returns a value without any JS-literal unfriendly newline characters', () => {
		const fragileValue = 'foo \\u2028 \\u2029';
		const fragileJSON = JSON.stringify({ foo: fragileValue });
		const parsed = parseApiValue([MOCK_RESPONSE, fragileJSON]).value.foo;
		expect(parsed).toEqual('foo \\n \\n');
	});
});
describe('makeParseApiResponse', () => {
	const MOCK_RESPONSE = {
		headers: {},
		statusCode: 200,
	};
	it('returns the flags set in the X-Meetup-Flags header', () => {
		const headers = {
			'x-meetup-flags': 'foo=true, bar=false',
		};
		const flaggedResponse = { ...MOCK_RESPONSE, headers };
		expect(
			makeParseApiResponse('http://example.com')([flaggedResponse, '{}']).meta
				.flags
		).toEqual({
			foo: true,
			bar: false,
		});
	});
	it('returns the requestId set in the X-Meetup-Request-Id header', () => {
		const requestId = '1234';
		const headers = {
			'x-meetup-request-id': requestId,
		};
		const flaggedResponse = { ...MOCK_RESPONSE, headers };
		expect(
			makeParseApiResponse('http://example.com')([flaggedResponse, '{}']).meta
				.requestId
		).toEqual(requestId);
	});
});

describe('parseMetaHeaders', () => {
	it('returns x-meetup-flags as flags object with real booleans camelcased', () => {
		expect(parseMetaHeaders({ 'x-meetup-foo-bar': 'whatwhat' })).toMatchObject({
			fooBar: 'whatwhat',
		});
	});
	it('returns x-meetup-flags as flags object with real booleans', () => {
		expect(
			parseMetaHeaders({ 'x-meetup-flags': 'foo=true, bar=false' })
		).toMatchObject({ flags: { foo: true, bar: false } });
	});
	it('parses specified x- headers', () => {
		expect(parseMetaHeaders({ 'x-total-count': 'whatwhat' })).toMatchObject({
			totalCount: 'whatwhat',
		});
	});
	it('parses Link header', () => {
		const next = 'http://example.com/next';
		const prev = 'http://example.com/prev';

		// both 'next' and 'prev'
		expect(
			parseMetaHeaders({
				link: `<${next}>; rel="next", <${prev}>; rel="prev"`,
			})
		).toMatchObject({ link: { next, prev } });
		// just 'next'
		expect(parseMetaHeaders({ link: `<${next}>; rel="next"` })).toMatchObject({
			link: { next },
		});
	});
	it('returns empty object for empty headers', () => {
		expect(parseMetaHeaders({})).toEqual({});
	});
});

describe('parseVariantsHeader', () => {
	it('parses a variants header into a nested object', () => {
		const header =
			'binge-pilot=123|variant critical-mass=1|control critical-mass=2|sendemail';
		const expectedObj = {
			'binge-pilot': {
				123: 'variant',
			},
			'critical-mass': {
				1: 'control',
				2: 'sendemail',
			},
		};
		expect(parseVariantsHeader(header)).toEqual(expectedObj);
	});
	it('sets `null` variant for missing variant', () => {
		const header = 'binge-pilot=123|';
		const expectedObj = {
			'binge-pilot': {
				123: null,
			},
		};
		expect(parseVariantsHeader(header)).toEqual(expectedObj);
	});
});

describe('makeApiResponseToQueryResponse', () => {
	const refs = ['foo', 'bar'];
	const queries = refs.map(ref => ({ ref }));
	const MOCK_API_RESPONSES = refs.map(ref => ({ ref }));
	it('transforms an API response object to an object for State consumption', function() {
		MOCK_API_RESPONSES.map((apiResponse, i) =>
			makeApiResponseToQueryResponse(queries[i])(apiResponse)
		).forEach((queryResponse, i) => {
			expect(queryResponse).toEqual(jasmine.any(Object));
			expect(queryResponse.ref).toEqual(refs[i]);
		});
	});
});

describe('makeLogResponse', () => {
	const request = { server: getServer() };
	const MOCK_INCOMINGMESSAGE_GET = {
		elapsedTime: 1234,
		request: {
			uri: {
				query: 'foo=bar',
				pathname: '/foo',
			},
			method: 'get',
		},
	};
	const MOCK_INCOMINGMESSAGE_POST = {
		elapsedTime: 2345,
		request: {
			uri: {
				pathname: '/foo',
			},
			method: 'post',
		},
	};
	it('emits parsed request and response data for GET request', () => {
		MOCK_LOGGER.info.mockClear();
		makeLogResponse(request)([MOCK_INCOMINGMESSAGE_GET, 'foo']);
		expect(MOCK_LOGGER.info).toHaveBeenCalled();
		const loggedObject = MOCK_LOGGER.info.mock.calls[0][0];
		expect(loggedObject).toEqual(jasmine.any(Object));
	});
	it('emits parsed request and response data for POST request', () => {
		MOCK_LOGGER.info.mockClear();
		makeLogResponse(request)([MOCK_INCOMINGMESSAGE_POST, 'foo']);
		expect(MOCK_LOGGER.info).toHaveBeenCalled();
		const loggedObject = MOCK_LOGGER.info.mock.calls[0][0];
		expect(loggedObject).toEqual(jasmine.any(Object));
	});
	it('handles multiple querystring vals for GET request', () => {
		MOCK_LOGGER.info.mockClear();
		const response = {
			...MOCK_INCOMINGMESSAGE_GET,
			request: {
				...MOCK_INCOMINGMESSAGE_GET.request,
				uri: {
					query: 'foo=bar&baz=boodle',
					pathname: '/foo',
				},
			},
		};
		makeLogResponse(request)([response, 'foo']);
		const loggedObject = MOCK_LOGGER.info.mock.calls[0][0];
		expect(loggedObject.info.query).toEqual({
			foo: 'bar',
			baz: 'boodle',
		});
	});
	it('returns the full body of the response if less than 256 characters', () => {
		const body = 'foo';
		MOCK_LOGGER.info.mockClear();
		makeLogResponse(request)([MOCK_INCOMINGMESSAGE_GET, body]);
		expect(MOCK_LOGGER.info).toHaveBeenCalled();
		const loggedObject = MOCK_LOGGER.info.mock.calls[0][0];
		expect(loggedObject.info.body).toEqual(body);
	});
	it('returns a truncated response body if more than 256 characters', () => {
		const body300 =
			'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean egestas viverra sem vel congue. Cras vitae malesuada justo. Fusce ut finibus felis, at sagittis leo. Morbi nec velit dignissim, viverra tellus at, pretium nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla turpis duis.';
		MOCK_LOGGER.info.mockClear();
		makeLogResponse(request)([MOCK_INCOMINGMESSAGE_GET, body300]);
		expect(MOCK_LOGGER.info).toHaveBeenCalled();
		const loggedObject = MOCK_LOGGER.info.mock.calls[0][0];
		expect(loggedObject.info.body.startsWith(body300.substr(0, 256))).toBe(
			true
		);
		expect(loggedObject.info.body.startsWith(body300)).toBe(false);
	});
});
<commit_msg>remove that line<commit_after>import externalRequest from 'request';

import { MOCK_API_PROBLEM } from 'meetup-web-mocks/lib/app';
import { MOCK_GROUP } from 'meetup-web-mocks/lib/api';

import { getServer, MOCK_LOGGER } from '../../../util/testUtils';

import { API_PROXY_PLUGIN_NAME } from '../';
import {
	makeApiResponseToQueryResponse,
	makeInjectResponseCookies,
	makeLogResponse,
	makeParseApiResponse,
	parseApiValue,
	parseMetaHeaders,
	parseVariantsHeader,
} from './receive';

describe('makeInjectResponseCookies', () => {
	const request = {
		plugins: {
			[API_PROXY_PLUGIN_NAME]: {
				setState() {},
			},
		},
		server: getServer(),
	};
	const responseObj = {
		request: {
			uri: {
				href: 'http://example.com',
			},
		},
	};
	const response = {
		toJSON() {
			return responseObj;
		},
	};

	it('does nothing without a cookie jar', () => {
		spyOn(response, 'toJSON');
		makeInjectResponseCookies(request)([response, null, null]);
		expect(response.toJSON).not.toHaveBeenCalled();
	});
	it('sets the provided cookies on the reply state', () => {
		const mockJar = externalRequest.jar();
		spyOn(request.plugins[API_PROXY_PLUGIN_NAME], 'setState');

		// set up mock cookie jar with a dummy cookie for the response.request.uri
		const key = 'foo';
		const value = 'bar';
		mockJar.setCookie(`${key}=${value}`, responseObj.request.uri.href);

		makeInjectResponseCookies(request)([response, null, mockJar]);
		expect(
			request.plugins[API_PROXY_PLUGIN_NAME].setState
		).toHaveBeenCalledWith(
			key,
			value,
			jasmine.any(Object) // don't actually care about the cookie options
		);
	});
});

describe('parseApiValue', () => {
	const MOCK_RESPONSE = {
		headers: {},
		statusCode: 200,
	};
	it('converts valid JSON into an equivalent object', () => {
		const validJSON = JSON.stringify(MOCK_GROUP);
		expect(parseApiValue([MOCK_RESPONSE, validJSON])).toEqual(
			jasmine.any(Object)
		);
		expect(parseApiValue([MOCK_RESPONSE, validJSON])).toEqual({
			value: MOCK_GROUP,
		});
	});
	it('returns an object with a string "error" value for invalid JSON', () => {
		const invalidJSON = 'not valid';
		expect(parseApiValue([MOCK_RESPONSE, invalidJSON]).error).toEqual(
			jasmine.any(String)
		);
	});
	it('returns an object with a string "error" value for API response with "problem"', () => {
		const responeWithProblem = JSON.stringify(MOCK_API_PROBLEM);
		expect(parseApiValue([MOCK_RESPONSE, responeWithProblem]).error).toEqual(
			jasmine.any(String)
		);
	});
	it('returns an object with a string "error" value for a not-ok response', () => {
		const noContentStatus = {
			statusCode: 204,
			statusMessage: 'No Content',
		};
		const noContentResponse = { ...MOCK_RESPONSE, ...noContentStatus };
		expect(parseApiValue([noContentResponse, '']).value).toBeNull();
	});
	it('returns an object with a string "error" value for a not-ok response', () => {
		const badStatus = {
			statusCode: 500,
			statusMessage: 'Problems',
		};
		const nonOkReponse = { ...MOCK_RESPONSE, ...badStatus };
		expect(parseApiValue([nonOkReponse, '{}']).error).toEqual(
			badStatus.statusMessage
		);
	});
	it('returns a value without any JS-literal unfriendly newline characters', () => {
		const fragileValue = 'foo \\u2028 \\u2029';
		const fragileJSON = JSON.stringify({ foo: fragileValue });
		const parsed = parseApiValue([MOCK_RESPONSE, fragileJSON]).value.foo;
		expect(parsed).toEqual('foo \\n \\n');
	});
});
describe('makeParseApiResponse', () => {
	const MOCK_RESPONSE = {
		headers: {},
		statusCode: 200,
	};
	it('returns the flags set in the X-Meetup-Flags header', () => {
		const headers = {
			'x-meetup-flags': 'foo=true, bar=false',
		};
		const flaggedResponse = { ...MOCK_RESPONSE, headers };
		expect(
			makeParseApiResponse('http://example.com')([flaggedResponse, '{}']).meta
				.flags
		).toEqual({
			foo: true,
			bar: false,
		});
	});
	it('returns the requestId set in the X-Meetup-Request-Id header', () => {
		const requestId = '1234';
		const headers = {
			'x-meetup-request-id': requestId,
		};
		const flaggedResponse = { ...MOCK_RESPONSE, headers };
		expect(
			makeParseApiResponse('http://example.com')([flaggedResponse, '{}']).meta
				.requestId
		).toEqual(requestId);
	});
});

describe('parseMetaHeaders', () => {
	it('returns x-meetup-flags as flags object with real booleans camelcased', () => {
		expect(parseMetaHeaders({ 'x-meetup-foo-bar': 'whatwhat' })).toMatchObject({
			fooBar: 'whatwhat',
		});
	});
	it('returns x-meetup-flags as flags object with real booleans', () => {
		expect(
			parseMetaHeaders({ 'x-meetup-flags': 'foo=true, bar=false' })
		).toMatchObject({ flags: { foo: true, bar: false } });
	});
	it('parses specified x- headers', () => {
		expect(parseMetaHeaders({ 'x-total-count': 'whatwhat' })).toMatchObject({
			totalCount: 'whatwhat',
		});
	});
	it('parses Link header', () => {
		const next = 'http://example.com/next';
		const prev = 'http://example.com/prev';

		// both 'next' and 'prev'
		expect(
			parseMetaHeaders({
				link: `<${next}>; rel="next", <${prev}>; rel="prev"`,
			})
		).toMatchObject({ link: { next, prev } });
		// just 'next'
		expect(parseMetaHeaders({ link: `<${next}>; rel="next"` })).toMatchObject({
			link: { next },
		});
	});
	it('returns empty object for empty headers', () => {
		expect(parseMetaHeaders({})).toEqual({});
	});
});

describe('parseVariantsHeader', () => {
	it('parses a variants header into a nested object', () => {
		const header =
			'binge-pilot=123|variant critical-mass=1|control critical-mass=2|sendemail';
		const expectedObj = {
			'binge-pilot': {
				123: 'variant',
			},
			'critical-mass': {
				1: 'control',
				2: 'sendemail',
			},
		};
		expect(parseVariantsHeader(header)).toEqual(expectedObj);
	});
	it('sets `null` variant for missing variant', () => {
		const header = 'binge-pilot=123|';
		const expectedObj = {
			'binge-pilot': {
				123: null,
			},
		};
		expect(parseVariantsHeader(header)).toEqual(expectedObj);
	});
});

describe('makeApiResponseToQueryResponse', () => {
	const refs = ['foo', 'bar'];
	const queries = refs.map(ref => ({ ref }));
	const MOCK_API_RESPONSES = refs.map(ref => ({ ref }));
	it('transforms an API response object to an object for State consumption', function() {
		MOCK_API_RESPONSES.map((apiResponse, i) =>
			makeApiResponseToQueryResponse(queries[i])(apiResponse)
		).forEach((queryResponse, i) => {
			expect(queryResponse).toEqual(jasmine.any(Object));
			expect(queryResponse.ref).toEqual(refs[i]);
		});
	});
});

describe('makeLogResponse', () => {
	const request = { server: getServer() };
	const MOCK_INCOMINGMESSAGE_GET = {
		elapsedTime: 1234,
		request: {
			uri: {
				query: 'foo=bar',
				pathname: '/foo',
			},
			method: 'get',
		},
	};
	const MOCK_INCOMINGMESSAGE_POST = {
		elapsedTime: 2345,
		request: {
			uri: {
				pathname: '/foo',
			},
			method: 'post',
		},
	};
	it('emits parsed request and response data for GET request', () => {
		MOCK_LOGGER.info.mockClear();
		makeLogResponse(request)([MOCK_INCOMINGMESSAGE_GET, 'foo']);
		expect(MOCK_LOGGER.info).toHaveBeenCalled();
		const loggedObject = MOCK_LOGGER.info.mock.calls[0][0];
		expect(loggedObject).toEqual(jasmine.any(Object));
	});
	it('emits parsed request and response data for POST request', () => {
		MOCK_LOGGER.info.mockClear();
		makeLogResponse(request)([MOCK_INCOMINGMESSAGE_POST, 'foo']);
		expect(MOCK_LOGGER.info).toHaveBeenCalled();
		const loggedObject = MOCK_LOGGER.info.mock.calls[0][0];
		expect(loggedObject).toEqual(jasmine.any(Object));
	});
	it('handles multiple querystring vals for GET request', () => {
		MOCK_LOGGER.info.mockClear();
		const response = {
			...MOCK_INCOMINGMESSAGE_GET,
			request: {
				...MOCK_INCOMINGMESSAGE_GET.request,
				uri: {
					query: 'foo=bar&baz=boodle',
					pathname: '/foo',
				},
			},
		};
		makeLogResponse(request)([response, 'foo']);
		const loggedObject = MOCK_LOGGER.info.mock.calls[0][0];
		expect(loggedObject.info.query).toEqual({
			foo: 'bar',
			baz: 'boodle',
		});
	});
	it('returns the full body of the response if less than 256 characters', () => {
		const body = 'foo';
		MOCK_LOGGER.info.mockClear();
		makeLogResponse(request)([MOCK_INCOMINGMESSAGE_GET, body]);
		expect(MOCK_LOGGER.info).toHaveBeenCalled();
		const loggedObject = MOCK_LOGGER.info.mock.calls[0][0];
		expect(loggedObject.info.body).toEqual(body);
	});
	it('returns a truncated response body if more than 256 characters', () => {
		const body300 =
			'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean egestas viverra sem vel congue. Cras vitae malesuada justo. Fusce ut finibus felis, at sagittis leo. Morbi nec velit dignissim, viverra tellus at, pretium nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla turpis duis.';
		MOCK_LOGGER.info.mockClear();
		makeLogResponse(request)([MOCK_INCOMINGMESSAGE_GET, body300]);
		expect(MOCK_LOGGER.info).toHaveBeenCalled();
		const loggedObject = MOCK_LOGGER.info.mock.calls[0][0];
		expect(loggedObject.info.body.startsWith(body300.substr(0, 256))).toBe(
			true
		);
		expect(loggedObject.info.body.startsWith(body300)).toBe(false);
	});
});
<|endoftext|>


<commit_before>var captionMinimise =
  document.querySelector('.windows-caption-buttons .caption-minimise, body.linux .titlebar-linux .caption-minimise')

var captionMaximise =
  document.querySelector('.windows-caption-buttons .caption-maximise, body.linux .titlebar-linux .caption-maximise')

var captionRestore =
  document.querySelector('.windows-caption-buttons .caption-restore, body.linux .titlebar-linux .caption-restore')

var captionClose =
  document.querySelector('.windows-caption-buttons .caption-close, body.linux .titlebar-linux .caption-close')

var windowIsMaximised = false
var windowIsFullscreen = false

if (navigator.platform === 'Win32') {
  captionMinimise.addEventListener('click', function (e) {
    remote.getCurrentWindow().minimize()
  })

  captionMaximise.addEventListener('click', function (e) {
    remote.getCurrentWindow().maximize()
  })

  captionRestore.addEventListener('click', function (e) {
    if (windowIsFullscreen) {
      remote.getCurrentWindow().setFullScreen(false)
    } else {
      remote.getCurrentWindow().restore()
    }
  })

  captionClose.addEventListener('click', function (e) {
    remote.getCurrentWindow().close()
  })

  if (windowIsMaximised || windowIsFullscreen) {
    captionMaximise.hidden = true
    captionRestore.hidden = false
  } else {
    captionMaximise.hidden = false
    captionRestore.hidden = true
  }

  ipc.on('maximize', function (e) {
    windowIsMaximised = true
    captionMaximise.hidden = true
    captionRestore.hidden = false
  })
  ipc.on('unmaximize', function (e) {
    windowIsMaximised = false
    captionMaximise.hidden = false
    captionRestore.hidden = true
  })
  ipc.on('enter-full-screen', function (e) {
    windowIsFullscreen = true
    captionMaximise.hidden = true
    captionRestore.hidden = false
  })
  ipc.on('leave-full-screen', function (e) {
    windowIsFullscreen = false
    if (windowIsMaximised) {
      captionMaximise.hidden = true
      captionRestore.hidden = false
    } else {
      captionMaximise.hidden = false
      captionRestore.hidden = true
    }
  })
}
<commit_msg>simplify caption button code<commit_after>var captionMinimise =
document.querySelector('.windows-caption-buttons .caption-minimise, body.linux .titlebar-linux .caption-minimise')

var captionMaximise =
document.querySelector('.windows-caption-buttons .caption-maximise, body.linux .titlebar-linux .caption-maximise')

var captionRestore =
document.querySelector('.windows-caption-buttons .caption-restore, body.linux .titlebar-linux .caption-restore')

var captionClose =
document.querySelector('.windows-caption-buttons .caption-close, body.linux .titlebar-linux .caption-close')

var windowIsMaximised = false
var windowIsFullscreen = false

function updateCaptionButtons () {
  if (windowIsMaximised || windowIsFullscreen) {
    captionMaximise.hidden = true
    captionRestore.hidden = false
  } else {
    captionMaximise.hidden = false
    captionRestore.hidden = true
  }
}

if (navigator.platform === 'Win32') {
  updateCaptionButtons()

  captionMinimise.addEventListener('click', function (e) {
    remote.getCurrentWindow().minimize()
  })

  captionMaximise.addEventListener('click', function (e) {
    remote.getCurrentWindow().maximize()
  })

  captionRestore.addEventListener('click', function (e) {
    if (windowIsFullscreen) {
      remote.getCurrentWindow().setFullScreen(false)
    } else {
      remote.getCurrentWindow().restore()
    }
  })

  captionClose.addEventListener('click', function (e) {
    remote.getCurrentWindow().close()
  })

  ipc.on('maximize', function (e) {
    windowIsMaximised = true
    updateCaptionButtons()
  })
  ipc.on('unmaximize', function (e) {
    windowIsMaximised = false
    updateCaptionButtons()
  })
  ipc.on('enter-full-screen', function (e) {
    windowIsFullscreen = true
    updateCaptionButtons()
  })
  ipc.on('leave-full-screen', function (e) {
    windowIsFullscreen = false
    updateCaptionButtons()
  })
}
<|endoftext|>


<commit_before>
import {objectEach, clone} from './../../helpers/object';
import {rangeEach} from './../../helpers/number';
import {align, getAlignmentClasses, getValidSelection, checkSelectionConsistency, markLabelAsSelected} from './utils';

export const ROW_ABOVE = 'row_above';
export const ROW_BELOW = 'row_below';
export const COLUMN_LEFT = 'col_left';
export const COLUMN_RIGHT = 'col_right';
export const CLEAR_COLUMN = 'clear_column';
export const REMOVE_ROW = 'remove_row';
export const REMOVE_COLUMN = 'remove_col';
export const UNDO = 'undo';
export const REDO = 'redo';
export const READ_ONLY = 'make_read_only';
export const ALIGNMENT = 'alignment';
export const SEPARATOR = '---------';
export const ITEMS = [
  ROW_ABOVE, ROW_BELOW, COLUMN_LEFT, COLUMN_RIGHT, CLEAR_COLUMN, REMOVE_ROW, REMOVE_COLUMN, UNDO, REDO, READ_ONLY,
  ALIGNMENT, SEPARATOR
];

/**
 * Gets new object with all predefined menu items.
 *
 * @returns {Object}
 */
export function predefinedItems() {
  const items = {};

  objectEach(_predefinedItems, (value, key) => items[key] = clone(value));

  return items;
}

const _predefinedItems = {
  [SEPARATOR]: {
    name: SEPARATOR
  },
  [ROW_ABOVE]: {
    key: ROW_ABOVE,
    name: 'Insert row above',

    callback: function(key, selection) {
      this.alter('insert_row', selection.start.row);
    },
    disabled: function() {
      let selected = getValidSelection(this);

      if (!selected) {
        return true;
      }
      let entireColumnSelection = [0, selected[1], this.countRows() - 1, selected[1]];

      return entireColumnSelection.join(',') === selected.join(',');
    },
    hidden: function() {
      return !this.getSettings().allowInsertRow;
    }
  },
  [ROW_BELOW]: {
    key: ROW_BELOW,
    name: 'Insert row below',

    callback: function(key, selection) {
      this.alter('insert_row', selection.end.row + 1);
    },
    disabled: function() {
      let selected = getValidSelection(this);

      if (!selected) {
        return true;
      }
      let entireColumnSelection = [0, selected[1], this.countRows() - 1, selected[1]];

      return entireColumnSelection.join(',') === selected.join(',');
    },
    hidden: function() {
      return !this.getSettings().allowInsertRow;
    }
  },
  [COLUMN_LEFT]: {
    key: COLUMN_LEFT,
    name: 'Insert column on the left',
    callback: function(key, selection) {
      this.alter('insert_col', selection.start.col);
    },
    disabled: function() {
      let selected = getValidSelection(this);

      if (!selected) {
        return true;
      }
      if (!this.isColumnModificationAllowed()) {
        return true;
      }
      let entireRowSelection = [selected[0], 0, selected[0], this.countCols() - 1];
      let rowSelected = entireRowSelection.join(',') == selected.join(',');

      return selected[1] < 0 || this.countCols() >= this.getSettings().maxCols || rowSelected;
    },
    hidden: function() {
      return !this.getSettings().allowInsertColumn;
    }
  },
  [COLUMN_RIGHT]: {
    key: COLUMN_RIGHT,
    name: 'Insert column on the right',

    callback: function(key, selection) {
      this.alter('insert_col', selection.end.col + 1);
    },
    disabled: function() {
      let selected = getValidSelection(this);

      if (!selected) {
        return true;
      }
      if (!this.isColumnModificationAllowed()) {
        return true;
      }
      let entireRowSelection = [selected[0], 0, selected[0], this.countCols() - 1];
      let rowSelected = entireRowSelection.join(',') == selected.join(',');

      return selected[1] < 0 || this.countCols() >= this.getSettings().maxCols || rowSelected;
    },
    hidden: function() {
      return !this.getSettings().allowInsertColumn;
    }
  },
  [CLEAR_COLUMN]: {
    key: CLEAR_COLUMN,
    name: 'Clear column',

    callback: function(key, selection) {
      let column = selection.start.col;

      rangeEach(Math.max(selection.start.row, selection.end.row), (row) => this.setDataAtCell(row, column, ''));
    },
    disabled: function() {
      let selected = getValidSelection(this);

      if (!selected) {
        return true;
      }
      let entireRowSelection = [selected[0], 0, selected[0], this.countCols() - 1];
      let rowSelected = entireRowSelection.join(',') == selected.join(',');

      return selected[1] < 0 || this.countCols() >= this.getSettings().maxCols || rowSelected;
    }
  },
  [REMOVE_ROW]: {
    key: REMOVE_ROW,
    name: 'Remove row',

    callback: function(key, selection) {
      let amount = selection.end.row - selection.start.row + 1;

      this.alter('remove_row', selection.start.row, amount);
    },
    disabled: function() {
      let selected = getValidSelection(this);

      if (!selected) {
        return true;
      }
      let entireColumnSelection = [0, selected[1], this.countRows() - 1, selected[1]];

      return entireColumnSelection.join(',') === selected.join(',');
    },
    hidden: function() {
      return !this.getSettings().allowRemoveRow;
    }
  },
  [REMOVE_COLUMN]: {
    key: REMOVE_COLUMN,
    name: 'Remove column',

    callback: function(key, selection) {
      let amount = selection.end.col - selection.start.col + 1;

      this.alter('remove_col', selection.start.col, amount);
    },
    disabled: function() {
      let selected = getValidSelection(this);

      if (!selected) {
        return true;
      }
      if (!this.isColumnModificationAllowed()) {
        return true;
      }
      let entireRowSelection = [selected[0], 0, selected[0], this.countCols() - 1];
      let rowSelected = entireRowSelection.join(',') == selected.join(',');

      return (selected[1] < 0 || rowSelected);
    },
    hidden: function() {
      return !this.getSettings().allowRemoveColumn;
    }
  },
  [UNDO]: {
    key: UNDO,
    name: 'Undo',

    callback: function() {
      this.undo();
    },
    disabled: function() {
      return this.undoRedo && !this.undoRedo.isUndoAvailable();
    }
  },
  [REDO]: {
    key: REDO,
    name: 'Redo',

    callback: function() {
      this.redo();
    },
    disabled: function() {
      return this.undoRedo && !this.undoRedo.isRedoAvailable();
    }
  },
  [READ_ONLY]: {
    key: READ_ONLY,
    name: function() {
      let label = 'Read only';
      let atLeastOneReadOnly = checkSelectionConsistency(this.getSelectedRange(), (row, col) => this.getCellMeta(row, col).readOnly);

      if (atLeastOneReadOnly) {
        label = markLabelAsSelected(label);
      }

      return label;
    },
    callback: function() {
      let range = this.getSelectedRange();
      let atLeastOneReadOnly = checkSelectionConsistency(range, (row, col) => this.getCellMeta(row, col).readOnly);

      range.forAll((row, col) => {
        this.getCellMeta(row, col).readOnly = atLeastOneReadOnly ? false : true;
      });
      this.render();
    },
    disabled: function() {
      return this.getSelectedRange() ? false : true;
    }
  },
  [ALIGNMENT]: {
    key: ALIGNMENT,
    name: 'Alignment',
    disabled: function() {
      return this.getSelectedRange() ? false : true;
    },
    submenu: {
      items: [
        {
          key: `${ALIGNMENT}:left`,
          name: function() {
            let label = 'Left';
            let hasClass = checkSelectionConsistency(this.getSelectedRange(), (row, col) => {
              let className = this.getCellMeta(row, col).className;

              if (className && className.indexOf('htLeft') !== -1) {
                return true;
              }
            });

            if (hasClass) {
              label = markLabelAsSelected(label);
            }

            return label;
          },
          callback: function() {
            let range = this.getSelectedRange();
            let stateBefore = getAlignmentClasses(range, (row, col) => this.getCellMeta(row, col).className);
            let type = 'horizontal';
            let alignment = 'htLeft';

            this.runHooks('beforeCellAlignment', stateBefore, range, type, alignment);
            align(range, type, alignment, (row, col) => this.getCellMeta(row, col));
            this.render();
          },
          disabled: false
        },
        {
          key: `${ALIGNMENT}:center`,
          name: function() {
            let label = 'Center';
            let hasClass = checkSelectionConsistency(this.getSelectedRange(), (row, col) => {
              let className = this.getCellMeta(row, col).className;

              if (className && className.indexOf('htCenter') !== -1) {
                return true;
              }
            });

            if (hasClass) {
              label = markLabelAsSelected(label);
            }

            return label;
          },
          callback: function() {
            let range = this.getSelectedRange();
            let stateBefore = getAlignmentClasses(range, (row, col) => this.getCellMeta(row, col).className);
            let type = 'horizontal';
            let alignment = 'htCenter';

            this.runHooks('beforeCellAlignment', stateBefore, range, type, alignment);
            align(range, type, alignment, (row, col) => this.getCellMeta(row, col));
            this.render();
          },
          disabled: false
        },
        {
          key: `${ALIGNMENT}:right`,
          name: function() {
            let label = 'Right';
            let hasClass = checkSelectionConsistency(this.getSelectedRange(), (row, col) => {
              let className = this.getCellMeta(row, col).className;

              if (className && className.indexOf('htRight') !== -1) {
                return true;
              }
            });

            if (hasClass) {
              label = markLabelAsSelected(label);
            }

            return label;
          },
          callback: function() {
            let range = this.getSelectedRange();
            let stateBefore = getAlignmentClasses(range, (row, col) => this.getCellMeta(row, col).className);
            let type = 'horizontal';
            let alignment = 'htRight';

            this.runHooks('beforeCellAlignment', stateBefore, range, type, alignment);
            align(range, type, alignment, (row, col) => this.getCellMeta(row, col));
            this.render();
          },
          disabled: false
        },
        {
          key: `${ALIGNMENT}:justify`,
          name: function() {
            let label = 'Justify';
            let hasClass = checkSelectionConsistency(this.getSelectedRange(), (row, col) => {
              let className = this.getCellMeta(row, col).className;

              if (className && className.indexOf('htJustify') !== -1) {
                return true;
              }
            });

            if (hasClass) {
              label = markLabelAsSelected(label);
            }

            return label;
          },
          callback: function() {
            let range = this.getSelectedRange();
            let stateBefore = getAlignmentClasses(range, (row, col) => this.getCellMeta(row, col).className);
            let type = 'horizontal';
            let alignment = 'htJustify';

            this.runHooks('beforeCellAlignment', stateBefore, range, type, alignment);
            align(range, type, alignment, (row, col) => this.getCellMeta(row, col));
            this.render();
          },
          disabled: false
        },
        {
          name: SEPARATOR
        },
        {
          key: `${ALIGNMENT}:top`,
          name: function() {
            let label = 'Top';
            let hasClass = checkSelectionConsistency(this.getSelectedRange(), (row, col) => {
              let className = this.getCellMeta(row, col).className;

              if (className && className.indexOf('htTop') !== -1) {
                return true;
              }
            });

            if (hasClass) {
              label = markLabelAsSelected(label);
            }
            return label;
          },
          callback: function() {
            let range = this.getSelectedRange();
            let stateBefore = getAlignmentClasses(range, (row, col) => this.getCellMeta(row, col).className);
            let type = 'vertical';
            let alignment = 'htTop';

            this.runHooks('beforeCellAlignment', stateBefore, range, type, alignment);
            align(range, type, alignment, (row, col) => this.getCellMeta(row, col));
            this.render();
          },
          disabled: false
        },
        {
          key: `${ALIGNMENT}:middle`,
          name: function() {
            let label = 'Middle';
            let hasClass = checkSelectionConsistency(this.getSelectedRange(), (row, col) => {
              let className = this.getCellMeta(row, col).className;

              if (className && className.indexOf('htMiddle') !== -1) {
                return true;
              }
            });

            if (hasClass) {
              label = markLabelAsSelected(label);
            }

            return label;
          },
          callback: function() {
            let range = this.getSelectedRange();
            let stateBefore = getAlignmentClasses(range, (row, col) => this.getCellMeta(row, col).className);
            let type = 'vertical';
            let alignment = 'htMiddle';

            this.runHooks('beforeCellAlignment', stateBefore, range, type, alignment);
            align(range, type, alignment, (row, col) => this.getCellMeta(row, col));
            this.render();
          },
          disabled: false
        },
        {
          key: `${ALIGNMENT}:bottom`,
          name: function() {
            let label = 'Bottom';
            let hasClass = checkSelectionConsistency(this.getSelectedRange(), (row, col) => {
              let className = this.getCellMeta(row, col).className;

              if (className && className.indexOf('htBottom') !== -1) {
                return true;
              }
            });

            if (hasClass) {
              label = markLabelAsSelected(label);
            }

            return label;
          },
          callback: function() {
            let range = this.getSelectedRange();
            let stateBefore = getAlignmentClasses(range, (row, col) => this.getCellMeta(row, col).className);
            let type = 'vertical';
            let alignment = 'htBottom';

            this.runHooks('beforeCellAlignment', stateBefore, range, type, alignment);
            align(range, type, alignment, (row, col) => this.getCellMeta(row, col));
            this.render();
          },
          disabled: false
        }
      ]
    }
  }
};
<commit_msg>Enable contextMenu's 'insert row' options for grids with only one row #1853<commit_after>
import {objectEach, clone} from './../../helpers/object';
import {rangeEach} from './../../helpers/number';
import {align, getAlignmentClasses, getValidSelection, checkSelectionConsistency, markLabelAsSelected} from './utils';

export const ROW_ABOVE = 'row_above';
export const ROW_BELOW = 'row_below';
export const COLUMN_LEFT = 'col_left';
export const COLUMN_RIGHT = 'col_right';
export const CLEAR_COLUMN = 'clear_column';
export const REMOVE_ROW = 'remove_row';
export const REMOVE_COLUMN = 'remove_col';
export const UNDO = 'undo';
export const REDO = 'redo';
export const READ_ONLY = 'make_read_only';
export const ALIGNMENT = 'alignment';
export const SEPARATOR = '---------';
export const ITEMS = [
  ROW_ABOVE, ROW_BELOW, COLUMN_LEFT, COLUMN_RIGHT, CLEAR_COLUMN, REMOVE_ROW, REMOVE_COLUMN, UNDO, REDO, READ_ONLY,
  ALIGNMENT, SEPARATOR
];

/**
 * Gets new object with all predefined menu items.
 *
 * @returns {Object}
 */
export function predefinedItems() {
  const items = {};

  objectEach(_predefinedItems, (value, key) => items[key] = clone(value));

  return items;
}

const _predefinedItems = {
  [SEPARATOR]: {
    name: SEPARATOR
  },
  [ROW_ABOVE]: {
    key: ROW_ABOVE,
    name: 'Insert row above',

    callback: function(key, selection) {
      this.alter('insert_row', selection.start.row);
    },
    disabled: function() {
      let selected = getValidSelection(this);

      if (!selected) {
        return true;
      }

      let rowCount = this.countRows();
      let entireColumnSelection = [0, selected[1], rowCount - 1, selected[1]];

      return (entireColumnSelection.join(',') === selected.join(',')) && rowCount > 1;
    },
    hidden: function() {
      return !this.getSettings().allowInsertRow;
    }
  },
  [ROW_BELOW]: {
    key: ROW_BELOW,
    name: 'Insert row below',

    callback: function(key, selection) {
      this.alter('insert_row', selection.end.row + 1);
    },
    disabled: function() {
      let selected = getValidSelection(this);

      if (!selected) {
        return true;
      }

      let rowCount = this.countRows();
      let entireColumnSelection = [0, selected[1], rowCount - 1, selected[1]];

      return (entireColumnSelection.join(',') === selected.join(',')) && rowCount > 1;
    },
    hidden: function() {
      return !this.getSettings().allowInsertRow;
    }
  },
  [COLUMN_LEFT]: {
    key: COLUMN_LEFT,
    name: 'Insert column on the left',
    callback: function(key, selection) {
      this.alter('insert_col', selection.start.col);
    },
    disabled: function() {
      let selected = getValidSelection(this);

      if (!selected) {
        return true;
      }
      if (!this.isColumnModificationAllowed()) {
        return true;
      }
      let entireRowSelection = [selected[0], 0, selected[0], this.countCols() - 1];
      let rowSelected = entireRowSelection.join(',') == selected.join(',');

      return selected[1] < 0 || this.countCols() >= this.getSettings().maxCols || rowSelected;
    },
    hidden: function() {
      return !this.getSettings().allowInsertColumn;
    }
  },
  [COLUMN_RIGHT]: {
    key: COLUMN_RIGHT,
    name: 'Insert column on the right',

    callback: function(key, selection) {
      this.alter('insert_col', selection.end.col + 1);
    },
    disabled: function() {
      let selected = getValidSelection(this);

      if (!selected) {
        return true;
      }
      if (!this.isColumnModificationAllowed()) {
        return true;
      }
      let entireRowSelection = [selected[0], 0, selected[0], this.countCols() - 1];
      let rowSelected = entireRowSelection.join(',') == selected.join(',');

      return selected[1] < 0 || this.countCols() >= this.getSettings().maxCols || rowSelected;
    },
    hidden: function() {
      return !this.getSettings().allowInsertColumn;
    }
  },
  [CLEAR_COLUMN]: {
    key: CLEAR_COLUMN,
    name: 'Clear column',

    callback: function(key, selection) {
      let column = selection.start.col;

      rangeEach(Math.max(selection.start.row, selection.end.row), (row) => this.setDataAtCell(row, column, ''));
    },
    disabled: function() {
      let selected = getValidSelection(this);

      if (!selected) {
        return true;
      }
      let entireRowSelection = [selected[0], 0, selected[0], this.countCols() - 1];
      let rowSelected = entireRowSelection.join(',') == selected.join(',');

      return selected[1] < 0 || this.countCols() >= this.getSettings().maxCols || rowSelected;
    }
  },
  [REMOVE_ROW]: {
    key: REMOVE_ROW,
    name: 'Remove row',

    callback: function(key, selection) {
      let amount = selection.end.row - selection.start.row + 1;

      this.alter('remove_row', selection.start.row, amount);
    },
    disabled: function() {
      let selected = getValidSelection(this);

      if (!selected) {
        return true;
      }
      let entireColumnSelection = [0, selected[1], this.countRows() - 1, selected[1]];

      return entireColumnSelection.join(',') === selected.join(',');
    },
    hidden: function() {
      return !this.getSettings().allowRemoveRow;
    }
  },
  [REMOVE_COLUMN]: {
    key: REMOVE_COLUMN,
    name: 'Remove column',

    callback: function(key, selection) {
      let amount = selection.end.col - selection.start.col + 1;

      this.alter('remove_col', selection.start.col, amount);
    },
    disabled: function() {
      let selected = getValidSelection(this);

      if (!selected) {
        return true;
      }
      if (!this.isColumnModificationAllowed()) {
        return true;
      }
      let entireRowSelection = [selected[0], 0, selected[0], this.countCols() - 1];
      let rowSelected = entireRowSelection.join(',') == selected.join(',');

      return (selected[1] < 0 || rowSelected);
    },
    hidden: function() {
      return !this.getSettings().allowRemoveColumn;
    }
  },
  [UNDO]: {
    key: UNDO,
    name: 'Undo',

    callback: function() {
      this.undo();
    },
    disabled: function() {
      return this.undoRedo && !this.undoRedo.isUndoAvailable();
    }
  },
  [REDO]: {
    key: REDO,
    name: 'Redo',

    callback: function() {
      this.redo();
    },
    disabled: function() {
      return this.undoRedo && !this.undoRedo.isRedoAvailable();
    }
  },
  [READ_ONLY]: {
    key: READ_ONLY,
    name: function() {
      let label = 'Read only';
      let atLeastOneReadOnly = checkSelectionConsistency(this.getSelectedRange(), (row, col) => this.getCellMeta(row, col).readOnly);

      if (atLeastOneReadOnly) {
        label = markLabelAsSelected(label);
      }

      return label;
    },
    callback: function() {
      let range = this.getSelectedRange();
      let atLeastOneReadOnly = checkSelectionConsistency(range, (row, col) => this.getCellMeta(row, col).readOnly);

      range.forAll((row, col) => {
        this.getCellMeta(row, col).readOnly = atLeastOneReadOnly ? false : true;
      });
      this.render();
    },
    disabled: function() {
      return this.getSelectedRange() ? false : true;
    }
  },
  [ALIGNMENT]: {
    key: ALIGNMENT,
    name: 'Alignment',
    disabled: function() {
      return this.getSelectedRange() ? false : true;
    },
    submenu: {
      items: [
        {
          key: `${ALIGNMENT}:left`,
          name: function() {
            let label = 'Left';
            let hasClass = checkSelectionConsistency(this.getSelectedRange(), (row, col) => {
              let className = this.getCellMeta(row, col).className;

              if (className && className.indexOf('htLeft') !== -1) {
                return true;
              }
            });

            if (hasClass) {
              label = markLabelAsSelected(label);
            }

            return label;
          },
          callback: function() {
            let range = this.getSelectedRange();
            let stateBefore = getAlignmentClasses(range, (row, col) => this.getCellMeta(row, col).className);
            let type = 'horizontal';
            let alignment = 'htLeft';

            this.runHooks('beforeCellAlignment', stateBefore, range, type, alignment);
            align(range, type, alignment, (row, col) => this.getCellMeta(row, col));
            this.render();
          },
          disabled: false
        },
        {
          key: `${ALIGNMENT}:center`,
          name: function() {
            let label = 'Center';
            let hasClass = checkSelectionConsistency(this.getSelectedRange(), (row, col) => {
              let className = this.getCellMeta(row, col).className;

              if (className && className.indexOf('htCenter') !== -1) {
                return true;
              }
            });

            if (hasClass) {
              label = markLabelAsSelected(label);
            }

            return label;
          },
          callback: function() {
            let range = this.getSelectedRange();
            let stateBefore = getAlignmentClasses(range, (row, col) => this.getCellMeta(row, col).className);
            let type = 'horizontal';
            let alignment = 'htCenter';

            this.runHooks('beforeCellAlignment', stateBefore, range, type, alignment);
            align(range, type, alignment, (row, col) => this.getCellMeta(row, col));
            this.render();
          },
          disabled: false
        },
        {
          key: `${ALIGNMENT}:right`,
          name: function() {
            let label = 'Right';
            let hasClass = checkSelectionConsistency(this.getSelectedRange(), (row, col) => {
              let className = this.getCellMeta(row, col).className;

              if (className && className.indexOf('htRight') !== -1) {
                return true;
              }
            });

            if (hasClass) {
              label = markLabelAsSelected(label);
            }

            return label;
          },
          callback: function() {
            let range = this.getSelectedRange();
            let stateBefore = getAlignmentClasses(range, (row, col) => this.getCellMeta(row, col).className);
            let type = 'horizontal';
            let alignment = 'htRight';

            this.runHooks('beforeCellAlignment', stateBefore, range, type, alignment);
            align(range, type, alignment, (row, col) => this.getCellMeta(row, col));
            this.render();
          },
          disabled: false
        },
        {
          key: `${ALIGNMENT}:justify`,
          name: function() {
            let label = 'Justify';
            let hasClass = checkSelectionConsistency(this.getSelectedRange(), (row, col) => {
              let className = this.getCellMeta(row, col).className;

              if (className && className.indexOf('htJustify') !== -1) {
                return true;
              }
            });

            if (hasClass) {
              label = markLabelAsSelected(label);
            }

            return label;
          },
          callback: function() {
            let range = this.getSelectedRange();
            let stateBefore = getAlignmentClasses(range, (row, col) => this.getCellMeta(row, col).className);
            let type = 'horizontal';
            let alignment = 'htJustify';

            this.runHooks('beforeCellAlignment', stateBefore, range, type, alignment);
            align(range, type, alignment, (row, col) => this.getCellMeta(row, col));
            this.render();
          },
          disabled: false
        },
        {
          name: SEPARATOR
        },
        {
          key: `${ALIGNMENT}:top`,
          name: function() {
            let label = 'Top';
            let hasClass = checkSelectionConsistency(this.getSelectedRange(), (row, col) => {
              let className = this.getCellMeta(row, col).className;

              if (className && className.indexOf('htTop') !== -1) {
                return true;
              }
            });

            if (hasClass) {
              label = markLabelAsSelected(label);
            }
            return label;
          },
          callback: function() {
            let range = this.getSelectedRange();
            let stateBefore = getAlignmentClasses(range, (row, col) => this.getCellMeta(row, col).className);
            let type = 'vertical';
            let alignment = 'htTop';

            this.runHooks('beforeCellAlignment', stateBefore, range, type, alignment);
            align(range, type, alignment, (row, col) => this.getCellMeta(row, col));
            this.render();
          },
          disabled: false
        },
        {
          key: `${ALIGNMENT}:middle`,
          name: function() {
            let label = 'Middle';
            let hasClass = checkSelectionConsistency(this.getSelectedRange(), (row, col) => {
              let className = this.getCellMeta(row, col).className;

              if (className && className.indexOf('htMiddle') !== -1) {
                return true;
              }
            });

            if (hasClass) {
              label = markLabelAsSelected(label);
            }

            return label;
          },
          callback: function() {
            let range = this.getSelectedRange();
            let stateBefore = getAlignmentClasses(range, (row, col) => this.getCellMeta(row, col).className);
            let type = 'vertical';
            let alignment = 'htMiddle';

            this.runHooks('beforeCellAlignment', stateBefore, range, type, alignment);
            align(range, type, alignment, (row, col) => this.getCellMeta(row, col));
            this.render();
          },
          disabled: false
        },
        {
          key: `${ALIGNMENT}:bottom`,
          name: function() {
            let label = 'Bottom';
            let hasClass = checkSelectionConsistency(this.getSelectedRange(), (row, col) => {
              let className = this.getCellMeta(row, col).className;

              if (className && className.indexOf('htBottom') !== -1) {
                return true;
              }
            });

            if (hasClass) {
              label = markLabelAsSelected(label);
            }

            return label;
          },
          callback: function() {
            let range = this.getSelectedRange();
            let stateBefore = getAlignmentClasses(range, (row, col) => this.getCellMeta(row, col).className);
            let type = 'vertical';
            let alignment = 'htBottom';

            this.runHooks('beforeCellAlignment', stateBefore, range, type, alignment);
            align(range, type, alignment, (row, col) => this.getCellMeta(row, col));
            this.render();
          },
          disabled: false
        }
      ]
    }
  }
};
<|endoftext|>


<commit_before>define (["./_default-component-plugin"], function (DefaultPlugin) {
	var IgniteUIDataSourcePlugin = IgniteUIDataSourcePlugin || DefaultPlugin.extend({
		init: function (options) {
			this._super(options);
		},
		getName: function () {
			return "igDataSource";
		},
		getMarkup: function (descriptor) {
			return null; // this is a non-visual component so it doesn't have any markup
		},
		getCodeEditorScriptSnippet: function (descriptor) {
			var code = "\t\t\t\twindow." + descriptor.id + " = new $.ig.DataSource({\n";
			var orderedReturnProps = [];
			// now write options / settings
			code += "\n\t\t\t\t});\n";
			return {
				codeString: code,
				lineCount: 3,
				orderedProps: orderedReturnProps
			};
		},
		getCodeEditorMarkupSnippet: function (descriptor) {
			return null;
		},
		/*
		addExtraMarkers: function (descriptor) {

		},
		*/
		requiresInitialization: function () {
			return true;
		},
		initComponent: function (descriptor) {
			window.frames[0][descriptor.id] = new $.ig.DataSource({});
		},
		getPropValue: function (descriptor) {
			// locate the dataSource control. Note that since this is not a widget, it's also not associated with any DOM elements
			// since it's not a visual control, and can be instantiated anywhere (including anonymous functions), there is no easy
			// way to get hold of the reference to that data source, unless its variable name is stored in the global (window) context.
			var obj = window.frames[0][descriptor.placeholder.attr("id")];
			//if (obj && obj instanceof $.ig.DataSource) {
			if (obj && obj._accumulatedTransactionLog) { // duck typing
				// get value from data source settings
				return obj.settings[descriptor.propName];
			}
			return descriptor.defaultValue;
		},
		update: function (descriptor) {
			var ide = this.settings.ide;
			var component = ide.componentById(descriptor.id);
			var opts = component.options ? component.options : {};
			var newOpts = $.extend({}, opts);
			newOpts[descriptor.propName] = descriptor.propValue;
			var codeMarker = component.codeMarker;
			var meta = codeMarker.extraMarkers;
			var options = meta.options;
			// set it in the ds
			var obj = window.frames[0][descriptor.id];
			var val = descriptor.propValue;
			//if (obj && obj instanceof $.ig.DataSource) {
			if (obj && obj._accumulatedTransactionLog) {
				// what should happen when a new dataSource option is set - rebind the data source?
				if (descriptor.args) {
					val = "function (event, args) { }";
					descriptor.propType = "literal";
				}
				if (descriptor.propType === "literal") {
					//We're binding to objects in the window scope
					obj.settings[descriptor.propName] = window.frames[0][val];
					obj.settings.dataSourceVal = val;
					obj._runtimeType = null;
				} else {
					obj.settings[descriptor.propName] = val;
				}
				var rebind = function () {
					//console.log("rebinding data source");
					obj.dataBind();
				}
				if (descriptor.delayBind) {
					// check if we have a wait in progress or not
					if (this.rebindTimeoutID) {
						clearTimeout(this.rebindTimeoutID);
					}
					this.rebindTimeoutID = setTimeout(rebind, descriptor.delayBind);
				} else {
					rebind();
				}
			}
			if (!options[descriptor.propName]) {
				this.addPropCode({
					component: component,
					propName: descriptor.propName,
					propValue: val,
					oldPropValue: descriptor.oldPropValue,
					defaultValue: val,
					propType: descriptor.propType,
					valueOptions: descriptor.valueOptions,
					schema: descriptor.schema
				}, true, false);
			} else {
				this.updatePropCode({
					component: component,
					propName: descriptor.propName,
					propValue: val,
					oldPropValue: descriptor.oldPropValue,
					propType: descriptor.propType,
					valueOptions: descriptor.valueOptions,
					schema: descriptor.schema
				});
			}
			if (descriptor.args) {
				ide.element.find(".code-button").click();

			}
		},
		render: function (container, descriptor) {
			var ds = window.frames[0][descriptor.id], ide = this.settings.ide, locale = $.plugin.dataSource.locale, dsval,
			that = this, ide = this.settings.ide, dscontainer, remoteContainer, localRemoteArea, localContainer;
			//if (!(ds instanceof $.ig.DataSource)) {
			if (!(ds && ds._accumulatedTransactionLog)) {
				throw new Error("Object with ID " + descriptor.id + " is not an instance of IG Data Source");
			}
			descriptor.delayBind = 1000; // 1000 ms before the data source rebinds after a property has been changed

			container.empty(); // fix for 168980
			if (ds.settings.dataSourceVal) {
				dsval = ds.settings.dataSourceVal;
			} else {
				dsval = ds.settings.dataSource;
			}
			if (dsval === null) {
				dsval = "";
			}
			$(".adorner-summary-sheet").addClass("data-source-summary-sheet");
			container.children(".ds-diag-container").remove();
			dscontainer = $("

").prependTo(container).addClass("ds-diag-container");
			remoteContainer = $("

").appendTo(dscontainer).addClass("ds-diag-remotecontainer");
			localRemoteArea = $("

").addClass("ds-diag-dt").prependTo(dscontainer);
			//$("" + locale.isYourData + ": ").appendTo(localRemoteArea).addClass("ds-diag-dt-label");
			//$("<input type=\"radio\" name=\"dstype\" id=\"dstype1\" checked value=\"" + locale.remote + "\"/>").addClass("ds-diag-dt-remote").appendTo(localRemoteArea);
			//$("" + locale.remote + "").appendTo(localRemoteArea).addClass("ds-diag-dt-remotelabel");
			//$("<input type=\"radio\" name=\"dstype\" id=\"dstype2\" value=\"" + locale.local + "\"/>").addClass("ds-diag-dt-local").appendTo(localRemoteArea);
			//$("" + locale.local + "").appendTo(localRemoteArea).addClass("ds-diag-dt-locallabel");
			// edit schema button
			localContainer = $("

").addClass("ds-diag-localcontainer").css("display", "none").appendTo(dscontainer);
			$("" + locale.editSchema + "").addClass("btn btn-default ds-diag-editschema").wrap("
").parent().prependTo($(".adorner-custom-footer"));
			//$("
" + locale.urlEndpoint + "").addClass("ds-diag-urllabel").appendTo(remoteContainer);
			$("
<input type=\"text\" class=\"form-control\"/>" + locale.test + "" + locale.setDataSource + "
").addClass("ds-diag-url").appendTo(remoteContainer);

			// for local
			//$("<input type=\"radio\" name=\"localdstype\" checked value=\"variable\"/>Type var name containing data:").appendTo(localContainer);
			$("" + locale.typeVarName + ":").appendTo(localContainer);
			$("<input type=\"text\" class=\"form-control\"/>").appendTo(localContainer);
			/*
			$("<input type=\"radio\" name=\"localdstype\" value=\"inline\"/>Or use inline data:").appendTo(localContainer);
			$("Edit Data").appendTo(localContainer);
			*/
			//dscontainer.find(".ds-diag-editschema-wrapper").clone().appendTo($(".adorner-custom-footer"));

			remoteContainer.css("display", "none");
			localContainer.css("display", "block");

			localRemoteArea.children("input[name=dstype]").on("change", function (event) {
				if ($(event.target).hasClass("ds-diag-dt-local")) {
					// hide remote, show local
					remoteContainer.css("display", "none");
					localContainer.css("display", "block");
				} else {
					// hide local, show remote
					localContainer.css("display", "none");
					remoteContainer.css("display", "block");
				}
			});
			remoteContainer.find(".ds-diag-url > input").val(dsval).keyup(function (event) {
				// update the dataSource's url property
				//ds.settings.dataSource = event.target.value; // validate?
			    //also update the code view
			    if (event.keyCode === 13) {
			        descriptor.propName = "dataSource";
			        descriptor.oldPropValue = event.target.value ? event.target.value.substring(0, event.target.value.length - 1) : "";
			        descriptor.propType = "string";
			        descriptor.propValue = event.target.value.trim();
			        that.update(descriptor);
			    }
			    event.preventDefault();
			    event.stopPropagation();
			});
			remoteContainer.find(".ds-diag-url > #setButton").click(function (event) {
			    descriptor.propName = "dataSource";
			    descriptor.oldPropValue = event.target.value ? event.target.value.substring(0, event.target.value.length - 1) : "";
			    descriptor.propType = "string";
			    descriptor.propValue = remoteContainer.find(".ds-diag-url > input").val().trim();
			    that.update(descriptor);
			});
			remoteContainer.find(".ds-diag-url > #testButton").click(function (event) {
				// test datasource by doing a query to it
			    var url = remoteContainer.find(".ds-diag-url > input").val(), testLabel = remoteContainer.find(".test-label"), locale = $.plugin.dataSource.locale;
				if (testLabel.length === 0) {
					testLabel = $("

").insertAfter(remoteContainer.find("input"));
				}
				if (url) {
					$.ajax({
						url: url,
						crossDomain: true,
						dataType : "jsonp"
					}).fail(function () {
						testLabel.addClass("test-fail").removeClass("test-success").text(locale.reqestFailed);
					}).done(function () {
						testLabel.removeClass("test-fail").addClass("test-success").text(locale.success);
					});
				} else {
				    testLabel.removeClass("test-fail").removeClass("test-success").text(locale.setValidUrl);
				}
			});
			// edit schema
			dscontainer.find(".ds-diag-editschema").click(function (event) {
				descriptor.compObject = ide.componentById(descriptor.id);
				descriptor.propName = "fields";
				descriptor.ide = ide;
				descriptor.propType = "array";
				descriptor.placeholder = descriptor.element; //TODO
				descriptor.provider = ide._codeProviders[descriptor.compObject.lib];
				var props = container.closest(".adorners").find("#propertyGrid").data("igGrid").dataSource.data();
				for (var i = 0; i < props.length; i++) {
					if (props[i].propName === "fields") {
						descriptor.schema = props[i].schema;
						descriptor.displayProp = props[i].displayProp;
						break;
					}
				}
				that.openCollectionEditor(descriptor);
			});
			/*
			dscontainer.find(".ds-diag-editdatainline").click(function (event) {
				//openPropertyEditor
			});
			*/
			localContainer.find("input").val(dsval).keyup(function (event) {
				// editing local data source
				//ds.settings.dataSource = event.target.value; // validate?
				// also update the code view
				descriptor.propName = "dataSource";
				descriptor.oldPropValue = event.target.value.substring(0, event.target.value.length - 1);
				descriptor.propType = "literal";
				descriptor.propValue = event.target.value.trim();
				that.update(descriptor);
			});
		}
	});
	return IgniteUIDataSourcePlugin;
});
<commit_msg>update data source component plugin<commit_after>define (["./_default-component-plugin"], function (DefaultPlugin) {
	var IgniteUIDataSourcePlugin = IgniteUIDataSourcePlugin || DefaultPlugin.extend({
		init: function (options) {
			this._super(options);
		},
		getName: function () {
			return "igDataSource";
		},
		getMarkup: function (descriptor) {
			return null; // this is a non-visual component so it doesn't have any markup
		},
		getCodeEditorScriptSnippet: function (descriptor) {
			var code = "\t\t\t\twindow." + descriptor.id + " = new $.ig.DataSource({\n";
			var orderedReturnProps = [];
			// now write options / settings
			code += "\n\t\t\t\t});\n";
			return {
				codeString: code,
				lineCount: 3,
				orderedProps: orderedReturnProps
			};
		},
		getCodeEditorMarkupSnippet: function (descriptor) {
			return null;
		},
		/*
		addExtraMarkers: function (descriptor) {

		},
		*/
		requiresInitialization: function () {
			return true;
		},
		initComponent: function (descriptor) {
			window.frames[0][descriptor.id] = new $.ig.DataSource({});
		},
		getPropValue: function (descriptor) {
			// locate the dataSource control. Note that since this is not a widget, it's also not associated with any DOM elements
			// since it's not a visual control, and can be instantiated anywhere (including anonymous functions), there is no easy
			// way to get hold of the reference to that data source, unless its variable name is stored in the global (window) context.
			var obj = window.frames[0][descriptor.placeholder.attr("id")];
			//if (obj && obj instanceof $.ig.DataSource) {
			if (obj && obj._accumulatedTransactionLog) { // duck typing
				// get value from data source settings
				return obj.settings[descriptor.propName];
			}
			return descriptor.defaultValue;
		},
		update: function (descriptor) {
			var ide = this.settings.ide;
			var component = ide.componentById(descriptor.id);
			var opts = component.options ? component.options : {};
			var newOpts = $.extend({}, opts);
			newOpts[descriptor.propName] = descriptor.propValue;
			var codeMarker = component.codeMarker;
			var meta = codeMarker.extraMarkers;
			var options = meta.options;
			// set it in the ds
			var obj = window.frames[0][descriptor.id];
			var val = descriptor.propValue;
			//if (obj && obj instanceof $.ig.DataSource) {
			if (obj && obj._accumulatedTransactionLog) {
				// what should happen when a new dataSource option is set - rebind the data source?
				if (descriptor.args) {
					val = "function (event, args) { }";
					descriptor.propType = "literal";
				}
				if (descriptor.propType === "literal") {
					//We're binding to objects in the window scope
					obj.settings[descriptor.propName] = window.frames[0][val];
					obj.settings.dataSourceVal = val;
					obj._runtimeType = null;
				} else {
					obj.settings[descriptor.propName] = val;
				}
				var rebind = function () {
					//console.log("rebinding data source");
					obj.dataBind();
				}
				if (descriptor.delayBind) {
					// check if we have a wait in progress or not
					if (this.rebindTimeoutID) {
						clearTimeout(this.rebindTimeoutID);
					}
					this.rebindTimeoutID = setTimeout(rebind, descriptor.delayBind);
				} else {
					rebind();
				}
			}
			if (!options[descriptor.propName]) {
				this.addPropCode({
					component: component,
					propName: descriptor.propName,
					propValue: val,
					oldPropValue: descriptor.oldPropValue,
					defaultValue: val,
					propType: descriptor.propType,
					valueOptions: descriptor.valueOptions,
					schema: descriptor.schema
				}, true, false);
			} else {
				this.updatePropCode({
					component: component,
					propName: descriptor.propName,
					propValue: val,
					oldPropValue: descriptor.oldPropValue,
					propType: descriptor.propType,
					valueOptions: descriptor.valueOptions,
					schema: descriptor.schema
				});
			}
			if (descriptor.args) {
				ide.element.find(".code-button").click();

			}
		},
		render: function (container, descriptor) {
			var ds = window.frames[0][descriptor.id], ide = this.settings.ide, locale = $.plugin.dataSource.locale, dsval,
			that = this, ide = this.settings.ide, dscontainer, remoteContainer, localRemoteArea, localContainer;
			//if (!(ds instanceof $.ig.DataSource)) {
			if (!(ds && ds._accumulatedTransactionLog)) {
				throw new Error("Object with ID " + descriptor.id + " is not an instance of IG Data Source");
			}
			descriptor.delayBind = 1000; // 1000 ms before the data source rebinds after a property has been changed

			container.empty(); // fix for 168980
			if (ds.settings.dataSourceVal) {
				dsval = ds.settings.dataSourceVal;
			} else {
				dsval = ds.settings.dataSource;
			}
			if (dsval === null) {
				dsval = "";
			}
			$(".adorner-summary-sheet").addClass("data-source-summary-sheet");
			container.children(".ds-diag-container").remove();
			dscontainer = $("

").prependTo(container).addClass("ds-diag-container");
			remoteContainer = $("

").appendTo(dscontainer).addClass("ds-diag-remotecontainer");
			localRemoteArea = $("

").addClass("ds-diag-dt").prependTo(dscontainer);
			//$("" + locale.isYourData + ": ").appendTo(localRemoteArea).addClass("ds-diag-dt-label");
			//$("<input type=\"radio\" name=\"dstype\" id=\"dstype1\" checked value=\"" + locale.remote + "\"/>").addClass("ds-diag-dt-remote").appendTo(localRemoteArea);
			//$("" + locale.remote + "").appendTo(localRemoteArea).addClass("ds-diag-dt-remotelabel");
			//$("<input type=\"radio\" name=\"dstype\" id=\"dstype2\" value=\"" + locale.local + "\"/>").addClass("ds-diag-dt-local").appendTo(localRemoteArea);
			//$("" + locale.local + "").appendTo(localRemoteArea).addClass("ds-diag-dt-locallabel");
			// edit schema button
			localContainer = $("

").addClass("ds-diag-localcontainer").css("display", "none").appendTo(dscontainer);
			$("" + locale.editSchema + "").addClass("btn btn-default ds-diag-editschema").wrap("
").parent().prependTo($(".adorner-custom-footer"));
			//$("
" + locale.urlEndpoint + "").addClass("ds-diag-urllabel").appendTo(remoteContainer);
			$("
<input type=\"text\" class=\"form-control\"/>" + locale.test + "" + locale.setDataSource + "
").addClass("ds-diag-url").appendTo(remoteContainer);

			// for local
			//$("<input type=\"radio\" name=\"localdstype\" checked value=\"variable\"/>Type var name containing data:").appendTo(localContainer);
			$("" + locale.typeVarName + ":").appendTo(localContainer);
			$("<input type=\"text\" class=\"form-control\"/>").appendTo(localContainer);
			/*
			$("<input type=\"radio\" name=\"localdstype\" value=\"inline\"/>Or use inline data:").appendTo(localContainer);
			$("Edit Data").appendTo(localContainer);
			*/
			//dscontainer.find(".ds-diag-editschema-wrapper").clone().appendTo($(".adorner-custom-footer"));

			remoteContainer.css("display", "none");
			localContainer.css("display", "block");

			localRemoteArea.children("input[name=dstype]").on("change", function (event) {
				if ($(event.target).hasClass("ds-diag-dt-local")) {
					// hide remote, show local
					remoteContainer.css("display", "none");
					localContainer.css("display", "block");
				} else {
					// hide local, show remote
					localContainer.css("display", "none");
					remoteContainer.css("display", "block");
				}
			});
			remoteContainer.find(".ds-diag-url > input").val(dsval).keyup(function (event) {
				// update the dataSource's url property
				//ds.settings.dataSource = event.target.value; // validate?
			    //also update the code view
			    if (event.keyCode === 13) {
			        descriptor.propName = "dataSource";
			        descriptor.oldPropValue = event.target.value ? event.target.value.substring(0, event.target.value.length - 1) : "";
			        descriptor.propType = "string";
			        descriptor.propValue = event.target.value.trim();
			        that.update(descriptor);
			    }
			    event.preventDefault();
			    event.stopPropagation();
			});
			remoteContainer.find(".ds-diag-url > #setButton").click(function (event) {
			    descriptor.propName = "dataSource";
			    descriptor.oldPropValue = event.target.value ? event.target.value.substring(0, event.target.value.length - 1) : "";
			    descriptor.propType = "string";
			    descriptor.propValue = remoteContainer.find(".ds-diag-url > input").val().trim();
			    that.update(descriptor);
			});
			remoteContainer.find(".ds-diag-url > #testButton").click(function (event) {
				// test datasource by doing a query to it
			    var url = remoteContainer.find(".ds-diag-url > input").val(), testLabel = remoteContainer.find(".test-label"), locale = $.plugin.dataSource.locale;
				if (testLabel.length === 0) {
					testLabel = $("

").insertAfter(remoteContainer.find("input"));
				}
				if (url) {
					$.ajax({
						url: url,
						crossDomain: true,
						dataType : "jsonp"
					}).fail(function () {
						testLabel.addClass("test-fail").removeClass("test-success").text(locale.reqestFailed);
					}).done(function () {
						testLabel.removeClass("test-fail").addClass("test-success").text(locale.success);
					});
				} else {
				    testLabel.removeClass("test-fail").removeClass("test-success").text(locale.setValidUrl);
				}
			});
			// edit schema
			dscontainer.find(".ds-diag-editschema").click(function (event) {
				descriptor.compObject = ide.componentById(descriptor.id);
				descriptor.propName = "fields";
				descriptor.ide = ide;
				descriptor.propType = "array";
				descriptor.placeholder = descriptor.element; //TODO
				descriptor.provider = ide._codeProviders[descriptor.compObject.lib];
				var props = container.closest(".adorners").find("#propertyGrid").data("igGrid").dataSource.data();
				for (var i = 0; i < props.length; i++) {
					if (props[i].propName === "fields") {
						descriptor.schema = props[i].schema;
						descriptor.displayProp = props[i].displayProp;
						break;
					}
				}
				that.openCollectionEditor(descriptor);
			});
			/*
			dscontainer.find(".ds-diag-editdatainline").click(function (event) {
				//openPropertyEditor
			});
			*/
			localContainer.find("input").val(dsval).keyup(function (event) {
				// editing local data source
				//ds.settings.dataSource = event.target.value; // validate?
				// also update the code view
				if (event.keyCode === 13) {
					descriptor.propName = "dataSource";
					descriptor.oldPropValue = event.target.value.substring(0, event.target.value.length - 1);
					descriptor.propType = "literal";
					descriptor.propValue = event.target.value.trim();
					that.update(descriptor);
				}
			});
		}
	});
	return IgniteUIDataSourcePlugin;
});
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var imageManipulatorRepository = require('../logic/ImageManipulatorRepository');
var config = require('../logic/ConfigurationLoader');

// ToDo: Add projectId params
// ToDo Better Error Handling
router.post('/checkAll', function(req, res) {
    // This request might take a while to finish the computations -> Needs a longer timeout,
    // so that the client will not run into a timeout
    res.setTimeout(config.getRequestTimeout());
    var bodyData = JSON.parse(req.body.data);

    // Sets a default falue to the body data if it was null
    bodyData = bodyData ? bodyData : {};

    imageManipulatorRepository.calculateDifferencesForAllImages(bodyData.autoCrop
        , bodyData.pixDiffThreshold
        , bodyData.distThreshold
        , function (job, isThresholdBreached) {
            res.statusCode = 200;
            res.json({message: 'OK', data: {job: job, isThresholdBreached: isThresholdBreached}});
        });
});

router.put('/:id/makeToNewReferenceImage', function(req, res) {
    var setId = req.params.id;

    imageManipulatorRepository.makeToNewReferenceImage(setId, function (job, updatedImageSet) {
        res.statusCode = 200;
        res.json({message: 'OK', data: {job: job, updatedImageSet: updatedImageSet}});
    });
});

router.get('/:id/getImageSet', function(req, res) {
    var setId = req.params.id;

    imageManipulatorRepository.getImageSet(setId, function (imageSet) {
        res.statusCode = 200;
        res.json({message: 'OK', data: {resultImageSet: imageSet}});
    });
});

router.put('/:id/modifyIgnoreAreas', function(req, res) {
    var setId = req.params.id;
    var ignoreAreas = JSON.parse(req.body.data).ignoreAreas;

    imageManipulatorRepository.modifyIgnoreAreas(setId, ignoreAreas, function (imageSet) {
        res.statusCode = 200;
        res.json({message: 'OK', data: {resultImageSet: imageSet}});
    });
});

router.put('/compareImageByName', function(req, res) {
    var reqData = JSON.parse(req.body.data);
    var imageBase64 = reqData.imageBase64;
    var imageName = reqData.imageName;
    var imageType = reqData.imageType;
    var projectId = reqData.projectId;

    imageManipulatorRepository.compareImageByName(imageName, imageType, imageBase64, projectId, function(job, isThresholdBreached) {
        res.statusCode = 200;
        res.json({ message: 'OK', data: {job: job, isThresholdBreached: isThresholdBreached}});
    });
});

router.get('/', function (req, res) {
    imageManipulatorRepository.getLastActiveJob(function (job) {
        res.statusCode = 200;
        res.json({ message: 'OK', data: {job: job} });
    });
});

router.delete('/:id', function (req, res) {
    var setId = req.params.id;

    imageManipulatorRepository.deleteImageSetFromModel(setId, function (job) {
        res.statusCode = 200;
        res.json({ message: 'OK', data: {job: job}});
    });
});

router.post('/addProject', function(req, res) {
    var projectName = JSON.parse(req.body.data).name;

    imageManipulatorRepository.addProject(projectName, function (job, newProject) {
        res.statusCode = 200;
        res.json({message: 'OK', data: {job: job, project: newProject}});
    });
});

router.put('/:id/editProject', function(req, res) {
    var projectId = req.params.id;
    var projectName = JSON.parse(req.body.data).name;

    imageManipulatorRepository.editProject(projectId, projectName, function (job, wasSuccessful) {
        res.statusCode = 200;
        res.json({message: 'OK', data: {job: job, wasSuccessful: wasSuccessful}});
    });
});

router.delete('/:id/removeProject', function(req, res) {
    var projectId = req.params.id;

    imageManipulatorRepository.removeProject(projectId, function (job, wasSuccessful) {
        res.statusCode = 200;
        res.json({message: 'OK', data: {job: job, wasSuccessful: wasSuccessful}});
    });
});

router.put('/:id/assignImageSetToProject', function(req, res) {
    var reqData = JSON.parse(req.body.data);
    var imageSetId = req.params.id;
    var projectIdFrom = reqData.projectIdFrom;
    var projectIdTo = reqData.projectIdTo;

    imageManipulatorRepository.assignImageSetToProject(imageSetId, projectIdFrom, projectIdTo, function (job, wasSuccessful) {
        res.statusCode = 200;
        res.json({message: 'OK', data: {job: job, wasSuccessful: wasSuccessful}});
    });
});

module.exports = router;
<commit_msg>Fixes a bug that caused the CompareImageByName API function to return a wrong isThresholdBreached value.<commit_after>var express = require('express');
var router = express.Router();
var imageManipulatorRepository = require('../logic/ImageManipulatorRepository');
var config = require('../logic/ConfigurationLoader');

// ToDo: Add projectId params
// ToDo Better Error Handling
router.post('/checkAll', function(req, res) {
    // This request might take a while to finish the computations -> Needs a longer timeout,
    // so that the client will not run into a timeout
    res.setTimeout(config.getRequestTimeout());
    var bodyData = JSON.parse(req.body.data);

    // Sets a default falue to the body data if it was null
    bodyData = bodyData ? bodyData : {};

    imageManipulatorRepository.calculateDifferencesForAllImages(bodyData.autoCrop
        , bodyData.pixDiffThreshold
        , bodyData.distThreshold
        , function (job, isThresholdBreached) {
            res.statusCode = 200;
            res.json({message: 'OK', data: {job: job, isThresholdBreached: isThresholdBreached}});
        });
});

router.put('/:id/makeToNewReferenceImage', function(req, res) {
    var setId = req.params.id;

    imageManipulatorRepository.makeToNewReferenceImage(setId, function (job, updatedImageSet) {
        res.statusCode = 200;
        res.json({message: 'OK', data: {job: job, updatedImageSet: updatedImageSet}});
    });
});

router.get('/:id/getImageSet', function(req, res) {
    var setId = req.params.id;

    imageManipulatorRepository.getImageSet(setId, function (imageSet) {
        res.statusCode = 200;
        res.json({message: 'OK', data: {resultImageSet: imageSet}});
    });
});

router.put('/:id/modifyIgnoreAreas', function(req, res) {
    var setId = req.params.id;
    var ignoreAreas = JSON.parse(req.body.data).ignoreAreas;

    imageManipulatorRepository.modifyIgnoreAreas(setId, ignoreAreas, function (imageSet) {
        res.statusCode = 200;
        res.json({message: 'OK', data: {resultImageSet: imageSet}});
    });
});

router.put('/compareImageByName', function(req, res) {
    // ToDo Make it consistent again
    var reqData = req.body;
    var imageBase64 = reqData.imageBase64;
    var imageName = reqData.imageName;
    var imageType = reqData.imageType;
    var projectId = reqData.projectId;

    imageManipulatorRepository.compareImageByName(imageName, imageType, imageBase64, projectId, function(job, isThresholdBreached) {
        res.statusCode = 200;
        res.json({ message: 'OK', data: {job: job, isThresholdBreached: isThresholdBreached}});
    });
});

router.get('/', function (req, res) {
    imageManipulatorRepository.getLastActiveJob(function (job) {
        res.statusCode = 200;
        res.json({ message: 'OK', data: {job: job} });
    });
});

router.delete('/:id', function (req, res) {
    var setId = req.params.id;

    imageManipulatorRepository.deleteImageSetFromModel(setId, function (job) {
        res.statusCode = 200;
        res.json({ message: 'OK', data: {job: job}});
    });
});

router.post('/addProject', function(req, res) {
    var projectName = JSON.parse(req.body.data).name;

    imageManipulatorRepository.addProject(projectName, function (job, newProject) {
        res.statusCode = 200;
        res.json({message: 'OK', data: {job: job, project: newProject}});
    });
});

router.put('/:id/editProject', function(req, res) {
    var projectId = req.params.id;
    var projectName = JSON.parse(req.body.data).name;

    imageManipulatorRepository.editProject(projectId, projectName, function (job, wasSuccessful) {
        res.statusCode = 200;
        res.json({message: 'OK', data: {job: job, wasSuccessful: wasSuccessful}});
    });
});

router.delete('/:id/removeProject', function(req, res) {
    var projectId = req.params.id;

    imageManipulatorRepository.removeProject(projectId, function (job, wasSuccessful) {
        res.statusCode = 200;
        res.json({message: 'OK', data: {job: job, wasSuccessful: wasSuccessful}});
    });
});

router.put('/:id/assignImageSetToProject', function(req, res) {
    var reqData = JSON.parse(req.body.data);
    var imageSetId = req.params.id;
    var projectIdFrom = reqData.projectIdFrom;
    var projectIdTo = reqData.projectIdTo;

    imageManipulatorRepository.assignImageSetToProject(imageSetId, projectIdFrom, projectIdTo, function (job, wasSuccessful) {
        res.statusCode = 200;
        res.json({message: 'OK', data: {job: job, wasSuccessful: wasSuccessful}});
    });
});

module.exports = router;
<|endoftext|>


<commit_before>var express   = require('express');
var router    = express.Router();
var User      = require('../model/user');
var passport  = require('passport');
var verify    = require('./verify');

router.get('/', function(req, res, next) {
    res.json({
        'status': 200,
        'message': 'Welcome to LTB bank !'
    });
});

router.get('/all', verify.verifyUser, function(req, res, next) {
    User.find({'role' : 'customer'}).populate('accounts').then(function (customers) {
        res.json({customers: customers});
    }, function (err) {
        console.log(err);
    });
});

router.get('/user/:username', verify.verifyUser, function(req, res, next) {
    User.find({'username': req.params.username}).then(function (user) {
        res.status(200).json({status: 200, user: user[0]});
    }, function (err) {
        console.log(err);
    });
});

router.post('/login', function (req, res, next) {
    passport.authenticate('local', function (err, user, info) {
        console.log(user);
        req.logIn(user, function (err) {
            if(err){
                res.status(401).json({status: 401, message: "Username or password invalid"});
                return;
            }
            var token = verify.getToken(user);
            res.status(200).json({status: 200, message: "Authorized", username: user.username, token: token});
        })
    })(req, res, next);
});

router.post('/register', function(req, res, next) {
    User.register( new User({
        mail: req.body.mail,
        firstname: req.body.firstname,
        lastname: req.body.lastname,
        username: req.body.username,
        role: req.body.role
    }), req.body.password, function (err, user) {
        if(err){
            res.status(500).json({status: 500, message: err.message});
            return;
        }
        res.status(200).json({status: 200, user: user});
    });
});

router.put('/user/:username', verify.verifyUser, function (req, res, next) {
    User.findOne({'username' : req.params.username}).then(function (user) {
        if(req.body.mail)      user.mail      = req.body.mail;
        if(req.body.firstname) user.firstname = req.body.firstname;
        if(req.body.lastname)  user.lastname  = req.body.lastname;
        if(req.body.username)  user.username  = req.body.username;

        user.save(function (err, user) {
            if(err) {
                res.json(err.message);
                return;
            }
            res.json(user);
        });
    }, function (err) {
        console.log(err);
    });
});

module.exports = router;<commit_msg>status added<commit_after>var express   = require('express');
var router    = express.Router();
var User      = require('../model/user');
var passport  = require('passport');
var verify    = require('./verify');

router.get('/', function(req, res, next) {
    res.json({
        'status': 200,
        'message': 'Welcome to LTB bank !'
    });
});

router.get('/all', verify.verifyUser, function(req, res, next) {
    User.find({'role' : 'customer'}).populate('accounts').then(function (customers) {
        res.json({customers: customers});
    }, function (err) {
        console.log(err);
    });
});

router.get('/user/:username', verify.verifyUser, function(req, res, next) {
    User.find({'username': req.params.username}).then(function (user) {
        res.status(200).json({status: 200, user: user[0]});
    }, function (err) {
        console.log(err);
    });
});

router.post('/login', function (req, res, next) {
    passport.authenticate('local', function (err, user, info) {
        console.log(user);
        req.logIn(user, function (err) {
            if(err){
                res.status(401).json({status: 401, message: "Username or password invalid"});
                return;
            }
            var token = verify.getToken(user);
            res.status(200).json({status: 200, message: "Authorized", username: user.username, token: token});
        })
    })(req, res, next);
});

router.post('/register', function(req, res, next) {
    User.register( new User({
        mail: req.body.mail,
        firstname: req.body.firstname,
        lastname: req.body.lastname,
        username: req.body.username,
        role: req.body.role
    }), req.body.password, function (err, user) {
        if(err){
            res.status(500).json({status: 500, message: err.message});
            return;
        }
        res.status(200).json({status: 200, user: user});
    });
});

router.put('/user/:username', verify.verifyUser, function (req, res, next) {
    User.findOne({'username' : req.params.username}).then(function (user) {
        if(req.body.mail)      user.mail      = req.body.mail;
        if(req.body.firstname) user.firstname = req.body.firstname;
        if(req.body.lastname)  user.lastname  = req.body.lastname;
        if(req.body.username)  user.username  = req.body.username;

        user.save(function (err, user) {
            if(err) {
                res.json(err.message);
                return;
            }
            res.status(200).json({status: 200, message: "user succesfully updated", user: user});
        });
    }, function (err) {
        console.log(err);
    });
});

module.exports = router;<|endoftext|>


<commit_before>const config = require('../config.js')
const routes = require('express').Router()
const uploadController = require('../controllers/uploadController')
const galleryController = require('../controllers/galleryController')

routes.get ('/check', (req, res, next) => {
	if(config.TOKEN === true)
		return res.json({token: false})
	return res.json({token: true})
})

routes.get('/info', (req, res, next) => {

	if(config.TOKEN === true)
		if(req.headers.auth !== config.clientToken)
			return res.status(401).send('not-authorized')

	return res.json({
		maxFileSize: config.uploads.maxsize.slice(0, -2)
	})
})

routes.get  ('/uploads', (req, res, next) => uploadController.list(req, res))
routes.post ('/upload', (req, res, next) => uploadController.upload(req, res, next))
routes.get  ('/gallery', (req, res, next) => galleryController.list(req, res, next))
routes.get  ('/gallery/test', (req, res, next) => galleryController.test(req, res, next))

module.exports = routes
<commit_msg>Fix on token check<commit_after>const config = require('../config.js')
const routes = require('express').Router()
const uploadController = require('../controllers/uploadController')
const galleryController = require('../controllers/galleryController')

routes.get ('/check', (req, res, next) => {
	return res.json({token: config.TOKEN})
})

routes.get('/info', (req, res, next) => {

	if(config.TOKEN === true)
		if(req.headers.auth !== config.clientToken)
			return res.status(401).send('not-authorized')

	return res.json({
		maxFileSize: config.uploads.maxsize.slice(0, -2)
	})
})

routes.get  ('/uploads', (req, res, next) => uploadController.list(req, res))
routes.post ('/upload', (req, res, next) => uploadController.upload(req, res, next))
routes.get  ('/gallery', (req, res, next) => galleryController.list(req, res, next))
routes.get  ('/gallery/test', (req, res, next) => galleryController.test(req, res, next))

module.exports = routes
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var article = require('../models/article')(mongoose.connection);
router.route('/api/news/:id')
    .all(article.list)
    .get(article.get)
    .put(article.create)
    .post(article.update)
    .delete(article.delete);

router.route('/api/news/')
    .get(function(req, res, next) {
        res.json(news);
    });
module.exports = router;<commit_msg>допилил монго<commit_after>var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var article = require('../models/article')(mongoose.connection);
router.route('/api/news/:id')
    .all(article.list)
    .get(article.get)
    .put(article.create)
    .post(article.update)
    .delete(article.remove);

router.route('/api/news/')
    .get(function(req, res, next) {
        res.json(news);
    });
module.exports = router;<|endoftext|>


<commit_before>var express = require('express');
var hipchat = require('../lib/hipchat');
var router = express.Router();
var fs = require('fs');

router.get('/', function(req, res, next) {
    res.render('json', {layout: false });
});

router.get("/image/:name", function(req, res) {

    var name = 'uploads/'+req.params.name;
    console.log( name );

    fs.readFile(name, function (err, data) {
        if (err) throw err;
        var img = new Buffer(data, 'base64');

        res.writeHead(200, {
            'Content-Type': 'image/jpg',
            'Content-Length': img.length
        });
        res.end(img);
    });

});

/* POST TEST */
router.post('/save', function(req, res, next) {

    var msg = req.body.message + ' ('+req.body.Filename+')';

    console.log( req.body );
    var link = 'http://lmodev.com:8888/api/image/' + req.files[0].filename;

    msg += "\n";
    msg += link;

    hipchat.success(msg);

    if (false) {
        res.render('xmlError', { layout: false, message: "Something broke!"});
    } else {
        res.render('xmlSuccess', { layout: false });
    }

});

module.exports = router;
<commit_msg>use new link old.lmodev.com<commit_after>var express = require('express');
var hipchat = require('../lib/hipchat');
var router = express.Router();
var fs = require('fs');

router.get('/', function(req, res, next) {
    res.render('json', {layout: false });
});

router.get("/image/:name", function(req, res) {

    var name = 'uploads/'+req.params.name;
    console.log( name );

    fs.readFile(name, function (err, data) {
        if (err) throw err;
        var img = new Buffer(data, 'base64');

        res.writeHead(200, {
            'Content-Type': 'image/jpg',
            'Content-Length': img.length
        });
        res.end(img);
    });

});

/* POST TEST */
router.post('/save', function(req, res, next) {

    var msg = req.body.message + ' ('+req.body.Filename+')';

    console.log( req.body );
    var link = 'http://old.lmodev.com:8888/api/image/' + req.files[0].filename;

    msg += "\n";
    msg += link;

    hipchat.success(msg);

    if (false) {
        res.render('xmlError', { layout: false, message: "Something broke!"});
    } else {
        res.render('xmlSuccess', { layout: false });
    }

});

module.exports = router;
<|endoftext|>


<commit_before>var useful = require('../lib/useful.js')
var config = require('../package')
var path = require('path')
var moment = require('moment')

var xlmns = {
		'xmlns:content': "http://purl.org/rss/1.0/modules/content/" ,
		// 'xmlns:wfw': "http://wellformedweb.org/CommentAPI/",
		// 'xmlns:dc': "http://purl.org/dc/elements/1.1/",
		'xmlns:atom': "http://www.w3.org/2005/Atom",
		'xmlns:sy': "http://purl.org/rss/1.0/modules/syndication/",
		'xmlns:slash': "http://purl.org/rss/1.0/modules/slash/"
}

renderRSS = function (req, res, next) {
	res.header("Content-Type", "application/rss+xml")
	useful.buildUpdates(20, function (err, results) {
		if (err) {
			res.send(err)
		} else {
			results.xlmns = xlmns
			results.config = config
			results.path = path
			results.moment = moment
			res.render('rss', results)
		}
	})
}

module.exports = renderRSS
<commit_msg>editing rss<commit_after>var useful = require('../lib/useful.js')
var config = require('../package')
var path = require('path')
var moment = require('moment')
var url = require('url')

var xlmns = {
		'xmlns:content': "http://purl.org/rss/1.0/modules/content/" ,
		// 'xmlns:wfw': "http://wellformedweb.org/CommentAPI/",
		// 'xmlns:dc': "http://purl.org/dc/elements/1.1/",
		'xmlns:atom': "http://www.w3.org/2005/Atom",
		'xmlns:sy': "http://purl.org/rss/1.0/modules/syndication/",
		'xmlns:slash': "http://purl.org/rss/1.0/modules/slash/"
}

renderRSS = function (req, res, next) {
	res.header("Content-Type", "application/rss+xml")
	useful.buildUpdates(20, function (err, results) {
		if (err) {
			res.send(err)
		} else {
			results.xlmns = xlmns
			results.config = config
			results.path = path
			results.moment = moment
			results.url = url
			res.render('rss', results)
		}
	})
}

module.exports = renderRSS
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var winston = require('winston');

var logger = new (winston.Logger)({
    transports: [
        new (winston.transports.File)({ filename: '/root/concepts-json/node_modules/sct-snapshot-rest-api/search.log' })
    ]
});

router.get('/', function(req, res,next) {
    var uri=req.query.uri;
    console.log("uri:" + uri);
    if (uri.indexOf("http://snomed.info/")<0){

        res.status(400);
        res.send("{Error:400, message:'system not found'}");
        return ;
    }
    var bar=uri.lastIndexOf("/");
    var id=uri.substring(bar + 1);
    var format="json";
    if (req.query.format) {
        format = req.query.format.toLowerCase();
    }
    console.log("format:" + format);
    console.log("id:" + id);
    if (format=="json"){
        var db=process.env.TS_MONGO_DB;
        var collection=process.env.TS_MONGO_COLLECTION;
        console.log("db:" + db + " , collection:" + collection);
        res.redirect("http://ihmi.termspace.com/api/snomed/" + db + "/" + collection + "/concepts/" + id);
        return
    }else{
        res.redirect("http://ihmi.termspace.com/?perspective=full&conceptId1=" + id + "&edition=en-edition&release=v20180731&langRefset=900000000000509007";

        return ;
    }

});
module.exports = router;
<commit_msg>testing redirection<commit_after>var express = require('express');
var router = express.Router();
var winston = require('winston');

var logger = new (winston.Logger)({
    transports: [
        new (winston.transports.File)({ filename: '/root/concepts-json/node_modules/sct-snapshot-rest-api/search.log' })
    ]
});

router.get('/', function(req, res,next) {
    var uri=req.query.uri;
    console.log("uri:" + uri);
    if (uri.indexOf("http://snomed.info/")<0){

        res.status(400);
        res.send("{Error:400, message:'system not found'}");
        return ;
    }
    var bar=uri.lastIndexOf("/");
    var id=uri.substring(bar + 1);
    var format="json";
    if (req.query.format) {
        format = req.query.format.toLowerCase();
    }
    console.log("format:" + format);
    console.log("id:" + id);
    if (format=="json"){
        var db=process.env.TS_MONGO_DB;
        var collection=process.env.TS_MONGO_COLLECTION;
        console.log("db:" + db + " , collection:" + collection);
        res.redirect("http://ihmi.termspace.com/api/snomed/" + db + "/" + collection + "/concepts/" + id);
        return
    }else{
        res.redirect("http://ihmi.termspace.com/?perspective=full&conceptId1=" + id + "&edition=en-edition&release=v20180731&langRefset=900000000000509007");

        return ;
    }

});
module.exports = router;
<|endoftext|>