<commit_before>import React from 'react';
import {
	View,
	Text,
	ListView,
	StyleSheet,
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import moment from 'moment';
import { connect } from 'react-redux';
import { Actions } from 'react-native-router-flux';
import Touchable from '../common/Touchable';
import { platformIOS, getHumanizedDuration } from '../../util/general';
import {
	MAX_CARD_WIDTH,
	WINDOW_WIDTH,
	WINDOW_HEIGHT,
	NAVIGATOR_IOS_HEIGHT,
	NAVIGATOR_ANDROID_HEIGHT,
	TAB_BAR_HEIGHT,
} from '../../styles/LayoutConstants';

const dataSource = new ListView.DataSource({
	rowHasChanged: (r1, r2) => r1 !== r2,
	sectionHeaderHasChanged: (s1, s2) => s1 !== s2
});

const ConferenceListView = ({ style, scrollEnabled, rows, personal, disabled, conferenceData, saved, addConference, removeConference }) => {
	if (personal && saved && saved.length === 0) {
		return (
			<View style={[style, rows ? styles.cardWidth : styles.fullWidth]}>
				<Text style={styles.noSavedSessions}>
					Click the star icon next to a session to save it to your list.
				</Text>
			</View>
		);
	} else {
		return (
			<ListView
				style={[style, rows ? styles.card : styles.full]}
				scrollEnabled={scrollEnabled}
				stickySectionHeadersEnabled={false}
				dataSource={dataSource.cloneWithRowsAndSections(convertArrayToMap(adjustData(conferenceData.schedule, saved, personal, rows)))}
				renderRow={(rowData, sectionID, rowID, highlightRow) => {
					// Don't render first row bc rendered by header
					if (Number(rowID) !== 0) {
						return (
							<View style={styles.rowContainer}>
								<EmptyItem />
								<ConferenceItem
									conferenceData={rowData}
									saved={isSaved(saved, rowData.id)}
									add={addConference}
									remove={removeConference}
									disabled={disabled}
								/>
							</View>
						);
					} else {
						return null;
					}
				}}
				renderSectionHeader={(sectionData, sectionID) => (
					// Render header along with first row
					<View style={styles.rowContainer}>
						<ConferenceHeader
							timestamp={sectionID}
						/>
						<ConferenceItem
							conferenceData={sectionData[0]}
							saved={isSaved(saved, sectionData[0].id)}
							add={addConference}
							remove={removeConference}
							disabled={disabled}
						/>
					</View>
				)}
			/>
		);
	}
};

function adjustData(scheduleArray, savedArray, personal, rows) {
	// Filter out saved items
	if (!personal || !savedArray) {
		if (!rows) {
			return scheduleArray;
		} else {
			const trimmed = {};
			const keys = Object.keys(scheduleArray);

			for (let i = 0; i < rows; ++i) {
				trimmed[keys[i]] = scheduleArray[keys[i]];
			}
			return trimmed;
		}
	} else {
		const filtered = {};

		if (rows) {
			for (let i = 0; i < savedArray.length && i < rows; ++i) {
				const key = savedArray[i];
				filtered[key] = scheduleArray[key];
			}
		} else {
			for (let i = 0; i < savedArray.length; ++i) {
				const key = savedArray[i];
				filtered[key] = scheduleArray[key];
			}
		}
		return filtered;
	}
}

function isSaved(savedArray, id) {
	for ( let i = 0; i < savedArray.length; ++i) {
		if (savedArray[i] === id) {
			return true;
		}
	}
	return false;
}

function convertArrayToMap(scheduleArray, header = false) {
	const scheduleMap = {};

	Object.keys(scheduleArray).forEach((key) => {
		const session = scheduleArray[key];
		if (!scheduleMap[session['start-time']]) {
			// Create an entry in the map for the timestamp if it hasn't yet been created
			scheduleMap[session['start-time']] = [];
		}
		scheduleMap[session['start-time']].push(session);
	});

	// Remove an item from section so spacing lines up
	if (header) {
		Object.keys(scheduleMap).forEach((key) => {
			scheduleMap[key].pop();
		});
	}
	return scheduleMap;
}

const ConferenceItem = ({ conferenceData, saved, add, remove, disabled }) => {
	return (
		<View
			style={styles.itemRow}
		>
			<CircleBorder />
			<View style={styles.titleContainer}>
				<Touchable
					onPress={() => Actions.ConferenceDetailView({ data: conferenceData })}
				>
					<View>
						{conferenceData['talk-title'] ? (
							<Text
								style={styles.titleText}
								numberOfLines={2}
							>
								{conferenceData['talk-title']}
							</Text>
						) : null }

						<Text style={styles.labelText}>
							{ conferenceData.label ? (
								<Text>{conferenceData.label} - </Text>
							) : null }
							{ conferenceData['talk-type'] === 'Keynote' ? (
								<Text>{conferenceData['talk-type']} - </Text>
							) : null }
							{getHumanizedDuration(conferenceData['start-time'], conferenceData['end-time'])}
						</Text>
					</View>
				</Touchable>
			</View>

			{ (!disabled) ? (
				<View style={styles.starButton}>
					<Touchable
						onPress={
							() => ((saved) ? (remove(conferenceData.id)) : (add(conferenceData.id)))
						}
					>
						<View style={styles.starButtonInner}>
							<Icon
								name={'ios-star-outline'}
								size={32}
								color={'#999'}
								style={styles.starOuterIcon}
							/>
							{ saved ? (
								<Icon
									name={'ios-star'}
									size={26}
									color={'yellow'}
									style={styles.starInnerIcon}
								/>
							) : null }
						</View>
					</Touchable>
				</View>
			) : null }
		</View>
	);
};

const EmptyItem = () => (
	<View style={styles.emptyRow} />
);

const ConferenceHeader = ({ timestamp }) => (
	<View
		style={styles.header}
	>
		<Text style={styles.headerText}>
			{moment(Number(timestamp)).format('h:mm')}
		</Text>
	</View>
);

const CircleBorder = () => (
	<View style={styles.borderContainer}>
		<View style={styles.line} />
		<View style={styles.circle} />
	</View>
);

const mapStateToProps = (state) => (
	{
		conferenceData: state.conference.data,
		saved: state.conference.saved
	}
);

const mapDispatchToProps = (dispatch) => (
	{
		addConference: (id) => {
			dispatch({ type: 'ADD_CONFERENCE', id });
		},
		removeConference: (id) => {
			dispatch({ type: 'REMOVE_CONFERENCE', id });
		}
	}
);

const ActualConferenceListView = connect(
	mapStateToProps,
	mapDispatchToProps
)(ConferenceListView);

const styles = StyleSheet.create({
	rowContainer: { flexDirection: 'row', height: 70 },
	full: { width: WINDOW_WIDTH, height: platformIOS ? (WINDOW_HEIGHT - NAVIGATOR_IOS_HEIGHT - TAB_BAR_HEIGHT) : (WINDOW_HEIGHT - NAVIGATOR_ANDROID_HEIGHT - TAB_BAR_HEIGHT) },
	card: { width: MAX_CARD_WIDTH },
	itemRow: { flexGrow: 1, flexDirection: 'row', backgroundColor: '#F9F9F9' },
	header: { justifyContent: 'flex-start', alignItems: 'center', width: 45, backgroundColor: '#F9F9F9', borderBottomWidth: 1, borderColor: '#F9F9F9' },
	headerText: { textAlign: 'right', alignSelf: 'stretch', color: '#000', fontSize: 12, marginTop: 7 },
	emptyRow: { width: 45, flexDirection: 'row',  backgroundColor: '#F9F9F9', borderBottomWidth: 1, borderColor: '#F9F9F9' },
	titleContainer: { flex: 1, marginTop: 3 },
	titleText: { alignSelf: 'stretch', fontSize: 18, color: '#000' },
	labelText: { fontSize: 13, paddingTop: 4 },
	starButton: { width: 50 },
	starButtonInner: { justifyContent: 'flex-start', alignItems: 'center' },
	starOuterIcon: { position: platformIOS() ? 'absolute' : 'relative', zIndex: 10, backgroundColor: 'rgba(0,0,0,0)' },
	starInnerIcon: { position: 'absolute', zIndex: platformIOS() ? 5 : 15, marginTop: 3 },
	borderContainer: { width: 1, alignSelf: 'stretch', marginHorizontal: 20, alignItems: 'flex-start' },
	line: { flexGrow: 1, borderLeftWidth: 1, borderColor: '#AAA', paddingBottom: 20 },
	circle: { position: 'absolute', top: 11, left: -2.5, height: 6, width: 6, borderRadius: 3, borderWidth: 1, borderColor: '#AAA', backgroundColor: '#F9F9F9' },
	bottomBorder: { borderBottomWidth: 1, borderBottomColor: '#DDD' },
	noSavedSessions: { flexGrow: 1, fontSize: 18, textAlign: 'center', padding: 40, lineHeight: 30 },
});

export default ActualConferenceListView;
<commit_msg>Fix height on conerence empty list full view<commit_after>import React from 'react';
import {
	View,
	Text,
	ListView,
	StyleSheet,
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import moment from 'moment';
import { connect } from 'react-redux';
import { Actions } from 'react-native-router-flux';
import Touchable from '../common/Touchable';
import { platformIOS, getHumanizedDuration } from '../../util/general';
import {
	MAX_CARD_WIDTH,
	WINDOW_WIDTH,
	WINDOW_HEIGHT,
	NAVIGATOR_IOS_HEIGHT,
	NAVIGATOR_ANDROID_HEIGHT,
	TAB_BAR_HEIGHT,
} from '../../styles/LayoutConstants';

const dataSource = new ListView.DataSource({
	rowHasChanged: (r1, r2) => r1 !== r2,
	sectionHeaderHasChanged: (s1, s2) => s1 !== s2
});

const ConferenceListView = ({ style, scrollEnabled, rows, personal, disabled, conferenceData, saved, addConference, removeConference }) => {
	if (personal && saved && saved.length === 0) {
		return (
			<View style={[style, rows ? styles.card : styles.full]}>
				<Text style={styles.noSavedSessions}>
					Click the star icon next to a session to save it to your list.
				</Text>
			</View>
		);
	} else {
		return (
			<ListView
				style={[style, rows ? styles.card : styles.full]}
				scrollEnabled={scrollEnabled}
				stickySectionHeadersEnabled={false}
				dataSource={dataSource.cloneWithRowsAndSections(convertArrayToMap(adjustData(conferenceData.schedule, saved, personal, rows)))}
				renderRow={(rowData, sectionID, rowID, highlightRow) => {
					// Don't render first row bc rendered by header
					if (Number(rowID) !== 0) {
						return (
							<View style={styles.rowContainer}>
								<EmptyItem />
								<ConferenceItem
									conferenceData={rowData}
									saved={isSaved(saved, rowData.id)}
									add={addConference}
									remove={removeConference}
									disabled={disabled}
								/>
							</View>
						);
					} else {
						return null;
					}
				}}
				renderSectionHeader={(sectionData, sectionID) => (
					// Render header along with first row
					<View style={styles.rowContainer}>
						<ConferenceHeader
							timestamp={sectionID}
						/>
						<ConferenceItem
							conferenceData={sectionData[0]}
							saved={isSaved(saved, sectionData[0].id)}
							add={addConference}
							remove={removeConference}
							disabled={disabled}
						/>
					</View>
				)}
			/>
		);
	}
};

function adjustData(scheduleArray, savedArray, personal, rows) {
	// Filter out saved items
	if (!personal || !savedArray) {
		if (!rows) {
			return scheduleArray;
		} else {
			const trimmed = {};
			const keys = Object.keys(scheduleArray);

			for (let i = 0; i < rows; ++i) {
				trimmed[keys[i]] = scheduleArray[keys[i]];
			}
			return trimmed;
		}
	} else {
		const filtered = {};

		if (rows) {
			for (let i = 0; i < savedArray.length && i < rows; ++i) {
				const key = savedArray[i];
				filtered[key] = scheduleArray[key];
			}
		} else {
			for (let i = 0; i < savedArray.length; ++i) {
				const key = savedArray[i];
				filtered[key] = scheduleArray[key];
			}
		}
		return filtered;
	}
}

function isSaved(savedArray, id) {
	for ( let i = 0; i < savedArray.length; ++i) {
		if (savedArray[i] === id) {
			return true;
		}
	}
	return false;
}

function convertArrayToMap(scheduleArray, header = false) {
	const scheduleMap = {};

	Object.keys(scheduleArray).forEach((key) => {
		const session = scheduleArray[key];
		if (!scheduleMap[session['start-time']]) {
			// Create an entry in the map for the timestamp if it hasn't yet been created
			scheduleMap[session['start-time']] = [];
		}
		scheduleMap[session['start-time']].push(session);
	});

	// Remove an item from section so spacing lines up
	if (header) {
		Object.keys(scheduleMap).forEach((key) => {
			scheduleMap[key].pop();
		});
	}
	return scheduleMap;
}

const ConferenceItem = ({ conferenceData, saved, add, remove, disabled }) => {
	return (
		<View
			style={styles.itemRow}
		>
			<CircleBorder />
			<View style={styles.titleContainer}>
				<Touchable
					onPress={() => Actions.ConferenceDetailView({ data: conferenceData })}
				>
					<View>
						{conferenceData['talk-title'] ? (
							<Text
								style={styles.titleText}
								numberOfLines={2}
							>
								{conferenceData['talk-title']}
							</Text>
						) : null }

						<Text style={styles.labelText}>
							{ conferenceData.label ? (
								<Text>{conferenceData.label} - </Text>
							) : null }
							{ conferenceData['talk-type'] === 'Keynote' ? (
								<Text>{conferenceData['talk-type']} - </Text>
							) : null }
							{getHumanizedDuration(conferenceData['start-time'], conferenceData['end-time'])}
						</Text>
					</View>
				</Touchable>
			</View>

			{ (!disabled) ? (
				<View style={styles.starButton}>
					<Touchable
						onPress={
							() => ((saved) ? (remove(conferenceData.id)) : (add(conferenceData.id)))
						}
					>
						<View style={styles.starButtonInner}>
							<Icon
								name={'ios-star-outline'}
								size={32}
								color={'#999'}
								style={styles.starOuterIcon}
							/>
							{ saved ? (
								<Icon
									name={'ios-star'}
									size={26}
									color={'yellow'}
									style={styles.starInnerIcon}
								/>
							) : null }
						</View>
					</Touchable>
				</View>
			) : null }
		</View>
	);
};

const EmptyItem = () => (
	<View style={styles.emptyRow} />
);

const ConferenceHeader = ({ timestamp }) => (
	<View
		style={styles.header}
	>
		<Text style={styles.headerText}>
			{moment(Number(timestamp)).format('h:mm')}
		</Text>
	</View>
);

const CircleBorder = () => (
	<View style={styles.borderContainer}>
		<View style={styles.line} />
		<View style={styles.circle} />
	</View>
);

const mapStateToProps = (state) => (
	{
		conferenceData: state.conference.data,
		saved: state.conference.saved
	}
);

const mapDispatchToProps = (dispatch) => (
	{
		addConference: (id) => {
			dispatch({ type: 'ADD_CONFERENCE', id });
		},
		removeConference: (id) => {
			dispatch({ type: 'REMOVE_CONFERENCE', id });
		}
	}
);

const ActualConferenceListView = connect(
	mapStateToProps,
	mapDispatchToProps
)(ConferenceListView);

const styles = StyleSheet.create({
	rowContainer: { flexDirection: 'row', height: 70 },
	full: { width: WINDOW_WIDTH, height: platformIOS ? (WINDOW_HEIGHT - NAVIGATOR_IOS_HEIGHT - TAB_BAR_HEIGHT) : (WINDOW_HEIGHT - NAVIGATOR_ANDROID_HEIGHT - TAB_BAR_HEIGHT) },
	card: { width: MAX_CARD_WIDTH },
	itemRow: { flexGrow: 1, flexDirection: 'row', backgroundColor: '#F9F9F9' },
	header: { justifyContent: 'flex-start', alignItems: 'center', width: 45, backgroundColor: '#F9F9F9', borderBottomWidth: 1, borderColor: '#F9F9F9' },
	headerText: { textAlign: 'right', alignSelf: 'stretch', color: '#000', fontSize: 12, marginTop: 7 },
	emptyRow: { width: 45, flexDirection: 'row',  backgroundColor: '#F9F9F9', borderBottomWidth: 1, borderColor: '#F9F9F9' },
	titleContainer: { flex: 1, marginTop: 3 },
	titleText: { alignSelf: 'stretch', fontSize: 18, color: '#000' },
	labelText: { fontSize: 13, paddingTop: 4 },
	starButton: { width: 50 },
	starButtonInner: { justifyContent: 'flex-start', alignItems: 'center' },
	starOuterIcon: { position: platformIOS() ? 'absolute' : 'relative', zIndex: 10, backgroundColor: 'rgba(0,0,0,0)' },
	starInnerIcon: { position: 'absolute', zIndex: platformIOS() ? 5 : 15, marginTop: 3 },
	borderContainer: { width: 1, alignSelf: 'stretch', marginHorizontal: 20, alignItems: 'flex-start' },
	line: { flexGrow: 1, borderLeftWidth: 1, borderColor: '#AAA', paddingBottom: 20 },
	circle: { position: 'absolute', top: 11, left: -2.5, height: 6, width: 6, borderRadius: 3, borderWidth: 1, borderColor: '#AAA', backgroundColor: '#F9F9F9' },
	bottomBorder: { borderBottomWidth: 1, borderBottomColor: '#DDD' },
	noSavedSessions: { flexGrow: 1, fontSize: 18, textAlign: 'center', padding: 40, lineHeight: 30 },
});

export default ActualConferenceListView;
<|endoftext|>


<commit_before>$(document).ready(function () {
	$("#NG1").nanoGallery({
		//itemsBaseURL:'http://localhost:3000',
		theme:'clean',
		thumbnailWidth: 'auto',
		thumbnailHeight: 100,
		locationHash: false,
		thumbnailHoverEffect:'borderLighter,imageScaleIn80',
		kind: 'json',
		jsonProvider: './nanoPhotosProvider.php',
	});
});<commit_msg>Webui: Pb with auto thumbnail size ?<commit_after>$(document).ready(function () {
	$("#NG1").nanoGallery({
		//itemsBaseURL:'http://localhost:3000',
		theme:'clean',
		thumbnailWidth: 150,
		thumbnailHeight: 150,
		locationHash: false,
		thumbnailHoverEffect:'borderLighter,imageScaleIn80',
		kind: 'json',
		jsonProvider: './nanoPhotosProvider.php',
	});
});<|endoftext|>


<commit_before>/**
 * Doc Comment Parser class.
 *
 * @example
 * for (let comment of node.leadingComments) {
 *   let tags = CommentParser.parse(comment);
 *   console.log(tags);
 * }
 */
export default class CommentParser {
  /**
   * parse comment to tags.
   * @param {ASTNode} commentNode - comment node.
   * @param {string} commentNode.value - comment body.
   * @param {string} commentNode.type - Block or Line.
   * @returns {Tag[]} parsed comment.
   */
  static parse(commentNode) {
    if (!this.isESDoc(commentNode)) return [];

    let comment = commentNode.value;
    console.log('comment', comment);

    // TODO: refactor
    comment = comment.replace(/\r\n/gm, '\n'); // for windows
    comment = comment.replace(/^\t*\s?/gm, ''); // remove trailing tab
    comment = comment.replace(/^\*\s?/, ''); // remove first '*'
    comment = comment.replace(/ $/, ''); // remove last ' '
    comment = comment.replace(/^ *\* ?/gm, ''); // remove line head '*'
    if (comment.charAt(0) !== '@')  comment = '@desc ' + comment; // auto insert @desc
    comment = comment.replace(/\s*$/, ''); // remove tail space.
    comment = comment.replace(/^(@\w+)$/gm, '$1 \\TRUE'); // auto insert tag text to non-text tag (e.g. @interface)
    comment = comment.replace(/^(@\w+)\s(.*)/gm, '\\Z$1\\Z$2'); // insert separator (\\Z@tag\\Ztext)
    let lines = comment.split('\\Z');

    let tagName = '';
    let tagValue = '';
    let tags = [];
    for (let i = 0; i < lines.length; i++) {
      let line = lines[i];
      if (line.charAt(0) === '@') {
        tagName = line;
        let nextLine = lines[i + 1];
        if (nextLine.charAt(0) === '@') {
          tagValue = '';
        } else {
          tagValue = nextLine;
          i++;
        }
        tagValue = tagValue.replace('\\TRUE', '').replace(/^\n/, '').replace(/\n*$/, '');
        tags.push({tagName, tagValue});
      }
    }
    return tags;
  }

  /**
   * judge doc comment or not.
   * @param {ASTNode} commentNode - comment node.
   * @returns {boolean} if true, this comment node is doc comment.
   */
  static isESDoc(commentNode) {
    if (commentNode.type !== 'Block') return false;
    return commentNode.value.charAt(0) === '*';
  }
}
<commit_msg>Remove console.log ;-)<commit_after>/**
 * Doc Comment Parser class.
 *
 * @example
 * for (let comment of node.leadingComments) {
 *   let tags = CommentParser.parse(comment);
 *   console.log(tags);
 * }
 */
export default class CommentParser {
  /**
   * parse comment to tags.
   * @param {ASTNode} commentNode - comment node.
   * @param {string} commentNode.value - comment body.
   * @param {string} commentNode.type - Block or Line.
   * @returns {Tag[]} parsed comment.
   */
  static parse(commentNode) {
    if (!this.isESDoc(commentNode)) return [];

    let comment = commentNode.value;

    // TODO: refactor
    comment = comment.replace(/\r\n/gm, '\n'); // for windows
    comment = comment.replace(/^\t*\s?/gm, ''); // remove trailing tab
    comment = comment.replace(/^\*\s?/, ''); // remove first '*'
    comment = comment.replace(/ $/, ''); // remove last ' '
    comment = comment.replace(/^ *\* ?/gm, ''); // remove line head '*'
    if (comment.charAt(0) !== '@')  comment = '@desc ' + comment; // auto insert @desc
    comment = comment.replace(/\s*$/, ''); // remove tail space.
    comment = comment.replace(/^(@\w+)$/gm, '$1 \\TRUE'); // auto insert tag text to non-text tag (e.g. @interface)
    comment = comment.replace(/^(@\w+)\s(.*)/gm, '\\Z$1\\Z$2'); // insert separator (\\Z@tag\\Ztext)
    let lines = comment.split('\\Z');

    let tagName = '';
    let tagValue = '';
    let tags = [];
    for (let i = 0; i < lines.length; i++) {
      let line = lines[i];
      if (line.charAt(0) === '@') {
        tagName = line;
        let nextLine = lines[i + 1];
        if (nextLine.charAt(0) === '@') {
          tagValue = '';
        } else {
          tagValue = nextLine;
          i++;
        }
        tagValue = tagValue.replace('\\TRUE', '').replace(/^\n/, '').replace(/\n*$/, '');
        tags.push({tagName, tagValue});
      }
    }
    return tags;
  }

  /**
   * judge doc comment or not.
   * @param {ASTNode} commentNode - comment node.
   * @returns {boolean} if true, this comment node is doc comment.
   */
  static isESDoc(commentNode) {
    if (commentNode.type !== 'Block') return false;
    return commentNode.value.charAt(0) === '*';
  }
}
<|endoftext|>


<commit_before>define(['sugar-web/activity/activity', "webL10n", 'activity/Board', 'activity/vanilla-state', 'activity/patterns', 'activity/shadeColor'], function (activity, l10n, Board, State, patterns, shadeColor) {
  require(['domReady!'], function (doc) {
    activity.setup();
    window.addEventListener('localized', function () {
      activity.getXOColor(function (err, color) {
        var dataStore = activity.getDatastoreObject();
        main(Board, State, patterns, color, shadeColor, l10n, dataStore);
      });
    });
  });
});

function main(Board, State, patterns, color, shadeColor, l10n, dataStore) {
  var state = new State({
    boardState: [],
    generation: 0,
    playPauseIcon: 'play',
    shouldPlay: false
  });
  var randomPattern = patterns[0],
      gliderPattern = patterns[1],
      noPattern = patterns[2],
      blankPattern = patterns[3];

  var target = document.querySelector('.main canvas');
  var board = new Board(state.state.boardState, color.fill, '#FBF6F5', shadeColor(color.stroke, 10), color.stroke, 12, 12, 2, 2, target);
  document.querySelector('.generation-count').style.color = color.fill;
  document.querySelector('.generation-status').style.color = color.fill;
  document.querySelector('.generation-status').innerText = l10n.get('Generation');

  board.draw();

  var storeLocally = function storeLocally(state) {
    dataStore.setDataAsText({
      boardState: state.boarState,
      generation: state.generation
    });
    console.log('writing');
    dataStore.save(function (err) {
      if (err) {
        console.log('writing failed.');
        console.error(err);
      } else {
        console.log('writing saved.');
      }
    });
  };

  var generateGeneration = function generateGeneration() {
    if (state.state.shouldPlay) {
      var nextGenerationBoard = state.state.boardState.map(function (row, y) {
        return row.map(function (cell, x) {
          return transformCellByRule(cell, findNeighbours(x, y));
        });
      });
      state.set(function (prev) {
        return {
          boardState: nextGenerationBoard,
          generation: prev.generation + 1
        };
      });
      setTimeout(generateGeneration, 100);
    } else {
      return 0;
    }
  };

  var transformCellByRule = function transformCellByRule(cell, neighbours) {
    var cellIsAlive = cell === 1 || cell === 2;
    var aliveInNeighbour = neighbours.filter(function (cell) {
      return cell === 1 || cell === 2;
    });
    var numOfAliveNeighbours = aliveInNeighbour.length;
    if (cellIsAlive) {
      if (numOfAliveNeighbours < 2) {
        return 0;
      } else if (numOfAliveNeighbours === 2 || numOfAliveNeighbours === 3) {
        return 1;
      } else {
        return 0;
      }
    } else {
      if (numOfAliveNeighbours === 3) {
        return 2;
      } else {
        return 0;
      }
    }
  };

  var findNeighbours = function findNeighbours(x, y) {
    var leftX = x - 1 === -1 ? 49 : x - 1;
    var rightX = x + 1 === 50 ? 0 : x + 1;
    var topY = y - 1 === -1 ? 29 : y - 1;
    var bottomY = y + 1 === 30 ? 0 : y + 1;
    var boardState = state.state.boardState;

    var left = boardState[y][leftX];
    var right = boardState[y][rightX];
    var top = boardState[topY][x];
    var bottom = boardState[bottomY][x];
    var leftTop = boardState[topY][leftX];
    var leftBottom = boardState[bottomY][leftX];
    var rightTop = boardState[topY][rightX];
    var rightBottom = boardState[bottomY][rightX];

    return [left, right, top, bottom, leftTop, leftBottom, rightTop, rightBottom];
  };

  state.subscribe({
    boardState: ['.fake-selector', function (fakeElem, value, prevValue) {
      board.update(value);
    }],

    generation: ['.generation-count', 'innerText'],

    playPauseIcon: ['#play-pause', function (elem, value, prevValue) {
      elem.className = value + ' toolbutton';
    }],

    shouldPlay: ['.fake-selector', function (fakeElem, value, prevValue) {
      if (value) {
        generateGeneration();
      }
    }]
  });

  dataStore.loadAsText(function (err, metadata, data) {
    console.log(data)
    var boardState = (data && data.state) ? data.state.boardState : randomPattern();
    var generation =  (data && data.state) ? data.state.generation : 0
    state.set({
      boardState: JSON.parse(boardState),
      generation: parseInt(generation)
    });
  });

  board.onClick(function (cellX, cellY) {
    state.set(function (prev) {
      var newState = [].concat(prev.boardState);
      newState[cellY][cellX] = 2;
      return {
        boardState: newState
      };
    });
  });

  document.querySelector('#play-pause').addEventListener('click', function () {
    state.set(function (prev) {
      var iconToSet = prev.playPauseIcon === 'play' ? 'pause' : 'play';
      var togglePlay = prev.shouldPlay === true ? false : true;
      if (prev.shouldPlay) {
        storeLocally({
          state: state.state.boardState,
          generation: state.state.generation
        });
      }
      return {
        playPauseIcon: iconToSet,
        shouldPlay: togglePlay
      };
    });
  });

  document.querySelector('#random').addEventListener('click', function () {
    state.set({
      boardState: randomPattern(),
      generation: 0
    });
  });
  document.querySelector('#glider').addEventListener('click', function () {
    state.set({
      boardState: glider(),
      generation: 0
    });
  });
  document.querySelector('#no').addEventListener('click', function () {
    state.set({
      boardState: no(),
      generation: 0
    });
  });
  document.querySelector('#clear').addEventListener('click', function () {
    state.set({
      boardState: blankPattern(),
      generation: 0,
      playPauseIcon: 'play',
      shouldPlay: false
    });
  });

  window.addEventListener('resize', function (e) {
    board.handleResize(window.innerWidth, state.state.boardState);
  });
  board.handleResize(window.innerWidth, state.state.boardState);
}<commit_msg>fixed typo<commit_after>define(['sugar-web/activity/activity', "webL10n", 'activity/Board', 'activity/vanilla-state', 'activity/patterns', 'activity/shadeColor'], function (activity, l10n, Board, State, patterns, shadeColor) {
  require(['domReady!'], function (doc) {
    activity.setup();
    window.addEventListener('localized', function () {
      activity.getXOColor(function (err, color) {
        var dataStore = activity.getDatastoreObject();
        main(Board, State, patterns, color, shadeColor, l10n, dataStore);
      });
    });
  });
});

function main(Board, State, patterns, color, shadeColor, l10n, dataStore) {
  var state = new State({
    boardState: [],
    generation: 0,
    playPauseIcon: 'play',
    shouldPlay: false
  });
  var randomPattern = patterns[0],
      gliderPattern = patterns[1],
      noPattern = patterns[2],
      blankPattern = patterns[3];

  var target = document.querySelector('.main canvas');
  var board = new Board(state.state.boardState, color.fill, '#FBF6F5', shadeColor(color.stroke, 10), color.stroke, 12, 12, 2, 2, target);
  document.querySelector('.generation-count').style.color = color.fill;
  document.querySelector('.generation-status').style.color = color.fill;
  document.querySelector('.generation-status').innerText = l10n.get('Generation');

  board.draw();

  var storeLocally = function storeLocally(state) {
    dataStore.setDataAsText({
      boardState: state.boardState,
      generation: state.generation
    });
    console.log('writing');
    dataStore.save(function (err) {
      if (err) {
        console.log('writing failed.');
        console.error(err);
      } else {
        console.log('writing saved.');
      }
    });
  };

  var generateGeneration = function generateGeneration() {
    if (state.state.shouldPlay) {
      var nextGenerationBoard = state.state.boardState.map(function (row, y) {
        return row.map(function (cell, x) {
          return transformCellByRule(cell, findNeighbours(x, y));
        });
      });
      state.set(function (prev) {
        return {
          boardState: nextGenerationBoard,
          generation: prev.generation + 1
        };
      });
      setTimeout(generateGeneration, 100);
    } else {
      return 0;
    }
  };

  var transformCellByRule = function transformCellByRule(cell, neighbours) {
    var cellIsAlive = cell === 1 || cell === 2;
    var aliveInNeighbour = neighbours.filter(function (cell) {
      return cell === 1 || cell === 2;
    });
    var numOfAliveNeighbours = aliveInNeighbour.length;
    if (cellIsAlive) {
      if (numOfAliveNeighbours < 2) {
        return 0;
      } else if (numOfAliveNeighbours === 2 || numOfAliveNeighbours === 3) {
        return 1;
      } else {
        return 0;
      }
    } else {
      if (numOfAliveNeighbours === 3) {
        return 2;
      } else {
        return 0;
      }
    }
  };

  var findNeighbours = function findNeighbours(x, y) {
    var leftX = x - 1 === -1 ? 49 : x - 1;
    var rightX = x + 1 === 50 ? 0 : x + 1;
    var topY = y - 1 === -1 ? 29 : y - 1;
    var bottomY = y + 1 === 30 ? 0 : y + 1;
    var boardState = state.state.boardState;

    var left = boardState[y][leftX];
    var right = boardState[y][rightX];
    var top = boardState[topY][x];
    var bottom = boardState[bottomY][x];
    var leftTop = boardState[topY][leftX];
    var leftBottom = boardState[bottomY][leftX];
    var rightTop = boardState[topY][rightX];
    var rightBottom = boardState[bottomY][rightX];

    return [left, right, top, bottom, leftTop, leftBottom, rightTop, rightBottom];
  };

  state.subscribe({
    boardState: ['.fake-selector', function (fakeElem, value, prevValue) {
      board.update(value);
    }],

    generation: ['.generation-count', 'innerText'],

    playPauseIcon: ['#play-pause', function (elem, value, prevValue) {
      elem.className = value + ' toolbutton';
    }],

    shouldPlay: ['.fake-selector', function (fakeElem, value, prevValue) {
      if (value) {
        generateGeneration();
      }
    }]
  });

  dataStore.loadAsText(function (err, metadata, data) {
    console.log(data)
    var boardState = (data && data.state) ? data.state.boardState : randomPattern();
    var generation =  (data && data.state) ? data.state.generation : 0
    state.set({
      boardState: JSON.parse(boardState),
      generation: parseInt(generation)
    });
  });

  board.onClick(function (cellX, cellY) {
    state.set(function (prev) {
      var newState = [].concat(prev.boardState);
      newState[cellY][cellX] = 2;
      return {
        boardState: newState
      };
    });
  });

  document.querySelector('#play-pause').addEventListener('click', function () {
    state.set(function (prev) {
      var iconToSet = prev.playPauseIcon === 'play' ? 'pause' : 'play';
      var togglePlay = prev.shouldPlay === true ? false : true;
      if (prev.shouldPlay) {
        storeLocally({
          state: state.state.boardState,
          generation: state.state.generation
        });
      }
      return {
        playPauseIcon: iconToSet,
        shouldPlay: togglePlay
      };
    });
  });

  document.querySelector('#random').addEventListener('click', function () {
    state.set({
      boardState: randomPattern(),
      generation: 0
    });
  });
  document.querySelector('#glider').addEventListener('click', function () {
    state.set({
      boardState: glider(),
      generation: 0
    });
  });
  document.querySelector('#no').addEventListener('click', function () {
    state.set({
      boardState: no(),
      generation: 0
    });
  });
  document.querySelector('#clear').addEventListener('click', function () {
    state.set({
      boardState: blankPattern(),
      generation: 0,
      playPauseIcon: 'play',
      shouldPlay: false
    });
  });

  window.addEventListener('resize', function (e) {
    board.handleResize(window.innerWidth, state.state.boardState);
  });
  board.handleResize(window.innerWidth, state.state.boardState);
}<|endoftext|>


<commit_before>import macro from 'vtk.js/Sources/macro';
import vtkDataArray from 'vtk.js/Sources/Common/Core/DataArray';
import vtkPolyData from 'vtk.js/Sources/Common/DataModel/PolyData';
import vtkMatrixBuilder from 'vtk.js/Sources/Common/Core/MatrixBuilder';

// ----------------------------------------------------------------------------
// vtkCubeSource methods
// ----------------------------------------------------------------------------

function vtkCubeSource(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkCubeSource');

  function requestData(inData, outData) {
    if (model.deleted) {
      return;
    }

    const polyData = vtkPolyData.newInstance();
    outData[0] = polyData;

    const numberOfPolys = 6;
    const numberOfPoints = 24;

    // Define points
    const points = new window[model.pointType](numberOfPoints * 3);
    polyData.getPoints().setData(points, 3);

    const normals = new window[model.pointType](numberOfPoints * 3);
    const normalArray = vtkDataArray.newInstance({
      name: 'Normals',
      values: normals,
      numberOfComponents: 3,
    });
    polyData.getPointData().setNormals(normalArray);

    let tcdim = 2;
    if (model.generate3DTextureCoordinates === true) {
      tcdim = 3;
    }

    const textureCoords = new window[model.pointType](numberOfPoints * tcdim);
    const tcoords = vtkDataArray.newInstance({
      name: 'TextureCoordinates',
      values: textureCoords,
      numberOfComponents: tcdim,
    });
    polyData.getPointData().setTCoords(tcoords);

    const x = [0.0, 0.0, 0.0];
    const n = [0.0, 0.0, 0.0];
    const tc = [0.0, 0.0];

    let pointIndex = 0;

    x[0] = model.center[0] - model.xLength / 2.0;
    n[0] = -1.0;
    n[1] = 0.0;
    n[2] = 0.0;
    for (let i = 0; i < 2; i++) {
      x[1] = model.center[1] - model.yLength / 2.0;

      for (let j = 0; j < 2; j++) {
        tc[1] = x[1] + 0.5;
        x[2] = model.center[2] - model.zLength / 2.0;

        for (let k = 0; k < 2; k++) {
          tc[0] = (x[2] + 0.5) * (1 - 2 * i);
          points[pointIndex * 3] = x[0];
          points[pointIndex * 3 + 1] = x[1];
          points[pointIndex * 3 + 2] = x[2];

          normals[pointIndex * 3] = n[0];
          normals[pointIndex * 3 + 1] = n[1];
          normals[pointIndex * 3 + 2] = n[2];

          if (tcdim === 2) {
            textureCoords[pointIndex * tcdim] = tc[0];
            textureCoords[pointIndex * tcdim + 1] = tc[1];
          } else {
            textureCoords[pointIndex * tcdim] = 2 * i - 1;
            textureCoords[pointIndex * tcdim + 1] = 2 * j - 1;
            textureCoords[pointIndex * tcdim + 2] = 2 * k - 1;
          }

          pointIndex++;

          x[2] += model.zLength;
        }
        x[1] += model.yLength;
      }
      x[0] += model.xLength;
      n[0] += 2.0;
    }

    x[1] = model.center[1] - model.yLength / 2.0;
    n[1] = -1.0;
    n[0] = 0.0;
    n[2] = 0.0;
    for (let i = 0; i < 2; i++) {
      x[0] = model.center[0] - model.xLength / 2.0;

      for (let j = 0; j < 2; j++) {
        tc[0] = (x[0] + 0.5) * (2 * i - 1);
        x[2] = model.center[2] - model.zLength / 2.0;

        for (let k = 0; k < 2; k++) {
          tc[1] = (x[2] + 0.5) * -1;

          points[pointIndex * 3] = x[0];
          points[pointIndex * 3 + 1] = x[1];
          points[pointIndex * 3 + 2] = x[2];

          normals[pointIndex * 3] = n[0];
          normals[pointIndex * 3 + 1] = n[1];
          normals[pointIndex * 3 + 2] = n[2];

          if (tcdim === 2) {
            textureCoords[pointIndex * tcdim] = tc[0];
            textureCoords[pointIndex * tcdim + 1] = tc[1];
          } else {
            textureCoords[pointIndex * tcdim] = 2 * j - 1;
            textureCoords[pointIndex * tcdim + 1] = 2 * i - 1;
            textureCoords[pointIndex * tcdim + 2] = 2 * k - 1;
          }

          pointIndex++;
          x[2] += model.zLength;
        }
        x[0] += model.xLength;
      }
      x[1] += model.yLength;
      n[1] += 2.0;
    }

    x[2] = model.center[2] - model.zLength / 2.0;
    n[2] = -1.0;
    n[0] = 0.0;
    n[1] = 0.0;
    for (let i = 0; i < 2; i++) {
      x[1] = model.center[1] - model.yLength / 2.0;

      for (let j = 0; j < 2; j++) {
        tc[1] = x[1] + 0.5;
        x[0] = model.center[0] - model.xLength / 2.0;

        for (let k = 0; k < 2; k++) {
          tc[0] = (x[0] + 0.5) * (2 * i - 1);

          points[pointIndex * 3] = x[0];
          points[pointIndex * 3 + 1] = x[1];
          points[pointIndex * 3 + 2] = x[2];

          normals[pointIndex * 3] = n[0];
          normals[pointIndex * 3 + 1] = n[1];
          normals[pointIndex * 3 + 2] = n[2];

          if (tcdim === 2) {
            textureCoords[pointIndex * tcdim] = tc[0];
            textureCoords[pointIndex * tcdim + 1] = tc[1];
          } else {
            textureCoords[pointIndex * tcdim] = 2 * k - 1;
            textureCoords[pointIndex * tcdim + 1] = 2 * j - 1;
            textureCoords[pointIndex * tcdim + 2] = 2 * i - 1;
          }

          pointIndex++;
          x[0] += model.xLength;
        }
        x[1] += model.yLength;
      }
      x[2] += model.zLength;
      n[2] += 2.0;
    }

    // Apply rotation to the points coordinates and normals
    vtkMatrixBuilder
      .buildFromRadian()
      .rotateX(model.rotations[0])
      .rotateY(model.rotations[1])
      .rotateZ(model.rotations[2])
      .apply(points)
      .apply(normals);

    // Apply transformation to the points coordinates
    vtkMatrixBuilder
      .buildFromRadian()
      .translate(...model.center)
      .apply(points);

    // Define quads
    const polys = new window[model.pointType](numberOfPolys * 5);
    polyData.getPolys().setData(polys, 1);

    let polyIndex = 0;

    polys[polyIndex++] = 4;
    polys[polyIndex++] = 0;
    polys[polyIndex++] = 1;
    polys[polyIndex++] = 3;
    polys[polyIndex++] = 2;

    polys[polyIndex++] = 4;
    polys[polyIndex++] = 4;
    polys[polyIndex++] = 6;
    polys[polyIndex++] = 7;
    polys[polyIndex++] = 5;

    polys[polyIndex++] = 4;
    polys[polyIndex++] = 8;
    polys[polyIndex++] = 10;
    polys[polyIndex++] = 11;
    polys[polyIndex++] = 9;

    polys[polyIndex++] = 4;
    polys[polyIndex++] = 12;
    polys[polyIndex++] = 13;
    polys[polyIndex++] = 15;
    polys[polyIndex++] = 14;

    polys[polyIndex++] = 4;
    polys[polyIndex++] = 16;
    polys[polyIndex++] = 18;
    polys[polyIndex++] = 19;
    polys[polyIndex++] = 17;

    polys[polyIndex++] = 4;
    polys[polyIndex++] = 20;
    polys[polyIndex++] = 21;
    polys[polyIndex++] = 23;
    polys[polyIndex] = 22;
  }

  publicAPI.setBounds = (...bounds) => {
    let boundsArray = [];

    if (Array.isArray(bounds[0])) {
      boundsArray = bounds[0];
    } else {
      for (let i = 0; i < bounds.length; i++) {
        boundsArray.push(bounds[i]);
      }
    }

    if (boundsArray.length !== 6) {
      return;
    }

    model.xLength = boundsArray[1] - boundsArray[0];
    model.yLength = boundsArray[3] - boundsArray[2];
    model.zLength = boundsArray[5] - boundsArray[4];
    model.center = [
      (boundsArray[0] + boundsArray[1]) / 2.0,
      (boundsArray[2] + boundsArray[3]) / 2.0,
      (boundsArray[4] + boundsArray[5]) / 2.0,
    ];
  };

  // Expose methods
  publicAPI.requestData = requestData;
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  xLength: 1.0,
  yLength: 1.0,
  zLength: 1.0,
  center: [0.0, 0.0, 0.0],
  rotations: [0.0, 0.0, 0.0],
  pointType: 'Float32Array',
  generate3DTextureCoordinates: false,
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  // Build VTK API
  macro.obj(publicAPI, model);
  macro.setGet(publicAPI, model, [
    'xLength',
    'yLength',
    'zLength',
    'generate3DTextureCoordinates',
  ]);
  macro.setGetArray(publicAPI, model, ['center', 'rotations'], 3);

  macro.algo(publicAPI, model, 0, 1);
  vtkCubeSource(publicAPI, model);
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(extend, 'vtkCubeSource');

// ----------------------------------------------------------------------------

export default { newInstance, extend };
<commit_msg>fix(CubeSource): Change buildFromRadian to buildFromDegree for rotations<commit_after>import macro from 'vtk.js/Sources/macro';
import vtkDataArray from 'vtk.js/Sources/Common/Core/DataArray';
import vtkPolyData from 'vtk.js/Sources/Common/DataModel/PolyData';
import vtkMatrixBuilder from 'vtk.js/Sources/Common/Core/MatrixBuilder';

// ----------------------------------------------------------------------------
// vtkCubeSource methods
// ----------------------------------------------------------------------------

function vtkCubeSource(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkCubeSource');

  function requestData(inData, outData) {
    if (model.deleted) {
      return;
    }

    const polyData = vtkPolyData.newInstance();
    outData[0] = polyData;

    const numberOfPolys = 6;
    const numberOfPoints = 24;

    // Define points
    const points = new window[model.pointType](numberOfPoints * 3);
    polyData.getPoints().setData(points, 3);

    const normals = new window[model.pointType](numberOfPoints * 3);
    const normalArray = vtkDataArray.newInstance({
      name: 'Normals',
      values: normals,
      numberOfComponents: 3,
    });
    polyData.getPointData().setNormals(normalArray);

    let tcdim = 2;
    if (model.generate3DTextureCoordinates === true) {
      tcdim = 3;
    }

    const textureCoords = new window[model.pointType](numberOfPoints * tcdim);
    const tcoords = vtkDataArray.newInstance({
      name: 'TextureCoordinates',
      values: textureCoords,
      numberOfComponents: tcdim,
    });
    polyData.getPointData().setTCoords(tcoords);

    const x = [0.0, 0.0, 0.0];
    const n = [0.0, 0.0, 0.0];
    const tc = [0.0, 0.0];

    let pointIndex = 0;

    x[0] = model.center[0] - model.xLength / 2.0;
    n[0] = -1.0;
    n[1] = 0.0;
    n[2] = 0.0;
    for (let i = 0; i < 2; i++) {
      x[1] = model.center[1] - model.yLength / 2.0;

      for (let j = 0; j < 2; j++) {
        tc[1] = x[1] + 0.5;
        x[2] = model.center[2] - model.zLength / 2.0;

        for (let k = 0; k < 2; k++) {
          tc[0] = (x[2] + 0.5) * (1 - 2 * i);
          points[pointIndex * 3] = x[0];
          points[pointIndex * 3 + 1] = x[1];
          points[pointIndex * 3 + 2] = x[2];

          normals[pointIndex * 3] = n[0];
          normals[pointIndex * 3 + 1] = n[1];
          normals[pointIndex * 3 + 2] = n[2];

          if (tcdim === 2) {
            textureCoords[pointIndex * tcdim] = tc[0];
            textureCoords[pointIndex * tcdim + 1] = tc[1];
          } else {
            textureCoords[pointIndex * tcdim] = 2 * i - 1;
            textureCoords[pointIndex * tcdim + 1] = 2 * j - 1;
            textureCoords[pointIndex * tcdim + 2] = 2 * k - 1;
          }

          pointIndex++;

          x[2] += model.zLength;
        }
        x[1] += model.yLength;
      }
      x[0] += model.xLength;
      n[0] += 2.0;
    }

    x[1] = model.center[1] - model.yLength / 2.0;
    n[1] = -1.0;
    n[0] = 0.0;
    n[2] = 0.0;
    for (let i = 0; i < 2; i++) {
      x[0] = model.center[0] - model.xLength / 2.0;

      for (let j = 0; j < 2; j++) {
        tc[0] = (x[0] + 0.5) * (2 * i - 1);
        x[2] = model.center[2] - model.zLength / 2.0;

        for (let k = 0; k < 2; k++) {
          tc[1] = (x[2] + 0.5) * -1;

          points[pointIndex * 3] = x[0];
          points[pointIndex * 3 + 1] = x[1];
          points[pointIndex * 3 + 2] = x[2];

          normals[pointIndex * 3] = n[0];
          normals[pointIndex * 3 + 1] = n[1];
          normals[pointIndex * 3 + 2] = n[2];

          if (tcdim === 2) {
            textureCoords[pointIndex * tcdim] = tc[0];
            textureCoords[pointIndex * tcdim + 1] = tc[1];
          } else {
            textureCoords[pointIndex * tcdim] = 2 * j - 1;
            textureCoords[pointIndex * tcdim + 1] = 2 * i - 1;
            textureCoords[pointIndex * tcdim + 2] = 2 * k - 1;
          }

          pointIndex++;
          x[2] += model.zLength;
        }
        x[0] += model.xLength;
      }
      x[1] += model.yLength;
      n[1] += 2.0;
    }

    x[2] = model.center[2] - model.zLength / 2.0;
    n[2] = -1.0;
    n[0] = 0.0;
    n[1] = 0.0;
    for (let i = 0; i < 2; i++) {
      x[1] = model.center[1] - model.yLength / 2.0;

      for (let j = 0; j < 2; j++) {
        tc[1] = x[1] + 0.5;
        x[0] = model.center[0] - model.xLength / 2.0;

        for (let k = 0; k < 2; k++) {
          tc[0] = (x[0] + 0.5) * (2 * i - 1);

          points[pointIndex * 3] = x[0];
          points[pointIndex * 3 + 1] = x[1];
          points[pointIndex * 3 + 2] = x[2];

          normals[pointIndex * 3] = n[0];
          normals[pointIndex * 3 + 1] = n[1];
          normals[pointIndex * 3 + 2] = n[2];

          if (tcdim === 2) {
            textureCoords[pointIndex * tcdim] = tc[0];
            textureCoords[pointIndex * tcdim + 1] = tc[1];
          } else {
            textureCoords[pointIndex * tcdim] = 2 * k - 1;
            textureCoords[pointIndex * tcdim + 1] = 2 * j - 1;
            textureCoords[pointIndex * tcdim + 2] = 2 * i - 1;
          }

          pointIndex++;
          x[0] += model.xLength;
        }
        x[1] += model.yLength;
      }
      x[2] += model.zLength;
      n[2] += 2.0;
    }

    // Apply rotation to the points coordinates and normals
    vtkMatrixBuilder
      .buildFromDegree()
      .rotateX(model.rotations[0])
      .rotateY(model.rotations[1])
      .rotateZ(model.rotations[2])
      .apply(points)
      .apply(normals);

    // Apply transformation to the points coordinates
    vtkMatrixBuilder
      .buildFromRadian()
      .translate(...model.center)
      .apply(points);

    // Define quads
    const polys = new window[model.pointType](numberOfPolys * 5);
    polyData.getPolys().setData(polys, 1);

    let polyIndex = 0;

    polys[polyIndex++] = 4;
    polys[polyIndex++] = 0;
    polys[polyIndex++] = 1;
    polys[polyIndex++] = 3;
    polys[polyIndex++] = 2;

    polys[polyIndex++] = 4;
    polys[polyIndex++] = 4;
    polys[polyIndex++] = 6;
    polys[polyIndex++] = 7;
    polys[polyIndex++] = 5;

    polys[polyIndex++] = 4;
    polys[polyIndex++] = 8;
    polys[polyIndex++] = 10;
    polys[polyIndex++] = 11;
    polys[polyIndex++] = 9;

    polys[polyIndex++] = 4;
    polys[polyIndex++] = 12;
    polys[polyIndex++] = 13;
    polys[polyIndex++] = 15;
    polys[polyIndex++] = 14;

    polys[polyIndex++] = 4;
    polys[polyIndex++] = 16;
    polys[polyIndex++] = 18;
    polys[polyIndex++] = 19;
    polys[polyIndex++] = 17;

    polys[polyIndex++] = 4;
    polys[polyIndex++] = 20;
    polys[polyIndex++] = 21;
    polys[polyIndex++] = 23;
    polys[polyIndex] = 22;
  }

  publicAPI.setBounds = (...bounds) => {
    let boundsArray = [];

    if (Array.isArray(bounds[0])) {
      boundsArray = bounds[0];
    } else {
      for (let i = 0; i < bounds.length; i++) {
        boundsArray.push(bounds[i]);
      }
    }

    if (boundsArray.length !== 6) {
      return;
    }

    model.xLength = boundsArray[1] - boundsArray[0];
    model.yLength = boundsArray[3] - boundsArray[2];
    model.zLength = boundsArray[5] - boundsArray[4];
    model.center = [
      (boundsArray[0] + boundsArray[1]) / 2.0,
      (boundsArray[2] + boundsArray[3]) / 2.0,
      (boundsArray[4] + boundsArray[5]) / 2.0,
    ];
  };

  // Expose methods
  publicAPI.requestData = requestData;
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  xLength: 1.0,
  yLength: 1.0,
  zLength: 1.0,
  center: [0.0, 0.0, 0.0],
  rotations: [0.0, 0.0, 0.0],
  pointType: 'Float32Array',
  generate3DTextureCoordinates: false,
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  // Build VTK API
  macro.obj(publicAPI, model);
  macro.setGet(publicAPI, model, [
    'xLength',
    'yLength',
    'zLength',
    'generate3DTextureCoordinates',
  ]);
  macro.setGetArray(publicAPI, model, ['center', 'rotations'], 3);

  macro.algo(publicAPI, model, 0, 1);
  vtkCubeSource(publicAPI, model);
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(extend, 'vtkCubeSource');

// ----------------------------------------------------------------------------

export default { newInstance, extend };
<|endoftext|>


<commit_before>function chartDrawer()
{
  if($("#chartdiv").length == 1){highChart();}
}

/**
 * Synchronize zooming through the setExtremes event handler.
 */
function syncExtremes(e) {
  var thisChart = this.chart;

  if (e.trigger !== 'syncExtremes') { // Prevent feedback loop
    Highcharts.each(Highcharts.charts, function (chart) {
      if (chart !== thisChart) {
        if (chart.xAxis[0].setExtremes) { // It is null while updating
          chart.xAxis[0].setExtremes(
            e.min,
            e.max,
            undefined,
            false,
            { trigger: 'syncExtremes' }
          );
        }
      }
    });
  }
}

function highChart()
{
/*
The purpose of this demo is to demonstrate how multiple charts on the same page
can be linked through DOM and Highcharts events and API methods. It takes a
standard Highcharts config with a small variation for each data set, and a
mouse/touch event handler to bind the charts together.
*/

/**
 * In order to synchronize tooltips and crosshairs, override the
 * built-in events with handlers defined on the parent element.
 */
['mousemove', 'touchmove', 'touchstart'].forEach(function (eventType) {
  document.getElementById('chartdiv').addEventListener(
    eventType,
    function (e) {
      var chart,
        point,
        i,
        event;

      for (i = 0; i < Highcharts.charts.length; i = i + 1) {
        chart = Highcharts.charts[i];
        // Find coordinates within the chart
        event = chart.pointer.normalize(e);
        // Get the hovered point
        point = chart.series[0].searchPoint(event, true);

        if (point) {
          point.highlight(e);
        }
      }
    }
  );
});

/**
 * Override the reset function, we don't need to hide the tooltips and
 * crosshairs.
 */
Highcharts.Pointer.prototype.reset = function () {
  return undefined;
};

/**
 * Highlight a point by showing tooltip, setting hover state and draw crosshair
 */
Highcharts.Point.prototype.highlight = function (event) {
  event = this.series.chart.pointer.normalize(event);
  this.onMouseOver(); // Show the hover marker
  this.series.chart.tooltip.refresh(this); // Show the tooltip
  this.series.chart.xAxis[0].drawCrosshair(event, this); // Show the crosshair
};

// Get the data. The contents of the data file can be viewed at
Highcharts.ajax({
  url: '{{url.this}}/report?ajaxreport=json',
  dataType: 'text',
  success: function (activity) {

    activity = JSON.parse(activity);
    activity.datasets.forEach(function (dataset, i) {

      // Add X values
      dataset.data = Highcharts.map(dataset.data, function (val, j) {
        return [activity.xData[j], val];
      });

      var chartDiv = document.createElement('div');
      chartDiv.className = 'chart';
      document.getElementById('chartdiv').appendChild(chartDiv);

      Highcharts.chart(chartDiv, {
        chart: {
          marginLeft: 40, // Keep all charts left aligned
          spacingTop: 20,
          spacingBottom: 20,
          zoomType: 'x',
          style: {
            fontFamily: 'IRANSans, Tahoma, sans-serif'
          }
        },
        title: {
          text: dataset.name,
          align: 'left',
          margin: 0,
          x: 30
        },
        credits: {
          enabled: false
        },
        exporting: {
          enabled: false
        },
        legend: {
          enabled: false
        },
        xAxis: {
          crosshair: true,
          events: {
            setExtremes: syncExtremes
          },
          labels: {
            format: '{value}'
          }
        },
        yAxis: {
          title: {
            text: null
          }
        },
        tooltip: {
          positioner: function () {
            return {
              // right aligned
              x: this.chart.chartWidth - this.label.width,
              y: 10 // align to title
            };
          },
          borderWidth: 0,
          backgroundColor: 'none',
          pointFormat: '{point.y}',
          headerFormat: '',
          shadow: false,
          style: {
            fontSize: '18px'
          },
          valueDecimals: dataset.valueDecimals
        },
        series: [{
          data: dataset.data,
          name: dataset.name,
          type: dataset.type,
          color: Highcharts.getOptions().colors[i],
          fillOpacity: 0.3,
          tooltip: {
            valueSuffix: ' ' + dataset.unit
          }
        }]
      });
    });
  }
});

}<commit_msg>fix decimal of support chart<commit_after>function chartDrawer()
{
  if($("#chartdiv").length == 1){highChart();}
}

/**
 * Synchronize zooming through the setExtremes event handler.
 */
function syncExtremes(e) {
  var thisChart = this.chart;

  if (e.trigger !== 'syncExtremes') { // Prevent feedback loop
    Highcharts.each(Highcharts.charts, function (chart) {
      if (chart !== thisChart) {
        if (chart.xAxis[0].setExtremes) { // It is null while updating
          chart.xAxis[0].setExtremes(
            e.min,
            e.max,
            undefined,
            false,
            { trigger: 'syncExtremes' }
          );
        }
      }
    });
  }
}

function highChart()
{
/*
The purpose of this demo is to demonstrate how multiple charts on the same page
can be linked through DOM and Highcharts events and API methods. It takes a
standard Highcharts config with a small variation for each data set, and a
mouse/touch event handler to bind the charts together.
*/

/**
 * In order to synchronize tooltips and crosshairs, override the
 * built-in events with handlers defined on the parent element.
 */
['mousemove', 'touchmove', 'touchstart'].forEach(function (eventType) {
  document.getElementById('chartdiv').addEventListener(
    eventType,
    function (e) {
      var chart,
        point,
        i,
        event;

      for (i = 0; i < Highcharts.charts.length; i = i + 1) {
        chart = Highcharts.charts[i];
        // Find coordinates within the chart
        event = chart.pointer.normalize(e);
        // Get the hovered point
        point = chart.series[0].searchPoint(event, true);

        if (point) {
          point.highlight(e);
        }
      }
    }
  );
});

/**
 * Override the reset function, we don't need to hide the tooltips and
 * crosshairs.
 */
Highcharts.Pointer.prototype.reset = function () {
  return undefined;
};

/**
 * Highlight a point by showing tooltip, setting hover state and draw crosshair
 */
Highcharts.Point.prototype.highlight = function (event) {
  event = this.series.chart.pointer.normalize(event);
  this.onMouseOver(); // Show the hover marker
  this.series.chart.tooltip.refresh(this); // Show the tooltip
  this.series.chart.xAxis[0].drawCrosshair(event, this); // Show the crosshair
};

// Get the data. The contents of the data file can be viewed at
Highcharts.ajax({
  url: '{{url.this}}/report?ajaxreport=json',
  dataType: 'text',
  success: function (activity) {

    activity = JSON.parse(activity);
    activity.datasets.forEach(function (dataset, i) {

      // Add X values
      dataset.data = Highcharts.map(dataset.data, function (val, j) {
        return [activity.xData[j], val];
      });

      var chartDiv = document.createElement('div');
      chartDiv.className = 'chart';
      document.getElementById('chartdiv').appendChild(chartDiv);

      Highcharts.chart(chartDiv, {
        chart: {
          marginLeft: 40, // Keep all charts left aligned
          spacingTop: 20,
          spacingBottom: 20,
          zoomType: 'x',
          style: {
            fontFamily: 'IRANSans, Tahoma, sans-serif'
          }
        },
        title: {
          text: dataset.name,
          align: 'left',
          margin: 0,
          x: 30
        },
        credits: {
          enabled: false
        },
        exporting: {
          enabled: false
        },
        legend: {
          enabled: false
        },
        xAxis: {
          crosshair: true,
          events: {
            setExtremes: syncExtremes
          },
          labels: {
            format: '{value}'
          }
        },
        yAxis: {
          allowDecimals: false,
          title: {
            text: null
          }
        },
        tooltip: {
          positioner: function () {
            return {
              // right aligned
              x: this.chart.chartWidth - this.label.width,
              y: 10 // align to title
            };
          },
          borderWidth: 0,
          backgroundColor: 'none',
          pointFormat: '{point.y}',
          headerFormat: '',
          shadow: false,
          style: {
            fontSize: '18px'
          },
          valueDecimals: dataset.valueDecimals
        },
        series: [{
          data: dataset.data,
          name: dataset.name,
          type: dataset.type,
          color: Highcharts.getOptions().colors[i],
          fillOpacity: 0.3,
          tooltip: {
            valueSuffix: ' ' + dataset.unit
          }
        }]
      });
    });
  }
});

}<|endoftext|>


<commit_before>'use strict';

var chai = require('chai');
var expect = chai.expect;
var express = require('express');
var app = express();
var http = require('http');
var entityRouter = require('../../').entities.entityRouter;

describe('back4app-rest entityRouter', function () {
  var server;

  after(function () {
    server.close();
  });

  it('should create a router', function (done) {
    var router = entityRouter({
      test: {
        Entity: {name: 'test'}
      }
    }, 'DummyToken');

    app.use('/api', router);

    server = app.listen(3000, function () {
      var port = server.address().port;
      expect(port).to.equal(3000);
      yo();
    });

    function yo() {
      var req = http.request({
        host: 'localhost',
        port: '3000',
        path: '/api/test',
        method: 'GET'
      }, function (response) {
        expect(response.statusCode).to.equal(200);
        var body = '';
        response.on('data', function (d) { body += d; });
        response.on('end', function () {
          var responseObj = JSON.parse(body);
          expect(responseObj.name).to.equal('test');
          done();
        });
      });
      req.end();
    }

  });
});
<commit_msg>Fixes the test, removing temporary function.<commit_after>'use strict';

var chai = require('chai');
var expect = chai.expect;
var express = require('express');
var app = express();
var http = require('http');
var entityRouter = require('../../').entities.entityRouter;

describe('back4app-rest entityRouter', function () {
  var server;

  before(function (done) {
    server = app.listen(3000, function () {
      var port = server.address().port;
      expect(port).to.equal(3000);
      done();
    });
  });

  after(function () {
    server.close();
  });

  it('should create a router', function (done) {
    var router = entityRouter({
      test: {
        Entity: {name: 'test'}
      }
    }, 'DummyToken');

    app.use('/api', router);

    var req = http.request({
      host: 'localhost',
      port: '3000',
      path: '/api/test',
      method: 'GET'
    }, function (response) {
      expect(response.statusCode).to.equal(200);
      var body = '';
      response.on('data', function (d) { body += d; });
      response.on('end', function () {
        var responseObj = JSON.parse(body);
        expect(responseObj.name).to.equal('test');
        done();
      });
    });
    req.end();

  });
});
<|endoftext|>


<commit_before>import { test, SYNTAX_CASES } from '../utils'
import { RuleTester } from 'eslint'

const ruleTester = new RuleTester()
    , rule = require('rules/no-named-default')

ruleTester.run('no-named-default', rule, {
  valid: [
    test({code: 'import bar from "./bar";'}),
    test({code: 'import bar, { foo } from "./bar";'}),

    ...SYNTAX_CASES,
  ],

  invalid: [
    test({
      code: 'import { default } from "./bar";',
      errors: [{
        message: 'Use default import syntax to import \'default\'.',
        type: 'Identifier',
      }],
      parser: 'babel-eslint',
    }),
    test({
      code: 'import { default as bar } from "./bar";',
      errors: [{
        message: 'Use default import syntax to import \'bar\'.',
        type: 'Identifier',
      }],
    }),
    test({
      code: 'import { foo, default as bar } from "./bar";',
      errors: [{
        message: 'Use default import syntax to import \'bar\'.',
        type: 'Identifier',
      }],
    }),
  ],
})
<commit_msg>[Tests] comment out failing (and probably invalid) test<commit_after>import { test, SYNTAX_CASES } from '../utils'
import { RuleTester } from 'eslint'

const ruleTester = new RuleTester()
    , rule = require('rules/no-named-default')

ruleTester.run('no-named-default', rule, {
  valid: [
    test({code: 'import bar from "./bar";'}),
    test({code: 'import bar, { foo } from "./bar";'}),

    ...SYNTAX_CASES,
  ],

  invalid: [
    /*test({
      code: 'import { default } from "./bar";',
      errors: [{
        message: 'Use default import syntax to import \'default\'.',
        type: 'Identifier',
      }],
      parser: 'babel-eslint',
    }),*/
    test({
      code: 'import { default as bar } from "./bar";',
      errors: [{
        message: 'Use default import syntax to import \'bar\'.',
        type: 'Identifier',
      }],
    }),
    test({
      code: 'import { foo, default as bar } from "./bar";',
      errors: [{
        message: 'Use default import syntax to import \'bar\'.',
        type: 'Identifier',
      }],
    }),
  ],
})
<|endoftext|>


<commit_before>
    angular
        .module('openeApp.tasks.common')
        .controller('baseTaskController', BaseTaskController);

    function BaseTaskController(taskService, $stateParams, $location, documentPreviewService, sessionService, workflowService, $translate, $mdDialog, $mdToast) {
        var vm = this;
        vm.taskId = $stateParams.taskId;
        vm.init = init;
        vm.updateTask = updateTask;
        vm.taskDone = taskDone;
        vm.approve = approve;
        vm.reject = reject;
        vm.endTask = endTask;
        vm.backToTasks = backToTasks;
        vm.changeStatus = changeStatus;
        vm.previewDocument = previewDocument;
        vm.deleteWorkflow = deleteWorkflow;
        vm.documentNodeRefToOpen = documentNodeRefToOpen;
        vm.statuses = ["Not Yet Started", "In Progres", "On Hold"];
        vm.toggleStatus = {item: -1};
        vm.isAdmin = sessionService.isAdmin();

        function init(){
            var vm = this;
            return taskService.getTaskDetails(vm.taskId).then(function(result){
                console.log("task", result);
                vm.task = result;
                vm.taskProperties = angular.extend({}, result.properties);
            });
        }

        function updateTask(){
            var vm = this;
            taskService.updateTask(vm.taskId, vm.task.properties).then(function(response){
                vm.backToTasks();
            });
        }

        function deleteWorkflow(task) {
            var vm = this;
            var confirm = $mdDialog.confirm()
                .title($translate.instant('COMMON.CONFIRM'))
                .content($translate.instant('WORKFLOW.ARE_YOU_SURE_YOU_WANT_TO_DELETE_THE_TASK_AND_WORKFLOW', {task_description: task.properties.bpm_description}))
                .ariaLabel('')
                .targetEvent(null)
                .ok($translate.instant('COMMON.YES'))
                .cancel($translate.instant('COMMON.CANCEL'));
            $mdDialog.show(confirm).then(function() {
                workflowService.deleteWorkflow(task.workflowInstance.id).then(function(result){
                    vm.backToTasks();
                });
            });

        };

        function taskDone(){
            var vm = this;
            taskService.updateTask(vm.taskId, vm.task.properties).then(function(response){
                vm.endTask($translate.instant('TASK.TASK_DONE'));
            });
        }

        /**
         *   Uses vm.reviewOutcomeProperty as review outcome property name.
         *   Uses vm.reviewOutcomeApprove as review approval outcome value.
         */
        function approve(){
            var vm = this;
            var props = angular.copy(vm.task.properties);
            props[vm.reviewOutcomeProperty] = vm.reviewOutcomeApprove;
            taskService.updateTask(vm.taskId, props).then(function(response){
                vm.endTask($translate.instant('TASK.TASK_APPROVED'));
            });
        }

        /**
         * Uses vm.reviewOutcomeReject as review reject outcome value.
         */
        function reject(){
            var vm = this;
            var props = angular.copy(vm.task.properties);
            props[vm.reviewOutcomeProperty] = vm.reviewOutcomeReject;
            taskService.updateTask(vm.taskId, props).then(function(response){
                vm.endTask($translate.instant('TASK.TASK_REJECTED'));
            });
        }

        function endTask(msg){
            $mdToast.showSimple(msg);
            taskService.endTask(vm.taskId).then(function(response){
                vm.backToTasks();
            });
        }

        function backToTasks(){
            $location.path('/tasks');
        }

        function changeStatus(idx){
            var vm = this;
            vm.toggleStatus.item = idx;
            vm.task.properties.bpm_status = vm.statuses[idx];
            taskService.updateTask(vm.taskId, vm.task.properties).then(function(response){
                // console.log('Task status updated');
            });
        }

        function previewDocument(item){
            var nodeRef = item.nodeRef;
            if(item.mainDocNodeRef != undefined && item.mainDocNodeRef != null){
                nodeRef = item.mainDocNodeRef;
            }
            documentPreviewService.previewDocument(nodeRef);
        }

        function documentNodeRefToOpen(item){
            if(item.docRecordNodeRef != undefined && item.docRecordNodeRef != null){
                return item.docRecordNodeRef;
            }
            return item.nodeRef;
        }
    }
<commit_msg>OPENE-337 Returning back the "task.cancel" controller methods to be able to close tasks with no effects.<commit_after>
    angular
        .module('openeApp.tasks.common')
        .controller('baseTaskController', BaseTaskController);

    function BaseTaskController(taskService, $stateParams, $location, documentPreviewService, sessionService, workflowService, $translate, $mdDialog, $mdToast) {
        var vm = this;
        vm.taskId = $stateParams.taskId;
        vm.init = init;
        vm.updateTask = updateTask;
        vm.cancel = cancel;
        vm.taskDone = taskDone;
        vm.approve = approve;
        vm.reject = reject;
        vm.endTask = endTask;
        vm.backToTasks = backToTasks;
        vm.changeStatus = changeStatus;
        vm.previewDocument = previewDocument;
        vm.deleteWorkflow = deleteWorkflow;
        vm.documentNodeRefToOpen = documentNodeRefToOpen;
        vm.statuses = ["Not Yet Started", "In Progres", "On Hold"];
        vm.toggleStatus = {item: -1};
        vm.isAdmin = sessionService.isAdmin();

        function init(){
            var vm = this;
            return taskService.getTaskDetails(vm.taskId).then(function(result){
                console.log("task", result);
                vm.task = result;
                vm.taskProperties = angular.extend({}, result.properties);
            });
        }

        function cancel(){
            this.backToTasks();
        }

        function updateTask(){
            var vm = this;
            taskService.updateTask(vm.taskId, vm.task.properties).then(function(response){
                vm.backToTasks();
            });
        }

        function deleteWorkflow(task) {
            var vm = this;
            var confirm = $mdDialog.confirm()
                .title($translate.instant('COMMON.CONFIRM'))
                .content($translate.instant('WORKFLOW.ARE_YOU_SURE_YOU_WANT_TO_DELETE_THE_TASK_AND_WORKFLOW', {task_description: task.properties.bpm_description}))
                .ariaLabel('')
                .targetEvent(null)
                .ok($translate.instant('COMMON.YES'))
                .cancel($translate.instant('COMMON.CANCEL'));
            $mdDialog.show(confirm).then(function() {
                workflowService.deleteWorkflow(task.workflowInstance.id).then(function(result){
                    vm.backToTasks();
                });
            });

        };

        function taskDone(){
            var vm = this;
            taskService.updateTask(vm.taskId, vm.task.properties).then(function(response){
                vm.endTask($translate.instant('TASK.TASK_DONE'));
            });
        }

        /**
         *   Uses vm.reviewOutcomeProperty as review outcome property name.
         *   Uses vm.reviewOutcomeApprove as review approval outcome value.
         */
        function approve(){
            var vm = this;
            var props = angular.copy(vm.task.properties);
            props[vm.reviewOutcomeProperty] = vm.reviewOutcomeApprove;
            taskService.updateTask(vm.taskId, props).then(function(response){
                vm.endTask($translate.instant('TASK.TASK_APPROVED'));
            });
        }

        /**
         * Uses vm.reviewOutcomeReject as review reject outcome value.
         */
        function reject(){
            var vm = this;
            var props = angular.copy(vm.task.properties);
            props[vm.reviewOutcomeProperty] = vm.reviewOutcomeReject;
            taskService.updateTask(vm.taskId, props).then(function(response){
                vm.endTask($translate.instant('TASK.TASK_REJECTED'));
            });
        }

        function endTask(msg){
            $mdToast.showSimple(msg);
            taskService.endTask(vm.taskId).then(function(response){
                vm.backToTasks();
            });
        }

        function backToTasks(){
            $location.path('/tasks');
        }

        function changeStatus(idx){
            var vm = this;
            vm.toggleStatus.item = idx;
            vm.task.properties.bpm_status = vm.statuses[idx];
            taskService.updateTask(vm.taskId, vm.task.properties).then(function(response){
                // console.log('Task status updated');
            });
        }

        function previewDocument(item){
            var nodeRef = item.nodeRef;
            if(item.mainDocNodeRef != undefined && item.mainDocNodeRef != null){
                nodeRef = item.mainDocNodeRef;
            }
            documentPreviewService.previewDocument(nodeRef);
        }

        function documentNodeRefToOpen(item){
            if(item.docRecordNodeRef != undefined && item.docRecordNodeRef != null){
                return item.docRecordNodeRef;
            }
            return item.nodeRef;
        }
    }
<|endoftext|>


<commit_before>(function() {
    angular
        .module("bibframeEditor")
        .directive("scribePopover", ["$q", "$timeout", "$document", "$position", "Resolver", ScribePopoverDirective]);

    function ScribePopoverDirective($q, $timeout, $document, $position, Resolver) {
        function resolve(uri) {
            var deferred = $q.defer();
            Resolver.resolve({"uri": uri}).$promise.then(function(data) {
                deferred.resolve(data.raw);
            }).catch(function(data) {
                deferred.reject("No additional data could be found.");
            });
            return deferred.promise;
        }

        function getAttr(attrs, name) {
            var prefix = "scribePopover";
            if (angular.isDefined(attrs[prefix + name])) {
                return attrs[prefix + name];
            } else {
                return null;
            }
        }

        return {
            restrict: "A",
            link: function(scope, el, atts) {
                var delay, trigger, cancel, to, tt, ttClick, docClick, docType, show, stop, destroy;

                delay = parseInt(getAttr(atts, "Delay"), 10);
                trigger = getAttr(atts, "Trigger");
                cancel = getAttr(atts, "Cancel");
                to = null;

                show = function() {
                    if (!to) {
                        to = $timeout(function() {
                            resolve(getAttr(atts, "Resource")).then(function(h) {
                                var esc, pos;
                                $document.triggerHandler("scribePopoverOpened");
                                esc = h.replace(/</g,"<").replace(/>/g,">");
                                tt = angular.element('

<' + getAttr(atts, "Resource") + '>

' + esc + '

');
                                $document.find("body").append(tt);
                                tt.css({ top: 0, left: 0, display: "block" });
                                pos = $position.positionElements(el, tt, "right", true);
                                pos.top += "px";
                                pos.left += "px";
                                tt.css(pos);
                                // do not destroy if tt clicked directly
                                ttClick = tt.on("click", function(evt) {
                                    evt.stopPropagation();
                                });
                            });
                        }, delay, false);
                    }
                };

                stop = function() {
                    if (to) {
                        $timeout.cancel(to);
                        to = null;
                    }
                };

                destroy = function() {
                    if (tt) {
                        tt.unbind("click", ttClick);
                        $document.unbind("click", docClick);
                        $document.unbind("keypress", docType);
                        tt.remove();
                        tt = null
                    }
                };

                if (trigger !== null) {
                    el.bind(trigger, show);
                }

                if (cancel !== null) {
                    el.bind(cancel, stop);
                }

                /**
                 * Remove popover on:
                 *  autocomplete change (cancel, changing query)
                 */
                docClick = $document.on("click", destroy);
                docType = $document.on("keypress", destroy);
                $document.on("scribePopoverOpened", destroy);
            }
        };
    }
})();
<commit_msg>note to maybe extract html for a template instead<commit_after>(function() {
    angular
        .module("bibframeEditor")
        .directive("scribePopover", ["$q", "$timeout", "$document", "$position", "Resolver", ScribePopoverDirective]);

    function ScribePopoverDirective($q, $timeout, $document, $position, Resolver) {
        function resolve(uri) {
            var deferred = $q.defer();
            Resolver.resolve({"uri": uri}).$promise.then(function(data) {
                deferred.resolve(data.raw);
            }).catch(function(data) {
                deferred.reject("No additional data could be found.");
            });
            return deferred.promise;
        }

        function getAttr(attrs, name) {
            var prefix = "scribePopover";
            if (angular.isDefined(attrs[prefix + name])) {
                return attrs[prefix + name];
            } else {
                return null;
            }
        }

        return {
            restrict: "A",
            link: function(scope, el, atts) {
                var delay, trigger, cancel, to, tt, ttClick, docClick, docType, show, stop, destroy;

                delay = parseInt(getAttr(atts, "Delay"), 10);
                trigger = getAttr(atts, "Trigger");
                cancel = getAttr(atts, "Cancel");
                to = null;

                show = function() {
                    if (!to) {
                        to = $timeout(function() {
                            resolve(getAttr(atts, "Resource")).then(function(h) {
                                var esc, pos;
                                $document.triggerHandler("scribePopoverOpened");
                                esc = h.replace(/</g,"<").replace(/>/g,">");
                                // @@@ make this a template?
                                tt = angular.element('

<' + getAttr(atts, "Resource") + '>

' + esc + '

');
                                $document.find("body").append(tt);
                                tt.css({ top: 0, left: 0, display: "block" });
                                pos = $position.positionElements(el, tt, "right", true);
                                pos.top += "px";
                                pos.left += "px";
                                tt.css(pos);
                                // do not destroy if tt clicked directly
                                ttClick = tt.on("click", function(evt) {
                                    evt.stopPropagation();
                                });
                            });
                        }, delay, false);
                    }
                };

                stop = function() {
                    if (to) {
                        $timeout.cancel(to);
                        to = null;
                    }
                };

                destroy = function() {
                    if (tt) {
                        tt.unbind("click", ttClick);
                        $document.unbind("click", docClick);
                        $document.unbind("keypress", docType);
                        tt.remove();
                        tt = null
                    }
                };

                if (trigger !== null) {
                    el.bind(trigger, show);
                }

                if (cancel !== null) {
                    el.bind(cancel, stop);
                }

                /**
                 * Remove popover on:
                 *  autocomplete change (cancel, changing query)
                 */
                docClick = $document.on("click", destroy);
                docType = $document.on("keypress", destroy);
                $document.on("scribePopoverOpened", destroy);
            }
        };
    }
})();
<|endoftext|>


<commit_before>"use strict";

/*
  Copyright 2014 Google Inc. All rights reserved.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

String.prototype.format = function() {
    var str = this;
    for (var i = 0; i < arguments.length; i++)
        str = str.replace(new RegExp('_|-'+i+'-|_', 'gi'), arguments[i]);
    return str;
};

function requestURL(url,method,data,headerParams,responseType){
	return new Promise( function(resolve,reject){
		var oReq = new XMLHttpRequest();
		oReq.open(method, url, true);
		for(var param in headerParams)
			oReq.setRequestHeader(param, headerParams[param]);
		oReq.responseType = responseType;
		oReq.onload = function (oEvent) {
			if(oReq.status == 200)
				resolve(oReq.response);
			else
				reject(oReq.status+' '+oReq.statusText);
		};
		oReq.onerror = function() {
  			reject(Error("Network Error"));
		};
		oReq.send(data);
	});
}

var CHAR_ARRAY = [ 97,98,99];
var FILENAME = 'my.ttf';

function determineCharacters(){
	return new Promise(function(resolve,reject){
		resolve(CHAR_ARRAY);
	});
}

function requestCharacters(chars){
	return requestURL('/incremental_fonts/request','POST',JSON.stringify({'font':'noto','arr':chars}),{'Content-Type':'application/json'},'arraybuffer');
}

function requestQuota(size){
	return new Promise(function(resolve,reject){
		navigator.webkitPersistentStorage.requestQuota(size + size/3,
			function(grantedSize) {
				resolve(grantedSize);
			},
			reject
		);
	});
}

function setTheFont(font_src){
	var f = new FontFace("myfont", "url('"+font_src+"'')", {});
	document.fonts.add(f);
}

function requestTemporaryFileSystem(grantedSize){
	window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;
	return new Promise(function(resolve,reject){
		window.requestFileSystem(window.TEMPORARY, grantedSize, resolve , reject);
	});
}

function requestPersistentFileSystem(grantedSize){
	window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;
	return new Promise(function(resolve,reject){
		window.requestFileSystem(window.PERSISTENT, grantedSize, function(fs) {resolve(fs); } , reject);
	});
}

function requestBaseFont(name){
	return requestURL('/incremental_fonts/base?font='+name,'GET',null,{},'arraybuffer');
}

function sanitizeBaseFont(baseFont){
    var fontObj = parseFont(baseFont);
    var fontParser = new Parser(new DataView(baseFont),0);
    var glyphOffset =  fontObj.glyfOffset;
    for(var i=1;i<fontObj.numGlyphs;i+=1)
    {
      fontParser.writeShortByOffset(glyphOffset+fontObj.loca[i],-1);
    }
    return baseFont;
}

function createTheFile(filename){
	return new Promise(function(resolve,reject){
		fs.root.getFile(filename,{create:true},function(fe){ resolve(fe)},reject);
	});
}

function createFileWriter(fileEntry){
	return new Promise(function(resolve,reject){
		fileEntry.createWriter(function(fw){ resolve(fw);}
			,reject)
	});
}

function getFileEntry(fs,filename){
	return new Promise(function(resolve,reject){
		fs.root.getFile(filename,{create:true},
			function(fileEntry){resolve(fileEntry)},
			reject);
	});
}

function getFileObj(fileEntry){
	return new Promise(function(resolve,reject){
		fileEntry.file(function(file){ resolve(file) },reject);
	});
}

function readFileAsArrayBuffer(file){
	return new Promise(function(resolve,reject){
		var reader = new FileReader();
		reader.onloadend = function(e){resolve(e.target.result)};
		reader.onerror = reject;
		reader.readAsArrayBuffer(file);
	});
}

function getFileWriter(fs,filename){
	return getFileEntry(fs,filename).then(createFileWriter);
}

function injectCharacters(baseFont,glyphData){
    var glyphParser = new Parser(new DataView(glyphData),0);
    console.log('bundle size:'+glyphData.byteLength);
    console.log('baseFont size:'+baseFont.byteLength);
    var fontParser = new Parser(new DataView(baseFont),0);
    var fontObj = parseFont(baseFont);
    var count = glyphParser.parseUShort();
    var flag_mtx = glyphParser.parseByte();
    var glyphOffset=  fontObj.glyfOffset;
    console.log('glyfOff2: '+glyphOffset);
    console.log('count'+count);
    for(var i=0;i<count;i+=1)
    {
       var id = glyphParser.parseUShort();
       var hmtx,vmtx;
       if(flag_mtx & 1){
           hmtx = glyphParser.parseUShort();
           fontObj.metrics[id][1] = hmtx
       }
       if(flag_mtx & 2){
          vmtx = glyphParser.parseUShort();
       }
       var offset = glyphParser.parseULong();
       var length = glyphParser.parseUShort();
       console.log('id:'+id+' off:'+offset+' len:'+length);
       var bytes = glyphParser.parseBytes(length);
       fontParser.setBytes(glyphOffset+offset,bytes);
    }
    if(flag_mtx & 1)
        fontParser.writeHmtx(fontObj);
    console.log('injection is done!');
    return baseFont;
}

var formatFontFace = "\
     @font-face {\
        font-family: 'myfont';\
        src: url('_|-0-|_') format('truetype');\
      }"

function createCSSText(fileURL){
	return formatFontFace.format(fileURL+'?t='+Date.now());
}

function getFileAsArrayBuffer(fs,filename){
	return getFileEntry(fs,filename).then(getFileObj).then(readFileAsArrayBuffer);
}

function writeToTheFile(baseFont,contentType,fileWriter){
	return new Promise(function(resolve,reject){
		fileWriter.onwriteend = function(e) { resolve(e); };
		fileWriter.onerror = function(e) {  reject(e)};
        fileWriter.write(new Blob([baseFont],{type:contentType}));
    });
}

function persistToTheFilesystem(fs,filename,content,type){
	return getFileWriter(fs,filename).then(function(fw){
		return writeToTheFile(content,type,fw);
	});
}

function updateFont()
{

	var baseSanitized = requestBaseFont('noto').then(sanitizeBaseFont);

	var fileSystemReady = requestTemporaryFileSystem(32 * 1024);//requestQuota( 32 * 1024).then(requestPersistentFileSystem);

	var baseFontPersisted = Promise.all([baseSanitized , fileSystemReady]).then(
		function(results){
			return persistToTheFilesystem(results[1],FILENAME,results[0],'application/octet-binary');
		}
	);

	var bundleReady = determineCharacters().then(requestCharacters);

	var charsInjected = Promise.all([baseFontPersisted,bundleReady,fileSystemReady]).then(
		function(results){
			return getFileAsArrayBuffer(results[2],FILENAME).then(
				function(baseFont){
					return injectCharacters(baseFont,results[1]);
				}
			);
		}
	);

	var fileURLReady = fileSystemReady.then(function(fs){ return getFileEntry(fs,FILENAME)})
									  .then(function(fe){ return fe.toURL() });

	var fileUpdated = Promise.all([charsInjected,fileSystemReady]).then(
		function(results){
			return persistToTheFilesystem(results[1],FILENAME,results[0],'application/octet-binary');
		}
	);

	/*var styleSheetReady = Promise.all([fileSystemReady,fileURLReady.then(createCSSText)]).then(function(results){
		return persistToTheFilesystem(results[0],'my_font.css',results[1],'text/css')
	});*/

	Promise.all([fileUpdated,fileURLReady]).then(
		function(results){
			setTheFont(results[1]);
		}
	);

}
<commit_msg>Fixed font loading in JS<commit_after>"use strict";

/*
  Copyright 2014 Google Inc. All rights reserved.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

String.prototype.format = function() {
    var str = this;
    for (var i = 0; i < arguments.length; i++)
        str = str.replace(new RegExp('_|-'+i+'-|_', 'gi'), arguments[i]);
    return str;
};

function requestURL(url,method,data,headerParams,responseType){
	return new Promise( function(resolve,reject){
		var oReq = new XMLHttpRequest();
		oReq.open(method, url, true);
		for(var param in headerParams)
			oReq.setRequestHeader(param, headerParams[param]);
		oReq.responseType = responseType;
		oReq.onload = function (oEvent) {
			if(oReq.status == 200)
				resolve(oReq.response);
			else
				reject(oReq.status+' '+oReq.statusText);
		};
		oReq.onerror = function() {
  			reject(Error("Network Error"));
		};
		oReq.send(data);
	});
}

var CHAR_ARRAY = [ 97,98,231];
var FILENAME = 'my.ttf';

function determineCharacters(){
	return new Promise(function(resolve,reject){
		resolve(CHAR_ARRAY);
	});
}

function requestCharacters(chars){
	return requestURL('/incremental_fonts/request','POST',JSON.stringify({'font':'noto','arr':chars}),{'Content-Type':'application/json'},'arraybuffer');
}

function requestQuota(size){
	return new Promise(function(resolve,reject){
		navigator.webkitPersistentStorage.requestQuota(size + size/3,
			function(grantedSize) {
				resolve(grantedSize);
			},
			reject
		);
	});
}

function setTheFont(font_src){
	console.log(font_src)
	var font = new FontFace("myfont", "url("+font_src+")", {});
	document.fonts.add(font);
	font.load();

}

function requestTemporaryFileSystem(grantedSize){
	window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;
	return new Promise(function(resolve,reject){
		window.requestFileSystem(window.TEMPORARY, grantedSize, resolve , reject);
	});
}

function requestPersistentFileSystem(grantedSize){
	window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;
	return new Promise(function(resolve,reject){
		window.requestFileSystem(window.PERSISTENT, grantedSize, function(fs) {resolve(fs); } , reject);
	});
}

function requestBaseFont(name){
	return requestURL('/incremental_fonts/base?font='+name,'GET',null,{},'arraybuffer');
}

function sanitizeBaseFont(baseFont){
    var fontObj = parseFont(baseFont);
    var fontParser = new Parser(new DataView(baseFont),0);
    var glyphOffset =  fontObj.glyfOffset;
    for(var i=1;i<fontObj.numGlyphs;i+=1)
    {
      fontParser.writeShortByOffset(glyphOffset+fontObj.loca[i],-1);
    }
    return baseFont;
}

function createTheFile(filename){
	return new Promise(function(resolve,reject){
		fs.root.getFile(filename,{create:true},function(fe){ resolve(fe)},reject);
	});
}

function createFileWriter(fileEntry){
	return new Promise(function(resolve,reject){
		fileEntry.createWriter(function(fw){ resolve(fw);}
			,reject)
	});
}

function getFileEntry(fs,filename){
	return new Promise(function(resolve,reject){
		fs.root.getFile(filename,{create:true},
			function(fileEntry){resolve(fileEntry)},
			reject);
	});
}

function getFileObj(fileEntry){
	return new Promise(function(resolve,reject){
		fileEntry.file(function(file){ resolve(file) },reject);
	});
}

function readFileAsArrayBuffer(file){
	return new Promise(function(resolve,reject){
		var reader = new FileReader();
		reader.onloadend = function(e){resolve(e.target.result)};
		reader.onerror = reject;
		reader.readAsArrayBuffer(file);
	});
}

function getFileWriter(fs,filename){
	return getFileEntry(fs,filename).then(createFileWriter);
}

function injectCharacters(baseFont,glyphData){
    var glyphParser = new Parser(new DataView(glyphData),0);
    console.log('bundle size:'+glyphData.byteLength);
    console.log('baseFont size:'+baseFont.byteLength);
    var fontParser = new Parser(new DataView(baseFont),0);
    var fontObj = parseFont(baseFont);
    var count = glyphParser.parseUShort();
    var flag_mtx = glyphParser.parseByte();
    var glyphOffset=  fontObj.glyfOffset;
    console.log('glyfOff2: '+glyphOffset);
    console.log('count'+count);
    for(var i=0;i<count;i+=1)
    {
       var id = glyphParser.parseUShort();
       var hmtx,vmtx;
       if(flag_mtx & 1){
           hmtx = glyphParser.parseUShort();
           fontObj.metrics[id][1] = hmtx
       }
       if(flag_mtx & 2){
          vmtx = glyphParser.parseUShort();
       }
       var offset = glyphParser.parseULong();
       var length = glyphParser.parseUShort();
       console.log('id:'+id+' off:'+offset+' len:'+length);
       var bytes = glyphParser.parseBytes(length);
       fontParser.setBytes(glyphOffset+offset,bytes);
    }
    if(flag_mtx & 1)
        fontParser.writeHmtx(fontObj);
    console.log('injection is done!');
    return baseFont;
}

var formatFontFace = "\
     @font-face {\
        font-family: 'myfont';\
        src: url('_|-0-|_') format('truetype');\
      }"

function createCSSText(fileURL){
	return formatFontFace.format(fileURL+'?t='+Date.now());
}

function getFileAsArrayBuffer(fs,filename){
	return getFileEntry(fs,filename).then(getFileObj).then(readFileAsArrayBuffer);
}

function writeToTheFile(baseFont,contentType,fileWriter){
	return new Promise(function(resolve,reject){
		fileWriter.onwriteend = function(e) { resolve(e); };
		fileWriter.onerror = function(e) {  reject(e)};
        fileWriter.write(new Blob([baseFont],{type:contentType}));
    });
}

function persistToTheFilesystem(fs,filename,content,type){
	return getFileWriter(fs,filename).then(function(fw){
		return writeToTheFile(content,type,fw);
	});
}

function updateFont()
{

	var baseSanitized = requestBaseFont('noto').then(sanitizeBaseFont);

	var fileSystemReady = requestTemporaryFileSystem(32 * 1024);//requestQuota( 32 * 1024).then(requestPersistentFileSystem);

	var baseFontPersisted = Promise.all([baseSanitized , fileSystemReady]).then(
		function(results){
			return persistToTheFilesystem(results[1],FILENAME,results[0],'application/octet-binary');
		}
	);

	var bundleReady = determineCharacters().then(requestCharacters);

	var charsInjected = Promise.all([baseFontPersisted,bundleReady,fileSystemReady]).then(
		function(results){
			return getFileAsArrayBuffer(results[2],FILENAME).then(
				function(baseFont){
					return injectCharacters(baseFont,results[1]);
				}
			);
		}
	);

	var fileURLReady = fileSystemReady.then(function(fs){ return getFileEntry(fs,FILENAME)})
									  .then(function(fe){ return fe.toURL() });

	var fileUpdated = Promise.all([charsInjected,fileSystemReady]).then(
		function(results){
			return persistToTheFilesystem(results[1],FILENAME,results[0],'application/octet-binary');
		}
	);

	/*var styleSheetReady = Promise.all([fileSystemReady,fileURLReady.then(createCSSText)]).then(function(results){
		return persistToTheFilesystem(results[0],'my_font.css',results[1],'text/css')
	});*/

	Promise.all([fileUpdated,fileURLReady]).then(
		function(results){

			setTheFont(results[1]);
		}
	);

}
<|endoftext|>