<commit_before>/* global describe it document before */
import { expect } from 'chai';
import {
  setAriaCurrent,
  updatePageStyles,
  handleDefaultPagItemClick,
  handleDefaultPagNextClick,
  // handleDefaultPagPrevClick,
} from '../src/assets/drizzle/scripts/pagination/default';
import { goForwardOne, goBackOne } from '../src/assets/drizzle/scripts/pagination/long';

describe('Pagination tests', () => {
  let newPageLink;
  let oldPageLink;
  let addItem;
  let removeItem;
  let classCSS;
  let defaultPag;
  let link1;
  let link2;
  let link3;
  let link1Div;
  let link2Div;
  let link3Div;
  let next;
  let prev;
  let nextDiv;
  let prevDiv;

  before(() => {
    newPageLink = document.createElement('a');
    oldPageLink = document.createElement('a');
    addItem = document.createElement('a');
    removeItem = document.createElement('a');
    defaultPag = document.createElement('nav');

    prev = document.createElement('a');
    next = document.createElement('a');

    prevDiv = document.createElement('div');
    nextDiv = document.createElement('div');

    prevDiv.classList.add('sprk-c-Pagination__item');
    nextDiv.classList.add('sprk-c-Pagination__item');

    link1Div = document.createElement('div');
    link2Div = document.createElement('div');
    link3Div = document.createElement('div');

    link1Div.classList.add('sprk-c-Pagination__item');
    link2Div.classList.add('sprk-c-Pagination__item');
    link3Div.classList.add('sprk-c-Pagination__item');

    link1 = document.createElement('a');
    link2 = document.createElement('a');
    link3 = document.createElement('a');

    link1.textContent = '1';
    link2.textContent = '2';
    link3.textContent = '3';

    link1Div.append(link1);
    link2Div.append(link2);
    link3Div.append(link3);

    prev.setAttribute('data-sprk-pagination', 'prev');
    next.setAttribute('data-sprk-pagination', 'next');

    prevDiv.append(prev);
    nextDiv.append(next);

    link1.setAttribute('data-sprk-pagination', 'item');
    link2.setAttribute('data-sprk-pagination', 'item');
    link3.setAttribute('data-sprk-pagination', 'item');

    defaultPag.setAttribute('data-sprk-pagination', 'default');
    defaultPag.append(prevDiv);
    defaultPag.append(link1Div);
    defaultPag.append(link2Div);
    defaultPag.append(link3Div);
    defaultPag.append(nextDiv);
  });

  it('should add aria-current attribute to new page link and remove from old', () => {
    setAriaCurrent(newPageLink, oldPageLink);
    expect(newPageLink.hasAttribute('aria-current')).eql(true);
    expect(oldPageLink.hasAttribute('aria-current')).eql(false);
  });

  it('should add the CSS class to new item and remove from old', () => {
    classCSS = 'sprk-b-Link--disabled';
    updatePageStyles(addItem, removeItem, classCSS);
    expect(addItem.classList.contains(classCSS)).eql(true);
    expect(removeItem.classList.contains(classCSS)).eql(false);
  });

  it('should go back one page', () => {
    expect(goBackOne(3)).eql(2);
  });

  it('should go forward one page', () => {
    expect(goForwardOne(1)).eql(2);
  });

  it('should add the disabled link class to the next link when the last page is selected', () => {
    classCSS = 'sprk-b-Link--disabled';
    const currentItemNum = parseInt(link3.textContent, 10);
    handleDefaultPagItemClick(currentItemNum, link3, link2, prev, next);
    expect(next.classList.contains(classCSS)).eql(true);
  });

  it('should add the disabled link class to the prev link when the first page is selected', () => {
    classCSS = 'sprk-b-Link--disabled';
    const currentItemNum = parseInt(link1.textContent, 10);
    handleDefaultPagItemClick(currentItemNum, link1, link2, prev, next);
    expect(prev.classList.contains(classCSS)).eql(true);
  });

  it('should add the current item css class to the next page when the next link is clicked', () => {
    classCSS = 'sprk-c-Pagination__item--current';
    const currentPageNum = parseInt(link1.textContent, 10);
    handleDefaultPagNextClick(currentPageNum, link2, link3, link1, prev, next);
    expect(link2.parentElement.classList.contains(classCSS)).eql(true);
    expect(link1.parentElement.classList.contains(classCSS)).eql(false);
  });
});
<commit_msg>bring default to 47.22<commit_after>/* global describe it document before */
import { expect } from 'chai';
import {
  setAriaCurrent,
  updatePageStyles,
  handleDefaultPagItemClick,
  handleDefaultPagNextClick,
  handleDefaultPagPrevClick,
} from '../src/assets/drizzle/scripts/pagination/default';
import { goForwardOne, goBackOne } from '../src/assets/drizzle/scripts/pagination/long';

describe('Pagination tests', () => {
  let newPageLink;
  let oldPageLink;
  let addItem;
  let removeItem;
  let classCSS;
  let defaultPag;
  let link1;
  let link2;
  let link3;
  let link1Div;
  let link2Div;
  let link3Div;
  let next;
  let prev;
  let nextDiv;
  let prevDiv;

  before(() => {
    newPageLink = document.createElement('a');
    oldPageLink = document.createElement('a');
    addItem = document.createElement('a');
    removeItem = document.createElement('a');
    defaultPag = document.createElement('nav');

    prev = document.createElement('a');
    next = document.createElement('a');

    prevDiv = document.createElement('div');
    nextDiv = document.createElement('div');

    prevDiv.classList.add('sprk-c-Pagination__item');
    nextDiv.classList.add('sprk-c-Pagination__item');

    link1Div = document.createElement('div');
    link2Div = document.createElement('div');
    link3Div = document.createElement('div');

    link1Div.classList.add('sprk-c-Pagination__item');
    link2Div.classList.add('sprk-c-Pagination__item');
    link3Div.classList.add('sprk-c-Pagination__item');

    link1 = document.createElement('a');
    link2 = document.createElement('a');
    link3 = document.createElement('a');

    link1.textContent = '1';
    link2.textContent = '2';
    link3.textContent = '3';

    link1Div.append(link1);
    link2Div.append(link2);
    link3Div.append(link3);

    prev.setAttribute('data-sprk-pagination', 'prev');
    next.setAttribute('data-sprk-pagination', 'next');

    prevDiv.append(prev);
    nextDiv.append(next);

    link1.setAttribute('data-sprk-pagination', 'item');
    link2.setAttribute('data-sprk-pagination', 'item');
    link3.setAttribute('data-sprk-pagination', 'item');

    defaultPag.setAttribute('data-sprk-pagination', 'default');
    defaultPag.append(prevDiv);
    defaultPag.append(link1Div);
    defaultPag.append(link2Div);
    defaultPag.append(link3Div);
    defaultPag.append(nextDiv);
  });

  it('should add aria-current attribute to new page link and remove from old', () => {
    setAriaCurrent(newPageLink, oldPageLink);
    expect(newPageLink.hasAttribute('aria-current')).eql(true);
    expect(oldPageLink.hasAttribute('aria-current')).eql(false);
  });

  it('should add the CSS class to new item and remove from old', () => {
    classCSS = 'sprk-b-Link--disabled';
    updatePageStyles(addItem, removeItem, classCSS);
    expect(addItem.classList.contains(classCSS)).eql(true);
    expect(removeItem.classList.contains(classCSS)).eql(false);
  });

  it('should go back one page', () => {
    expect(goBackOne(3)).eql(2);
  });

  it('should go forward one page', () => {
    expect(goForwardOne(1)).eql(2);
  });

  it('should add the disabled link class to the next link when the last page is selected', () => {
    classCSS = 'sprk-b-Link--disabled';
    const currentItemNum = parseInt(link3.textContent, 10);
    handleDefaultPagItemClick(currentItemNum, link3, link2, prev, next);
    expect(next.classList.contains(classCSS)).eql(true);
  });

  it('should add the disabled link class to the prev link when the first page is selected', () => {
    classCSS = 'sprk-b-Link--disabled';
    const currentItemNum = parseInt(link1.textContent, 10);
    handleDefaultPagItemClick(currentItemNum, link1, link2, prev, next);
    expect(prev.classList.contains(classCSS)).eql(true);
  });

  it('should add the current item css class to the next page when the next link is clicked', () => {
    classCSS = 'sprk-c-Pagination__item--current';
    const currentPageNum = parseInt(link1.textContent, 10);
    handleDefaultPagNextClick(currentPageNum, link2, link3, link1, prev, next);
    expect(link2.parentElement.classList.contains(classCSS)).eql(true);
    expect(link1.parentElement.classList.contains(classCSS)).eql(false);
  });

  it('should add the current item css class to the previous page when the previous link is clicked', () => {
    classCSS = 'sprk-c-Pagination__item--current';
    const currentPageNum = parseInt(link2.textContent, 10);
    handleDefaultPagPrevClick(currentPageNum, link1, link2, link2, prev, next);
    expect(link1.parentElement.classList.contains(classCSS)).eql(true);
    expect(link2.parentElement.classList.contains(classCSS)).eql(false);
  });
});
<|endoftext|>


<commit_before>const path = require('path');
const fs = require('fs-extra');
const exec = require('child_process').exec;
const vinyl = require('vinyl-fs');
const mergeStream = require('merge-stream');
const PolymerProject = require('polymer-build').PolymerProject;
const config = require('./build-web.config');
config.source = config.source || 'src';
config.target = config.target || 'build';

function execute(command, silent) {
    if(!silent) {
        console.log('>', command);
    }
    return new Promise((resolve, reject) => {
        exec(command, (error, stdout, stderr) => {
            if(!silent) {
                console.log(stdout);
                console.log(stderr);
            }
            if(error) {
                reject(error);
            } else {
                resolve(stdout);
            }
        });
    });
}

async function gitStashPush(identifier) {
    identifier = identifier || 'DEPLOY#' + Date.now().toString(16).toUpperCase();
    await execute(`git stash push -u -m '${identifier}'`);
    return identifier;
}

async function gitStashPop(identifier) {
    let out = await execute(`git stash list`);
    if(out.includes(identifier)) {
        await execute(`git stash pop`);
    }
}

function pipe(streamReader, streamWriter) {
    return new Promise((resolve, reject) => {
        let stream = streamReader.pipe(streamWriter);
        stream.on('error', reject);
        stream.on('end', resolve);
    });
}

async function polymerBuild(settings) {
    let target = path.resolve(config.target);
    let cwd = process.cwd();
    if(config.source) {
        process.chdir(config.source);
    }

    let project = new PolymerProject(settings);
    let streamIn = mergeStream(project.sources(), project.dependencies());
    let streamOut = vinyl.dest(target);
    await pipe(streamIn, streamOut);

    process.chdir(cwd);
}

async function createVersionInfo(file) {
    let branch = undefined;
    // GitHub actions checkout the commit in a detached HEAD state => try to get branch from GitHub environment variable
    if(process.env.GITHUB_REF) {
        process.env.GITHUB_REF.split('/').pop();
    }
    branch = branch || (await execute(`git rev-parse --abbrev-ref HEAD`)).trim();
    let revision = (await execute(`git rev-parse HEAD`)).trim();
    let content = [
        `export default {`,
        `    branch: {`,
        `        label: '${branch}',`,
        `        link: 'https://github.com/manga-download/hakuneko/commits/${branch}',`,
        `    },`,
        `    revision: {`,
        `        label: '${revision.slice(0, 6)}',`,
        `        link: 'https://github.com/manga-download/hakuneko/commits/${revision}',`,
        `    }`,
        `};`
    ].join('\n');
    await fs.writeFile(file, content);
}

async function main() {
    let stashID = await gitStashPush();
    await fs.remove(config.target);
    await polymerBuild(config.polymer);
    await createVersionInfo(path.join(config.target, config.version));
    await gitStashPop(stashID);
}

// exit application as soon as any uncaught exception is thrown
process.on('unhandledRejection', error => { throw error; });
main();<commit_msg>[github-actions] checkout@v2 allows simpler branch name extraction<commit_after>const path = require('path');
const fs = require('fs-extra');
const exec = require('child_process').exec;
const vinyl = require('vinyl-fs');
const mergeStream = require('merge-stream');
const PolymerProject = require('polymer-build').PolymerProject;
const config = require('./build-web.config');
config.source = config.source || 'src';
config.target = config.target || 'build';

function execute(command, silent) {
    if(!silent) {
        console.log('>', command);
    }
    return new Promise((resolve, reject) => {
        exec(command, (error, stdout, stderr) => {
            if(!silent) {
                console.log(stdout);
                console.log(stderr);
            }
            if(error) {
                reject(error);
            } else {
                resolve(stdout);
            }
        });
    });
}

async function gitStashPush(identifier) {
    identifier = identifier || 'DEPLOY#' + Date.now().toString(16).toUpperCase();
    await execute(`git stash push -u -m '${identifier}'`);
    return identifier;
}

async function gitStashPop(identifier) {
    let out = await execute(`git stash list`);
    if(out.includes(identifier)) {
        await execute(`git stash pop`);
    }
}

function pipe(streamReader, streamWriter) {
    return new Promise((resolve, reject) => {
        let stream = streamReader.pipe(streamWriter);
        stream.on('error', reject);
        stream.on('end', resolve);
    });
}

async function polymerBuild(settings) {
    let target = path.resolve(config.target);
    let cwd = process.cwd();
    if(config.source) {
        process.chdir(config.source);
    }

    let project = new PolymerProject(settings);
    let streamIn = mergeStream(project.sources(), project.dependencies());
    let streamOut = vinyl.dest(target);
    await pipe(streamIn, streamOut);

    process.chdir(cwd);
}

async function createVersionInfo(file) {
    let branch = /*process.env.GITHUB_REF ? process.env.GITHUB_REF.split('/').pop() : */(await execute(`git rev-parse --abbrev-ref HEAD`)).trim();
    let revision = (await execute(`git rev-parse HEAD`)).trim();
    let content = [
        `export default {`,
        `    branch: {`,
        `        label: '${branch}',`,
        `        link: 'https://github.com/manga-download/hakuneko/commits/${branch}',`,
        `    },`,
        `    revision: {`,
        `        label: '${revision.slice(0, 6)}',`,
        `        link: 'https://github.com/manga-download/hakuneko/commits/${revision}',`,
        `    }`,
        `};`
    ].join('\n');
    await fs.writeFile(file, content);
}

async function main() {
    let stashID = await gitStashPush();
    await fs.remove(config.target);
    await polymerBuild(config.polymer);
    await createVersionInfo(path.join(config.target, config.version));
    await gitStashPop(stashID);
}

// exit application as soon as any uncaught exception is thrown
process.on('unhandledRejection', error => { throw error; });
main();<|endoftext|>


<commit_before>const JSONRequest = require("./request");

class PostcodeClient {
	constructor (options) {
		if(!options) throw new TypeError("'options' has to be set");
		if(!options.key) throw new TypeError("'options.key' has to be set");
		if(!options.secret) throw new TypeError("'options.secret' has to be set");

		this._options = options;

		this._r = new JSONRequest(this._options);
	}

	address(postcode, number, numberAddition) {
		//Check if the postcode is set
		if(!postcode) throw new TypeError("'postcode' is required");

		// Rewrite the format to 1234AA (no space, capitalized)
		postcode = postcode.replace(/\s/g, "").toUpperCase();

		// Check if the postcode is a valid format
		if(!/^[1-9][0-9]{3}[A-Z]{2}$/.test(postcode)) throw new TypeError("'postcode' is not in a valid format");

		let vars = {
			postcode: postcode
		};

		let path = "/addresses/"+postcode;
		if(number) {
			if(Number(number) === number && number >= 0 && number <= 99999 && number % 1 === 0) {
				path += "/"+number;
				vars.number = number;
				if(numberAddition) {
					path += "/"+numberAddition;
					vars.numberAddition = numberAddition;
				}
			}else{
				throw new TypeError("'number' is not a valid number or out of range");
			}
		}else{
			throw new TypeError("'number' is required");
		}

		return new Promise((resolve, reject) => {
			this._r.get(path)
			.then((res) => {
				resolve(res);
			})
			.catch((err) => {
				if(err.statusCode === 404) {
					let error = new Error("Address not found");
					error.code = err.json.exceptionId;
					error.vars = vars;
					reject(error);
				}else{
					reject(err);
				}
			});
		});
	}

	signal(options) {
		if(!options || typeof options != "object") throw new TypeError("'options' is required and should be an object");
		if(Object.keys(options).length == 0) throw new TypeError("'options' must have at least one option");

		return new Promise((resolve, reject) => {
			this._r.post("/signal/check", options)
			.then((res) => {
				resolve(res);
			})
			.catch((err) => {
				if(err.statusCode === 400) {
					err.code = err.json.exceptionId;
					reject(err);
				}else{
					reject(error);
				}
			});
		});
	}
};

module.exports = PostcodeClient;<commit_msg>Fix error is not defined<commit_after>const JSONRequest = require("./request");

class PostcodeClient {
	constructor (options) {
		if(!options) throw new TypeError("'options' has to be set");
		if(!options.key) throw new TypeError("'options.key' has to be set");
		if(!options.secret) throw new TypeError("'options.secret' has to be set");

		this._options = options;

		this._r = new JSONRequest(this._options);
	}

	address(postcode, number, numberAddition) {
		//Check if the postcode is set
		if(!postcode) throw new TypeError("'postcode' is required");

		// Rewrite the format to 1234AA (no space, capitalized)
		postcode = postcode.replace(/\s/g, "").toUpperCase();

		// Check if the postcode is a valid format
		if(!/^[1-9][0-9]{3}[A-Z]{2}$/.test(postcode)) throw new TypeError("'postcode' is not in a valid format");

		let vars = {
			postcode: postcode
		};

		let path = "/addresses/"+postcode;
		if(number) {
			if(Number(number) === number && number >= 0 && number <= 99999 && number % 1 === 0) {
				path += "/"+number;
				vars.number = number;
				if(numberAddition) {
					path += "/"+numberAddition;
					vars.numberAddition = numberAddition;
				}
			}else{
				throw new TypeError("'number' is not a valid number or out of range");
			}
		}else{
			throw new TypeError("'number' is required");
		}

		return new Promise((resolve, reject) => {
			this._r.get(path)
			.then((res) => {
				resolve(res);
			})
			.catch((err) => {
				if(err.statusCode === 404) {
					let error = new Error("Address not found");
					error.code = err.json.exceptionId;
					error.vars = vars;
					reject(error);
				}else{
					reject(err);
				}
			});
		});
	}

	signal(options) {
		if(!options || typeof options != "object") throw new TypeError("'options' is required and should be an object");
		if(Object.keys(options).length == 0) throw new TypeError("'options' must have at least one option");

		return new Promise((resolve, reject) => {
			this._r.post("/signal/check", options)
			.then((res) => {
				resolve(res);
			})
			.catch((err) => {
				if(err.statusCode === 400) {
					err.code = err.json.exceptionId;
					reject(err);
				}else{
					reject(err);
				}
			});
		});
	}
};

module.exports = PostcodeClient;
<|endoftext|>


<commit_before>import { TextMetrics } from 'pixi.js';

export function PIXITextMetricsPlugIn() {
    const WordWrap = TextMetrics.wordWrap;
    TextMetrics.__breakAllWordWrap = __breakAllWordWrap;

    TextMetrics.wordWrap = function(text, style, canvas = TextMetrics._canvas) {
        return style.wordBreakAll
            ? TextMetrics.__breakAllWordWrap(text, style, canvas)
            : WordWrap(text, style, canvas);
    };

    /**
     *
     * @param text
     * @param {PIXI.TextStyle | PIXITextStyle} style
     * @param canvas
     * @return {string}
     * @private
     */
    function __breakAllWordWrap(text, style, canvas) {
        const context = canvas.getContext('2d');

        let width = 0;
        let line = '';
        let lines = '';

        const cache = {};
        const { letterSpacing, whiteSpace } = style;

        // How to handle whitespaces
        const collapseSpaces = TextMetrics.collapseSpaces(whiteSpace);
        const collapseNewlines = TextMetrics.collapseNewlines(whiteSpace);

        // whether or not spaces may be added to the beginning of lines
        let canPrependSpaces = !collapseSpaces;

        // There is letterSpacing after every char except the last one
        // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_!
        // so for convenience the above needs to be compared to width + 1 extra letterSpace
        // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_!_
        // ________________________________________________
        // And then the final space is simply no appended to each line
        const wordWrapWidth = style.wordWrapWidth + letterSpacing;

        // break text into words, spaces and newline chars
        const tokens = TextMetrics.tokenize(text);

        for (let i = 0; i < tokens.length; i++) {
            // get the word, space or newlineChar
            let token = tokens[i];

            // if word is a new line
            if (TextMetrics.isNewline(token)) {
                // keep the new line
                if (!collapseNewlines) {
                    lines += TextMetrics.addLine(line);
                    canPrependSpaces = !collapseSpaces;
                    line = '';
                    width = 0;
                    continue;
                }

                // if we should collapse new lines
                // we simply convert it into a space
                token = ' ';
            }

            // if we should collapse repeated whitespaces
            if (collapseSpaces) {
                // check both this and the last tokens for spaces
                const currIsBreakingSpace = TextMetrics.isBreakingSpace(token);
                const lastIsBreakingSpace = TextMetrics.isBreakingSpace(line[line.length - 1]);

                if (currIsBreakingSpace && lastIsBreakingSpace) {
                    continue;
                }
            }

            // get word width from cache if possible
            const tokenWidth = TextMetrics.getFromCache(token, letterSpacing, cache, context);

            // word is longer than desired bounds
            if (width + tokenWidth > wordWrapWidth) {
                const characters = token.split('');
                for (let j = 0; j < characters.length; j++) {
                    const char = characters[j];
                    const characterWidth = TextMetrics.getFromCache(
                        char,
                        letterSpacing,
                        cache,
                        context
                    );
                    if (width + characterWidth > wordWrapWidth) {
                        //newLine
                        lines += TextMetrics.addLine(line);
                        canPrependSpaces = false;
                        line = '';
                        width = 0;
                    }
                    line += char;
                    width += characterWidth;
                }
            }

            // word could fit
            else {
                // word won't fit because of existing words
                // start a new line
                if (tokenWidth + width > wordWrapWidth) {
                    // if its a space we don't want it
                    canPrependSpaces = false;

                    // add a new line
                    lines += TextMetrics.addLine(line);

                    // start a new line
                    line = '';
                    width = 0;
                }

                // don't add spaces to the beginning of lines
                if (line.length > 0 || !TextMetrics.isBreakingSpace(token) || canPrependSpaces) {
                    // add the word to the current line
                    line += token;

                    // update width counter
                    width += tokenWidth;
                }
            }
        }

        lines += TextMetrics.addLine(line, false);

        return lines;
    }

    //createjs와 동일한 글씨 크기 측정을 위해
    /**
     *
     * @param {PIXI.TextStyle} style
     * @param text
     * @return {number}
     * @private
     */
    function getMeasuredWidth(font, text) {
        const ctx = TextMetrics._context;
        ctx.save();
        ctx.font = font;
        const w = ctx.measureText(text).width;
        ctx.restore();
        return w;
    }

    //createjs와 동일한 글씨 크기 측정을 위해
    TextMetrics.measureText = function(text, style, wordWrap, canvas = TextMetrics._canvas) {
        wordWrap = wordWrap === undefined || wordWrap === null ? style.wordWrap : wordWrap;
        const font = style.toFontString();
        // const fontProperties = TextMetrics.measureFont(font); //skip for performance
        const fontProperties = null;
        const context = canvas.getContext('2d');

        context.font = font;

        const outputText = wordWrap ? TextMetrics.wordWrap(text, style, canvas) : text;
        const lines = outputText.split(/(?:\r\n|\r|\n)/);
        const lineWidths = new Array(lines.length);
        let maxLineWidth = 0;

        for (let i = 0; i < lines.length; i++) {
            const lineWidth =
                context.measureText(lines[i]).width + (lines[i].length - 1) * style.letterSpacing;

            lineWidths[i] = lineWidth;
            maxLineWidth = Math.max(maxLineWidth, lineWidth);
        }
        const width = maxLineWidth + style.strokeThickness;
        const lineHeight = style.lineHeight || _getMeasuredWidth(font, 'M') * 1.2;
        const height = lineHeight * lines.length;

        return new TextMetrics(
            text,
            style,
            width,
            height,
            lines,
            lineWidths,
            lineHeight + style.leading,
            maxLineWidth,
            fontProperties
        );
    };
}
<commit_msg>부스트모드 에러 수정<commit_after>import { TextMetrics } from 'pixi.js';

export function PIXITextMetricsPlugIn() {
    const WordWrap = TextMetrics.wordWrap;
    TextMetrics.__breakAllWordWrap = __breakAllWordWrap;

    TextMetrics.wordWrap = function(text, style, canvas = TextMetrics._canvas) {
        return style.wordBreakAll
            ? TextMetrics.__breakAllWordWrap(text, style, canvas)
            : WordWrap(text, style, canvas);
    };

    /**
     *
     * @param text
     * @param {PIXI.TextStyle | PIXITextStyle} style
     * @param canvas
     * @return {string}
     * @private
     */
    function __breakAllWordWrap(text, style, canvas) {
        const context = canvas.getContext('2d');

        let width = 0;
        let line = '';
        let lines = '';

        const cache = {};
        const { letterSpacing, whiteSpace } = style;

        // How to handle whitespaces
        const collapseSpaces = TextMetrics.collapseSpaces(whiteSpace);
        const collapseNewlines = TextMetrics.collapseNewlines(whiteSpace);

        // whether or not spaces may be added to the beginning of lines
        let canPrependSpaces = !collapseSpaces;

        // There is letterSpacing after every char except the last one
        // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_!
        // so for convenience the above needs to be compared to width + 1 extra letterSpace
        // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_!_
        // ________________________________________________
        // And then the final space is simply no appended to each line
        const wordWrapWidth = style.wordWrapWidth + letterSpacing;

        // break text into words, spaces and newline chars
        const tokens = TextMetrics.tokenize(text);

        for (let i = 0; i < tokens.length; i++) {
            // get the word, space or newlineChar
            let token = tokens[i];

            // if word is a new line
            if (TextMetrics.isNewline(token)) {
                // keep the new line
                if (!collapseNewlines) {
                    lines += TextMetrics.addLine(line);
                    canPrependSpaces = !collapseSpaces;
                    line = '';
                    width = 0;
                    continue;
                }

                // if we should collapse new lines
                // we simply convert it into a space
                token = ' ';
            }

            // if we should collapse repeated whitespaces
            if (collapseSpaces) {
                // check both this and the last tokens for spaces
                const currIsBreakingSpace = TextMetrics.isBreakingSpace(token);
                const lastIsBreakingSpace = TextMetrics.isBreakingSpace(line[line.length - 1]);

                if (currIsBreakingSpace && lastIsBreakingSpace) {
                    continue;
                }
            }

            // get word width from cache if possible
            const tokenWidth = TextMetrics.getFromCache(token, letterSpacing, cache, context);

            // word is longer than desired bounds
            if (width + tokenWidth > wordWrapWidth) {
                const characters = token.split('');
                for (let j = 0; j < characters.length; j++) {
                    const char = characters[j];
                    const characterWidth = TextMetrics.getFromCache(
                        char,
                        letterSpacing,
                        cache,
                        context
                    );
                    if (width + characterWidth > wordWrapWidth) {
                        //newLine
                        lines += TextMetrics.addLine(line);
                        canPrependSpaces = false;
                        line = '';
                        width = 0;
                    }
                    line += char;
                    width += characterWidth;
                }
            }

            // word could fit
            else {
                // word won't fit because of existing words
                // start a new line
                if (tokenWidth + width > wordWrapWidth) {
                    // if its a space we don't want it
                    canPrependSpaces = false;

                    // add a new line
                    lines += TextMetrics.addLine(line);

                    // start a new line
                    line = '';
                    width = 0;
                }

                // don't add spaces to the beginning of lines
                if (line.length > 0 || !TextMetrics.isBreakingSpace(token) || canPrependSpaces) {
                    // add the word to the current line
                    line += token;

                    // update width counter
                    width += tokenWidth;
                }
            }
        }

        lines += TextMetrics.addLine(line, false);

        return lines;
    }

    //createjs와 동일한 글씨 크기 측정을 위해
    /**
     *
     * @param {PIXI.TextStyle} style
     * @param text
     * @return {number}
     * @private
     */
    function _getMeasuredWidth(font, text) {
        const ctx = TextMetrics._context;
        ctx.save();
        ctx.font = font;
        const w = ctx.measureText(text).width;
        ctx.restore();
        return w;
    }

    //createjs와 동일한 글씨 크기 측정을 위해
    TextMetrics.measureText = function(text, style, wordWrap, canvas = TextMetrics._canvas) {
        wordWrap = wordWrap === undefined || wordWrap === null ? style.wordWrap : wordWrap;
        const font = style.toFontString();
        // const fontProperties = TextMetrics.measureFont(font); //skip for performance
        const fontProperties = null;
        const context = canvas.getContext('2d');

        context.font = font;

        const outputText = wordWrap ? TextMetrics.wordWrap(text, style, canvas) : text;
        const lines = outputText.split(/(?:\r\n|\r|\n)/);
        const lineWidths = new Array(lines.length);
        let maxLineWidth = 0;

        for (let i = 0; i < lines.length; i++) {
            const lineWidth =
                context.measureText(lines[i]).width + (lines[i].length - 1) * style.letterSpacing;

            lineWidths[i] = lineWidth;
            maxLineWidth = Math.max(maxLineWidth, lineWidth);
        }
        const width = maxLineWidth + style.strokeThickness;
        const lineHeight = style.lineHeight || _getMeasuredWidth(font, 'M') * 1.2;
        const height = lineHeight * lines.length;

        return new TextMetrics(
            text,
            style,
            width,
            height,
            lines,
            lineWidths,
            lineHeight + style.leading,
            maxLineWidth,
            fontProperties
        );
    };
}
<|endoftext|>


<commit_before>'use strict'
var Module = require('module')
var assert = require('assert')
var process = require('process')
var fs = require('fs')
var isNode = require('./is/node')
var _isArray = require('lodash.isarray')
var _isFunction = require('lodash.isfunction')
var _isRegExp = require('lodash.isregexp')
var _isString = require('lodash.isstring')

var originalRequire

if (isNode) {
  originalRequire = Module.prototype.require
  module.exports = enhanceRequire
} else { // let browserify (or similar) do it
  module.exports = enhanceRequireMock
}

/**
 * @id require.enhanceRequire
 * @function enhanceRequire
 * In node, modifies the behaviour of `require` so that it ignores paths containing `.css`, `.less`, `.scss`, `.sass`, and any other paths indicated via the `exclude` option.
 * Outside of node (browserify, webpack, etc.), this function does nothing.
 * @param {object} [options] - Options to further define the behaviour of `require`:
 * - + {*boolean*} **options.package** : set to `true` to convert `require('package.json')` to `JSON.parse(require(process.cwd() + '/package.json'))`
 * - + {*string|regexp|function|array*} **options.exclude** : paths containing the specified string, or matching the specified regexp, or for which specified function returns `true`, will be excluded. If an array is provided, each element is treated exactly the same as `options.exclude` and only paths which aren't excluded by any item will be `require`d.
 */
function enhanceRequire (_options) {
  var options = _options || {}
  var require = function require (path) {
    assert(typeof path === 'string', 'path must be a string')
    assert(path, 'missing path')
    var next = () => {
      return Module.prototype.require.next.apply(this, arguments)
    }
    // This is dirty but probably the best solution for now
    if (options.package && path === 'package.json') {
      var pckg = fs.readFileSync(process.cwd() + '/package.json')
      return JSON.parse(pckg.toString())
    }
    if (exclude(options.exclude, path, next)) {
      return {}
    } else {
      if (path === 'package.json') {
        console.log('find top package.json not doing it now.. do it soon')
        path = './package.json'
      }
      return next(path)
    }
  }
  require.next = Module.prototype.require
  Module.prototype.require = require
}

function exclude (optionsExclude, path) {
  if (optionsExclude) {
    if (_isArray(optionsExclude)) {
      let excludeIt = false
      let len = optionsExclude.length
      for (let i = 0; i < len && !excludeIt; i += 1) {
        if (exclude(optionsExclude[i], path)) {
          excludeIt = true
        }
      }
      if (excludeIt) {
        return true
      }
    } else if (_isFunction(optionsExclude) && optionsExclude(path)) {
      return true
    } else if (_isRegExp(optionsExclude) && optionsExclude.test(path)) {
      return true
    } else if (_isString(optionsExclude) && path.indexOf(optionsExclude) !== -1) {
      return true
    }
  }
  if (/\.less/.test(path)) {
    return true
  }
  if (/\.css/.test(path)) {
    return true
  }
  if (/\.scss/.test(path)) {
    return true
  }
  if (/\.sass/.test(path)) {
    return true
  }
  return false
}

/**
 * @id require.restore
 * @function restore
 * Restores the original behaviour or `require`
 */
enhanceRequire.restore = function restoreRequire () {
  Module.prototype.require = originalRequire
}

function enhanceRequireMock (options) {
  // Do nothing
}
enhanceRequireMock.restore = function restoreRequireMock () {
  // Do nothing
}
<commit_msg>require logs<commit_after>'use strict'
var Module = require('module')
var assert = require('assert')
// var process = require('process')
var fs = require('fs')
var isNode = require('./is/node')
var _isArray = require('lodash.isarray')
var _isFunction = require('lodash.isfunction')
var _isRegExp = require('lodash.isregexp')
var _isString = require('lodash.isstring')

var originalRequire

if (isNode) {
  originalRequire = Module.prototype.require
  module.exports = enhanceRequire
} else { // let browserify (or similar) do it
  module.exports = enhanceRequireMock
}

/**
 * @id require.enhanceRequire
 * @function enhanceRequire
 * In node, modifies the behaviour of `require` so that it ignores paths containing `.css`, `.less`, `.scss`, `.sass`, and any other paths indicated via the `exclude` option.
 * Outside of node (browserify, webpack, etc.), this function does nothing.
 * @param {object} [options] - Options to further define the behaviour of `require`:
 * - + {*boolean*} **options.package** : set to `true` to convert `require('package.json')` to `JSON.parse(require(process.cwd() + '/package.json'))`
 * - + {*string|regexp|function|array*} **options.exclude** : paths containing the specified string, or matching the specified regexp, or for which specified function returns `true`, will be excluded. If an array is provided, each element is treated exactly the same as `options.exclude` and only paths which aren't excluded by any item will be `require`d.
 */
function enhanceRequire (_options) {
  var options = _options || {}
  var require = function require (path) {
    assert(typeof path === 'string', 'path must be a string')
    assert(path, 'missing path')
    var next = () => {
      return Module.prototype.require.next.apply(this, arguments)
    }
    // This is dirty but probably the best solution for now
    if (options.package && path === 'package.json') {
      var pckg = fs.readFileSync(process.cwd() + '/package.json')
      return JSON.parse(pckg.toString())
    }
    if (exclude(options.exclude, path, next)) {
      return {}
    } else {
      if (path === 'package.json') {
        console.log('find top package.json not doing it now.. do it soon')
        path = './package.json'
      }
      return next(path)
    }
  }
  require.next = Module.prototype.require
  Module.prototype.require = require
}

function exclude (optionsExclude, path) {
  if (optionsExclude) {
    if (_isArray(optionsExclude)) {
      let excludeIt = false
      let len = optionsExclude.length
      for (let i = 0; i < len && !excludeIt; i += 1) {
        if (exclude(optionsExclude[i], path)) {
          excludeIt = true
        }
      }
      if (excludeIt) {
        return true
      }
    } else if (_isFunction(optionsExclude) && optionsExclude(path)) {
      return true
    } else if (_isRegExp(optionsExclude) && optionsExclude.test(path)) {
      return true
    } else if (_isString(optionsExclude) && path.indexOf(optionsExclude) !== -1) {
      return true
    }
  }
  if (/\.less/.test(path)) {
    return true
  }
  if (/\.css/.test(path)) {
    return true
  }
  if (/\.scss/.test(path)) {
    return true
  }
  if (/\.sass/.test(path)) {
    return true
  }
  return false
}

/**
 * @id require.restore
 * @function restore
 * Restores the original behaviour or `require`
 */
enhanceRequire.restore = function restoreRequire () {
  Module.prototype.require = originalRequire
}

function enhanceRequireMock (options) {
  // Do nothing
}
enhanceRequireMock.restore = function restoreRequireMock () {
  // Do nothing
}
<|endoftext|>


<commit_before>/**
 * Created by josh.horecny on 11/3/15.
 */
var express = require('express');
var router = express();

router.get('/', function(req, res) {
    res.send('Must Include Collection Name')
})

router.get('/polls', function(req, res, next) {
    var db = req.db;
    var collection = db.get('Polls');
    collection.find({} ,{limit:10, sort: [['_id',-1]]}).toArray(function(e, results){
        if (e) return next(e)
        res.send(results)
    })
})

/*router.post('/collections/:collectionName', function(req, res, next) {
    req.collection.insert(req.body, {}, function(e, results){
        if (e) return next(e)
        res.send(results)
    })
})

router.get('/collections/:collectionName/:id', function(req, res, next) {
    req.collection.findById(req.params.id, function(e, result){
        if (e) return next(e)
        res.send(result)
    })
})

router.put('/collections/:collectionName/:id', function(req, res, next) {
    req.collection.updateById(req.params.id, {$set:req.body}, {safe:true, multi:false}, function(e, result){
        if (e) return next(e)
        res.send((result===1)?{msg:'success'}:{msg:'error'})
    })
})

router.delete('/collections/:collectionName/:id', function(req, res, next) {
    req.collection.removeById(req.params.id, function(e, result){
        if (e) return next(e)
        res.send((result===1)?{msg:'success'}:{msg:'error'})
    })
})*/<commit_msg>Added file path for static files<commit_after>/**
 * Created by josh.horecny on 11/3/15.
 */
var express = require('express');
var router = express.Router();

router.get('/', function(req, res) {
    res.send('Must Include Collection Name')
})

router.get('/polls', function(req, res, next) {
    var db = req.db;
    var collection = db.get('Polls');
    collection.find({} ,{limit:10, sort: [['_id',-1]]}).toArray(function(e, results){
        if (e) return next(e)
        res.send(results)
    })
})

/*router.post('/collections/:collectionName', function(req, res, next) {
    req.collection.insert(req.body, {}, function(e, results){
        if (e) return next(e)
        res.send(results)
    })
})

router.get('/collections/:collectionName/:id', function(req, res, next) {
    req.collection.findById(req.params.id, function(e, result){
        if (e) return next(e)
        res.send(result)
    })
})

router.put('/collections/:collectionName/:id', function(req, res, next) {
    req.collection.updateById(req.params.id, {$set:req.body}, {safe:true, multi:false}, function(e, result){
        if (e) return next(e)
        res.send((result===1)?{msg:'success'}:{msg:'error'})
    })
})

router.delete('/collections/:collectionName/:id', function(req, res, next) {
    req.collection.removeById(req.params.id, function(e, result){
        if (e) return next(e)
        res.send((result===1)?{msg:'success'}:{msg:'error'})
    })
})*/<|endoftext|>


<commit_before>if (jQuery != undefined) {
    var django = {
        'jQuery':jQuery,
    }
}
(function($) {

    window.geopositionMapInit = function() {
        var mapDefaults = {
            'mapTypeId': google.maps.MapTypeId.ROADMAP
        };

        $('p.geoposition-widget').each(function() {
            var $container = $(this),
                $mapContainer = $('
'),
                $addressRow = $('
'),
                $searchRow = $('
'),
                $searchInput = $('<input>', {'type': 'search', 'placeholder': 'Search …'}),
                $latitudeField = $container.find('input.geoposition:eq(0)'),
                $longitudeField = $container.find('input.geoposition:eq(1)'),
                latitude = parseFloat($latitudeField.val()) || 0,
                longitude = parseFloat($longitudeField.val()) || 0,
                map,
                mapLatLng,
                mapOptions,
                marker;

            $searchInput.bind('keydown', function(e) {
                if (e.keyCode == 13) {
                    e.preventDefault();
                    var $input = $(this),
                        gc = new google.maps.Geocoder();
                    $input.parent().find('ul.geoposition-results').remove();
                    gc.geocode({
                        'address': $(this).val()
                    }, function(results, status) {
                        if (status == 'OK') {
                            var updatePosition = function(result) {
                                if (result.geometry.bounds) {
                                    map.fitBounds(result.geometry.bounds);
                                } else {
                                    map.panTo(result.geometry.location);
                                    map.setZoom(18);
                                }
                                marker.setPosition(result.geometry.location);
                                google.maps.event.trigger(marker, 'dragend');
                            };

                            if (results.length == 1) {
                                updatePosition(results[0]);
                            } else {
                                var $ul = $('
', {'class': 'geoposition-results'});
                                $.each(results, function(i, result) {
                                    var $li = $('
');
                                    $li.text(result.formatted_address);
                                    $li.bind('click', function() {
                                        updatePosition(result);
                                        $li.closest('ul').remove();
                                    });
                                    $li.appendTo($ul);
                                });
                                $input.after($ul);
                            }
                        }
                    });
                }
            }).bind('abort', function() {
                $(this).parent().find('ul.geoposition-results').remove();
            });
            $searchInput.appendTo($searchRow);
            $container.append($mapContainer, $addressRow, $searchRow);

            mapLatLng = new google.maps.LatLng(latitude, longitude);
            mapOptions = $.extend({}, mapDefaults, {
                'center': mapLatLng,
                'zoom': latitude && longitude ? 15 : 1
            });
            map = new google.maps.Map($mapContainer.get(0), mapOptions);
            marker = new google.maps.Marker({
                'position': mapLatLng,
                'map': map,
                'draggable': true,
                'animation': google.maps.Animation.DROP
            });
            google.maps.event.addListener(marker, 'dragend', function() {
                $latitudeField.val(this.position.lat());
                $longitudeField.val(this.position.lng());

                var gc = new google.maps.Geocoder();
                gc.geocode({
                    'latLng': marker.position
                }, function(results, status) {
                    $addressRow.text('');
                    if (results[0]) {
                        $addressRow.text(results[0].formatted_address);
                    }
                });
            });
            google.maps.event.trigger(marker, 'dragend');
        });

    };

    $(document).ready(function() {
        var $script = $('


<commit_before>Seed({
		name : "Mold.Lib.VDom.ProtoNode",
		dna : "data",
		include : [
			"Mold.Lib.VDom.VDoc",
			"Mold.Lib.Filter"
		]
	},
	function(){

		var STATE_RENDER = "render";
		var STATE_NEW = "new";
		var STATE_REMOVE = "remove";
		var STATE_NO_CHANGES = "no changes";
		var STATE_UPDATE = "update";

		var VALUE_NODE = 1;
		var BLOCK_NODE = 2;
		var NEGATIVE_BLOCK_NODE = 3;
		var DOM_NODE = 5;
		var TEXT_NODE = 6;
		var ATTRIBUTE_NODE = 6;
		var STRING_NODE = 8;
		var ROOT_NODE = 9;

		var _doc = Mold.Lib.VDom.VDoc;

		if(!config.name){
			throw new Error("Name must be specified!")
		}

		var _vDom = config.vdom || [];
		var _that = this;
		var _oldData = false;

		this.children = this.children || {};
		this.data = config.data || false;
		this.name = config.name;
		this.type = STRING_NODE;
		this.parent = false;
		this.state = STATE_NEW;
		this.isString = config.isString || false;
		this.hasBinding = false;
		this._id = Mold.getId();
		this.services = config.services || false;
		this.template = config.template || false;

		this.vdom = _vDom;
		this.protoChild = {};

		this.renderDom = false;

		this.afterAddChild = function(child){

		}

		this.addNode = function(child, addAttribute){

			if(!addAttribute){
				_vDom.push(child);
			}

			child.parent = _that;
			child.services = this.services;

			if(
				child.type === BLOCK_NODE
				|| child.type === VALUE_NODE
				|| child.type === NEGATIVE_BLOCK_NODE
			){

				//if current node is not a block-node add child to next block-node
				if(this.type !== BLOCK_NODE){
					if(this.children[child.name]){
						//if there are two nodes with the same name create an array
						this.children[child.name] = [this.children[child.name]]
						this.children[child.name].push(child);
					}else{
						this.children[child.name] = child;
					}
					var parentBlock = this.parent;
					if(parentBlock){
						while(parentBlock.type !== BLOCK_NODE && parentBlock.parent){
							parentBlock = parentBlock.parent;
						}

						if(parentBlock){
							if(parentBlock.type === BLOCK_NODE){
								var index = (parentBlock.children.length) ? parentBlock.children.length -1 : 0;
								if(!parentBlock.children[index]){
									parentBlock.children[index] = {};
								}
								parentBlock.children[index][child.name] = this.children[child.name];
							}else{
								parentBlock.children[child.name] = this.children[child.name];
							}
						}
					}
				}else{
					var index = (this.children.length) ? this.children.length  -1 : 0;
					if(!this.children[index]){
						this.children[index] = {};
					}
					this.children[index][child.name] = child;
				}
			}

			this.afterAddChild(child);

		}

		this.addAttribute = function(child){
			this.attributes[child.name] = child;
			this.addNode(child, true);
		}

		this.get = function(){
			return _domPointer;
		}

		this.onSetData = function(data){

				//set children to false if no data is given
			for(var name in this.children){
				if(Mold.isArray(this.children[name])){
					var len = this.children[name].length, i = 0;
					for(; i < len; i++){
						var selected = this.children[name][i];

						if(selected.type === BLOCK_NODE){
							//if type is a blocknode add parent data
							if(data){
								selected.setData(data);
							}else{
								selected.setData(false);
							}
						}else{
							if(selected.hasParentValue && data[selected.parentName] &&  data[selected.parentName][selected.childName]){
								selected.setData(data[selected.parentName][selected.childName]);
							}else if(data[name]){
								selected.setData(data[name]);
							}else{
								selected.setData("");
							}

						}
					}
				}else{

					if(this.children[name].type === BLOCK_NODE){
						//if type is a blocknode add parent data
						if(data){
							this.children[name].setData(data);
						}else{
							this.children[name].setData(false);
						}
					}else{
						var selected = this.children[name];
						if(selected.hasParentValue && data[selected.parentName] &&  data[selected.parentName][selected.childName]){
							selected.setData(data[selected.parentName][selected.childName]);
						}else if(data[name]){
							this.children[name].setData(data[name]);
						}else{
							this.children[name].setData("");
						}
					}

				}
			}
		}

		this.renderParentDom = function(){
			var parent = this.parent;
			var isDom = false;
			while(parent){
				isDom = (parent.type === 5) ? true : false;
				if(isDom) {
					break;
				}
				parent = parent.parent;
			}
			parent.render()
		}

		this.setNodeData = function(nodeName, data, bind){
			if(this.children[nodeName]){
				if(Mold.isArray(this.children[nodeName])){
					var i = 0, len = this.children[nodeName].length;
					for(; i < len; i++){
						this.children[nodeName][i].setData(data, bind)
					}
				}else{
					this.children[nodeName].setData(data, bind)
				}
			}
		}

		this.setData = function(data){

			if(typeof this.data === "string" && this.data === data){
				this.state = STATE_NO_CHANGES;
			}else if(this.state === STATE_NO_CHANGES){
				this.state = STATE_UPDATE;
			}

			this.data = data;
			this.onSetData(data);

		}

		this.renderString = function(){
			throw new Error("renderString ist not implemented!")
		}

	}
)<commit_msg>reRender method added<commit_after>Seed({
		name : "Mold.Lib.VDom.ProtoNode",
		dna : "data",
		include : [
			"Mold.Lib.VDom.VDoc",
			"Mold.Lib.Filter",
			"Mold.Lib.Observer"
		]
	},
	function(){

		var STATE_RENDER = "render";
		var STATE_NEW = "new";
		var STATE_REMOVE = "remove";
		var STATE_NO_CHANGES = "no changes";
		var STATE_UPDATE = "update";

		var VALUE_NODE = 1;
		var BLOCK_NODE = 2;
		var NEGATIVE_BLOCK_NODE = 3;
		var DOM_NODE = 5;
		var TEXT_NODE = 6;
		var ATTRIBUTE_NODE = 6;
		var STRING_NODE = 8;
		var ROOT_NODE = 9;

		var _doc = Mold.Lib.VDom.VDoc;

		if(!config.name){
			throw new Error("Name must be specified!")
		}

		var _vDom = config.vdom || [];
		var _that = this;
		var _oldData = false;

		this.children = this.children || {};
		this.data = config.data || false;
		this.name = config.name;
		this.type = STRING_NODE;
		this.parent = false;
		this.parentElement = false;
		this.state = STATE_NEW;
		this.isString = config.isString || false;
		this.hasBinding = false;
		this._id = Mold.getId();
		this.services = config.services || false;
		this.template = config.template || false;

		this.vdom = _vDom;
		this.protoChild = {};

		this.renderDom = false;

		this.afterAddChild = function(child){

		}

		this.addNode = function(child, addAttribute){

			if(!addAttribute){
				_vDom.push(child);
			}

			child.parent = _that;
			child.services = this.services;

			if(
				child.type === BLOCK_NODE
				|| child.type === VALUE_NODE
				|| child.type === NEGATIVE_BLOCK_NODE
			){

				//if current node is not a block-node add child to next block-node
				if(this.type !== BLOCK_NODE){
					if(this.children[child.name]){
						//if there are two nodes with the same name create an array
						this.children[child.name] = [this.children[child.name]]
						this.children[child.name].push(child);
					}else{
						this.children[child.name] = child;
					}
					var parentBlock = this.parent;
					if(parentBlock){
						while(parentBlock.type !== BLOCK_NODE && parentBlock.parent){
							parentBlock = parentBlock.parent;
						}

						if(parentBlock){
							if(parentBlock.type === BLOCK_NODE){
								var index = (parentBlock.children.length) ? parentBlock.children.length -1 : 0;
								if(!parentBlock.children[index]){
									parentBlock.children[index] = {};
								}
								parentBlock.children[index][child.name] = this.children[child.name];
							}else{
								parentBlock.children[child.name] = this.children[child.name];
							}
						}
					}
				}else{
					var index = (this.children.length) ? this.children.length  -1 : 0;
					if(!this.children[index]){
						this.children[index] = {};
					}
					this.children[index][child.name] = child;
				}
			}

			this.afterAddChild(child);

		}

		this.addAttribute = function(child){
			this.attributes[child.name] = child;
			this.addNode(child, true);
		}

		this.get = function(){
			return _domPointer;
		}

		this.onSetData = function(data){

				//set children to false if no data is given
			for(var name in this.children){
				if(Mold.isArray(this.children[name])){
					var len = this.children[name].length, i = 0;
					for(; i < len; i++){
						var selected = this.children[name][i];

						if(selected.type === BLOCK_NODE){
							//if type is a blocknode add parent data
							if(data){
								selected.setData(data);
							}else{
								selected.setData(false);
							}
						}else{
							if(selected.hasParentValue && data[selected.parentName] &&  data[selected.parentName][selected.childName]){
								selected.setData(data[selected.parentName][selected.childName]);
							}else if(data[name]){
								selected.setData(data[name]);
							}else{
								selected.setData("");
							}

						}
					}
				}else{

					if(this.children[name].type === BLOCK_NODE){
						//if type is a blocknode add parent data
						if(data){
							this.children[name].setData(data);
						}else{
							this.children[name].setData(false);
						}
					}else{
						var selected = this.children[name];
						if(selected.hasParentValue && data[selected.parentName] &&  data[selected.parentName][selected.childName]){
							selected.setData(data[selected.parentName][selected.childName]);
						}else if(data[name]){
							this.children[name].setData(data[name]);
						}else{
							this.children[name].setData("");
						}
					}

				}
			}
		}

		this.renderParentDom = function(){
			var parent = this.parent;
			var isDom = false;
			while(parent){
				isDom = (parent.type === 5) ? true : false;
				if(isDom) {
					break;
				}
				parent = parent.parent;
			}
			parent.render()
		}

		this.setNodeData = function(nodeName, data, bind){
			if(this.children[nodeName]){
				if(Mold.isArray(this.children[nodeName])){
					var i = 0, len = this.children[nodeName].length;
					for(; i < len; i++){
						this.children[nodeName][i].setData(data, bind)
					}
				}else{
					this.children[nodeName].setData(data, bind)
				}
			}
		}

		this.setData = function(data){

			if(typeof this.data === "string" && this.data === data){
				this.state = STATE_NO_CHANGES;
			}else if(this.state === STATE_NO_CHANGES){
				this.state = STATE_UPDATE;
			}

			this.data = data;
			this.onSetData(data);

		}

		this.renderString = function(){
			throw new Error("renderString ist not implemented!")
		}

		this.reRender = function(){
			throw new Error("reRender ist not implemented!")
		}

	}
)<|endoftext|>


<commit_before>const pontuations = require('../src/pontuations')

test('"Muito simples" must return 30', () => {
    const payload = 'Muito simples'
    const expected = 30

    const result = pontuations(payload).points
    expect(result).toBe(expected);
});

test('"Simples" must return 75', () => {
    const payload = 'Simples'
    const expected = 75

    const result = pontuations(payload).points
    expect(result).toBe(expected);
});

test('"Média" must return 160', () => {
    const payload = 'Média'
    const expected = 160

    const result = pontuations(payload).points
    expect(result).toBe(expected);
});

test('"Difícil" must return 320', () => {
    const payload = 'Difícil'
    const expected = 320

    const result = pontuations(payload).points
    expect(result).toBe(expected);
});

test('"Muito difícil" must return 560', () => {
    const payload = 'Muito difícil'
    const expected = 560

    const result = pontuations(payload).points
    expect(result).toBe(expected);
});

test('"Anything" must return 30', () => {
    const payload = 'Anything'
    const expected = 30

    const result = pontuations(payload).points
    expect(result).toBe(expected);
});

<commit_msg>Tests to pontuations slug<commit_after>const pontuations = require('../src/pontuations')

describe('Issue: Very simple', () => {
    test('"Muito simples" must have "VS" as slug', () => {
        const payload = 'Muito simples'
        const expected = 'VS'

        const result = pontuations(payload).slug
        expect(result).toBe(expected)
    });

    test('"Muito simples" must return 30', () => {
        const payload = 'Muito simples'
        const expected = 30

        const result = pontuations(payload).points
        expect(result).toBe(expected)
    });
})

describe('Issue: Simple', () => {
    test('"Simples" must have "S" as slug', () => {
        const payload = 'Simples'
        const expected = 'S'

        const result = pontuations(payload).slug
        expect(result).toBe(expected)
    })

     test('"Simples" must return 75', () => {
        const payload = 'Simples'
        const expected = 75

        const result = pontuations(payload).points
        expect(result).toBe(expected)
    })
})

describe('Issue: Média', () => {
    test('"Média" must have "M" as slug', () => {
        const payload = 'Média'
        const expected = 'M'

        const result = pontuations(payload).slug
        expect(result).toBe(expected)
    })

    test('"Média" must return 160', () => {
        const payload = 'Média'
        const expected = 160

        const result = pontuations(payload).points
        expect(result).toBe(expected)
    })
})

describe('Issue: Difícil', () => {
    test('"Difícil" must have "D" as slug', () => {
        const payload = 'Difícil'
        const expected = 'H'

        const result = pontuations(payload).slug
        expect(result).toBe(expected)
    })

    test('"Difícil" must return 320', () => {
        const payload = 'Difícil'
        const expected = 320

        const result = pontuations(payload).points
        expect(result).toBe(expected)
    })
})

describe('Issue: Muito Difícil', () => {
    test('"Muito Difícil" must have "D" as slug', () => {
        const payload = 'Muito difícil'
        const expected = 'VH'

        const result = pontuations(payload).slug
        expect(result).toBe(expected)
    })

    test('"Muito difícil" must return 560', () => {
        const payload = 'Muito difícil'
        const expected = 560

        const result = pontuations(payload).points
        expect(result).toBe(expected)
    })
})

describe('Issue: Não classificado', () => {
    test('"Não classificado" must have "NC" as slug', () => {
        const payload = 'Não classificado'
        const expected = 'NC'

        const result = pontuations(payload).slug
        expect(result).toBe(expected)
    })

    test('"Não classificado" must return 30', () => {
        const payload = 'Não classificado'
        const expected = 30

        const result = pontuations(payload).points
        expect(result).toBe(expected)
    })
})

test('"Anything" must return as "Não classificado"', () => {
    const payload = 'Anything'
    const expectedPoints = 30
    const expectedSlug = 'NC'

    const actualPoints = pontuations(payload).points
    expect(actualPoints).toBe(expectedPoints)

    const actualSlug = pontuations(payload).slug
    expect(actualSlug).toBe(expectedSlug)

})

<|endoftext|>


<commit_before>// -> str -> str | Error
const optAlias = opts => opt => {
  const cleanOpt = opt.replace(':', '')
  const optKeys = Object.keys(opts)
  if (!opts[cleanOpt] || !opts[cleanOpt]['alias']) return opt
  else return ':' + opts[cleanOpt]['alias']
}

/**
 * @function argvToFormatStr
 * @param  {object} opts - Options passed to yargs
 * @param  {object} argv - Output of yargs
 * @return {string} With tokens to be populated. Eg ":bar :eta"
 */
const argvToFormatStr = opts => argv => {
  if (argv.format) {
    return argv.format
      // /g flag calls optAlias with each match
      .replace(/:[a-z]{1}\b/g, optAlias(opts))
  }
  else {
    const optsStr = Object.keys(argv)
      .filter(x => x.length === 1) // in only options aliases
      .filter(x => x !== 'no-file')
      .filter(x => argv[x]) // in the ones with truthy values
      .filter(x => x !== '_') // out yargs' "_"
      .join(' ')

    const defaultOrder = 't b p r a e'
    return defaultOrder.split(' ')
      .map(x => optsStr.match(x) ? ':' + opts[x]['alias'] : null)
      .filter(x => x)
      .join(' ')
  }
}

module.exports = {optAlias, argvToFormatStr}
<commit_msg>added formatDevInfo and devName fns<commit_after>// -> str -> str | Error
const optAlias = opts => opt => {
  const cleanOpt = opt.replace(':', '')
  const optKeys = Object.keys(opts)
  if (!opts[cleanOpt] || !opts[cleanOpt]['alias']) return opt
  else return ':' + opts[cleanOpt]['alias']
}

/**
 * @function argvToFormatStr
 * @param  {object} opts - Options passed to yargs
 * @param  {object} argv - Output of yargs
 * @return {string} With tokens to be populated. Eg ":bar :eta"
 */
const argvToFormatStr = opts => argv => {
  if (argv.format) {
    return argv.format
      // /g flag calls optAlias with each match
      .replace(/:[a-z]{1}\b/g, optAlias(opts))
  }
  else {
    const optsStr = Object.keys(argv)
      .filter(x => x.length === 1) // in only options aliases
      .filter(x => x !== 'no-file')
      .filter(x => argv[x]) // in the ones with truthy values
      .filter(x => x !== '_') // out yargs' "_"
      .join(' ')

    const defaultOrder = 't b p r a e'
    return defaultOrder.split(' ')
      .map(x => optsStr.match(x) ? ':' + opts[x]['alias'] : null)
      .filter(x => x)
      .join(' ')
  }
}

/**
 * @function formatDevInfo
 * @param  {Array<Object>} devInfo
 * @return {Array<String>}
 */
const formatDevInfo = devInfo =>
  devInfo.reduce((acc, cur) => {
    const partitions = cur.partitions.map(x => {
      const lab = x.label || 'No_label'
      return `${x.name} ${lab} ${x.size} in ${cur.vendor} ${cur.model}`
    })
    return [...acc, ...partitions]
  }, [])

/**
 * @function devName
 * @param  {String} str device info
 * @return {String} device full path
 */
const devName = str =>
  str.match(/sd[a-z]{1}\d{1,}/)[0]

module.exports = {
  optAlias,
  argvToFormatStr,
  formatDevInfo,
  devName
}<|endoftext|>


<commit_before>// @flow
import hotPath from '../hot-path'
import menubar from 'menubar'
import {injectReactQueryParams} from '../../util/dev'
import {screen as electronScreen, ipcMain, systemPreferences, app} from 'electron'
import {isDarwin, isWindows, isLinux} from '../../constants/platform'
import {resolveImage, resolveRootAsURL} from '../resolve-root'
import {showDevTools, skipSecondaryDevtools} from '../../local-debug.desktop'

import type {BadgeType} from '../../constants/notifications'

let iconType: BadgeType = 'regular'

const isDarkMode = () => isDarwin && systemPreferences && systemPreferences.isDarkMode()

const getIcon = invertColors => {
  const devMode = __DEV__ ? '-dev' : ''
  let color = 'white'
  let platform = ''

  if (isDarwin) {
    color = isDarkMode() ? 'white' : 'black'
  } else if (isWindows) {
    color = 'black'
    platform = 'windows-'
  }

  const size = isWindows ? 16 : 22

  color = invertColors ? {black: 'white', white: 'black'}[color] : color

  return resolveImage(
    'menubarIcon',
    `icon-${platform}keybase-menubar-${iconType}-${color}-${size}${devMode}@2x.png`
  )
}

export default function() {
  const mb = menubar({
    index: resolveRootAsURL('renderer', injectReactQueryParams('renderer.html?menubar')),
    width: 320,
    height: 350,
    resizable: false,
    hasShadow: true,
    transparent: true,
    preloadWindow: true,
    icon: getIcon(false),
    // Without this flag set, menubar will hide the dock icon when the app
    // ready event fires. We manage the dock icon ourselves, so this flag
    // prevents menubar from changing the state.
    showDockIcon: true,
  })

  const updateIcon = invertColors => {
    mb.tray.setImage(getIcon(invertColors))
  }

  if (isDarwin && systemPreferences && systemPreferences.subscribeNotification) {
    systemPreferences.subscribeNotification('AppleInterfaceThemeChangedNotification', () => {
      updateIcon(false)
    })
  }

  ipcMain.on('showTray', (event, type, count) => {
    iconType = type
    updateIcon(false)
    if (app.dock && app.dock.isVisible()) {
      app.setBadgeCount(count)
    }
  })

  // We keep the listeners so we can cleanup on hot-reload
  const menubarListeners = []

  ipcMain.on('unsubscribeMenubar', event => {
    const index = menubarListeners.indexOf(event.sender)
    if (index !== -1) {
      menubarListeners.splice(index, 1)
    }
  })

  ipcMain.on('subscribeMenubar', event => {
    menubarListeners.push(event.sender)
  })

  ipcMain.on('closeMenubar', () => {
    mb.hideWindow()
  })

  mb.on('ready', () => {
    // Hack: open widget when left/right/double clicked
    mb.tray.on('right-click', (e, bounds) => {
      e.preventDefault()
      setImmediate(() => mb.tray.emit('click', {...e}, {...bounds}))
    })
    mb.tray.on('double-click', e => e.preventDefault())

    const webContents = mb.window.webContents
    webContents.on('did-finish-load', () => {
      webContents.send('load', {
        scripts: [
          ...(__DEV__
            ? [
                {
                  src: resolveRootAsURL('dist', 'dll/dll.vendor.js'),
                  async: false,
                },
                {
                  src: hotPath('common-chunks.js'),
                  async: false,
                },
              ]
            : []),
          {
            src: hotPath('launcher.bundle.js'),
            async: false,
          },
        ],
        selectorParams: 'menubar',
      })
    })

    if (showDevTools && !skipSecondaryDevtools) {
      webContents.openDevTools('detach')
    }

    // prevent the menubar's window from dying when we quit
    // We remove any existing listeners to close because menubar has one that deletes the reference to mb.window
    mb.window.removeAllListeners('close')
    mb.window.on('close', event => {
      event.preventDefault()
      mb.hideWindow()
    })

    if (isLinux) {
      mb.tray.setToolTip('Show Keybase')
    }

    mb.on('show', () => {
      // Account for different taskbar positions on Windows
      if (isWindows) {
        const cursorPoint = electronScreen.getCursorScreenPoint()
        const screenSize = electronScreen.getDisplayNearestPoint(cursorPoint).workArea
        if (screenSize.x > 0) {
          // start menu on left
          mb.setOption('windowPosition', 'trayBottomLeft')
        } else if (screenSize.y > 0) {
          // start menu on top
          mb.setOption('windowPosition', 'trayRight')
        } else if (cursorPoint.x > screenSize.x) {
          // start menu on right
          mb.setOption('windowPosition', 'bottomRight')
        } else {
          // start menu on bottom
          mb.setOption('windowPosition', 'trayBottomCenter')
        }
      }

      menubarListeners.forEach(l => l.send('menubarShow'))
      isDarwin && updateIcon(!isDarkMode())
    })
    mb.on('hide', () => {
      menubarListeners.forEach(l => l.send('menubarHide'))
      isDarwin && updateIcon(false)
    })
  })

  // Work around an OS X bug that leaves a gap in the status bar if you exit
  // without removing your status bar icon.
  if (isDarwin) {
    mb.app.on('before-quit', () => {
      mb.tray && mb.tray.destroy()
    })
  }
}
<commit_msg>add some logging around tray menu (#8729)<commit_after>// @flow
import hotPath from '../hot-path'
import menubar from 'menubar'
import {injectReactQueryParams} from '../../util/dev'
import {screen as electronScreen, ipcMain, systemPreferences, app} from 'electron'
import {isDarwin, isWindows, isLinux} from '../../constants/platform'
import {resolveImage, resolveRootAsURL} from '../resolve-root'
import {showDevTools, skipSecondaryDevtools} from '../../local-debug.desktop'

import type {BadgeType} from '../../constants/notifications'

let iconType: BadgeType = 'regular'

const isDarkMode = () => isDarwin && systemPreferences && systemPreferences.isDarkMode()

const getIcon = invertColors => {
  const devMode = __DEV__ ? '-dev' : ''
  let color = 'white'
  let platform = ''

  if (isDarwin) {
    color = isDarkMode() ? 'white' : 'black'
  } else if (isWindows) {
    color = 'black'
    platform = 'windows-'
  }

  const size = isWindows ? 16 : 22

  color = invertColors ? {black: 'white', white: 'black'}[color] : color

  return resolveImage(
    'menubarIcon',
    `icon-${platform}keybase-menubar-${iconType}-${color}-${size}${devMode}@2x.png`
  )
}

export default function() {
  const mb = menubar({
    index: resolveRootAsURL('renderer', injectReactQueryParams('renderer.html?menubar')),
    width: 320,
    height: 350,
    resizable: false,
    hasShadow: true,
    transparent: true,
    preloadWindow: true,
    icon: getIcon(false),
    // Without this flag set, menubar will hide the dock icon when the app
    // ready event fires. We manage the dock icon ourselves, so this flag
    // prevents menubar from changing the state.
    showDockIcon: true,
  })

  const updateIcon = invertColors => {
    mb.tray.setImage(getIcon(invertColors))
  }

  if (isDarwin && systemPreferences && systemPreferences.subscribeNotification) {
    systemPreferences.subscribeNotification('AppleInterfaceThemeChangedNotification', () => {
      updateIcon(false)
    })
  }

  ipcMain.on('showTray', (event, type, count) => {
    iconType = type
    updateIcon(false)
    if (app.dock && app.dock.isVisible()) {
      app.setBadgeCount(count)
    }
  })

  // We keep the listeners so we can cleanup on hot-reload
  const menubarListeners = []

  ipcMain.on('unsubscribeMenubar', event => {
    const index = menubarListeners.indexOf(event.sender)
    if (index !== -1) {
      menubarListeners.splice(index, 1)
    }
  })

  ipcMain.on('subscribeMenubar', event => {
    menubarListeners.push(event.sender)
  })

  ipcMain.on('closeMenubar', () => {
    mb.hideWindow()
  })

  mb.on('ready', () => {
    // Hack: open widget when left/right/double clicked
    mb.tray.on('right-click', (e, bounds) => {
      e.preventDefault()
      setImmediate(() => mb.tray.emit('click', {...e}, {...bounds}))
    })
    mb.tray.on('double-click', e => e.preventDefault())

    const webContents = mb.window.webContents
    webContents.on('did-finish-load', () => {
      webContents.send('load', {
        scripts: [
          ...(__DEV__
            ? [
                {
                  src: resolveRootAsURL('dist', 'dll/dll.vendor.js'),
                  async: false,
                },
                {
                  src: hotPath('common-chunks.js'),
                  async: false,
                },
              ]
            : []),
          {
            src: hotPath('launcher.bundle.js'),
            async: false,
          },
        ],
        selectorParams: 'menubar',
      })
    })

    if (showDevTools && !skipSecondaryDevtools) {
      webContents.openDevTools('detach')
    }

    // prevent the menubar's window from dying when we quit
    // We remove any existing listeners to close because menubar has one that deletes the reference to mb.window
    mb.window.removeAllListeners('close')
    mb.window.on('close', event => {
      event.preventDefault()
      mb.hideWindow()
    })

    if (isLinux) {
      mb.tray.setToolTip('Show Keybase')
    }

    mb.on('show', () => {
      // Account for different taskbar positions on Windows
      if (isWindows) {
        const cursorPoint = electronScreen.getCursorScreenPoint()
        const screenSize = electronScreen.getDisplayNearestPoint(cursorPoint).workArea
        if (screenSize.x > 0) {
          // start menu on left
          mb.setOption('windowPosition', 'trayBottomLeft')
        } else if (screenSize.y > 0) {
          // start menu on top
          mb.setOption('windowPosition', 'trayRight')
        } else if (cursorPoint.x > screenSize.x) {
          // start menu on right
          mb.setOption('windowPosition', 'bottomRight')
        } else {
          // start menu on bottom
          mb.setOption('windowPosition', 'trayBottomCenter')
        }
      }

      menubarListeners.forEach(l => l.send('menubarShow'))
      isDarwin && updateIcon(!isDarkMode())
    })
    mb.on('hide', () => {
      menubarListeners.forEach(l => l.send('menubarHide'))
      isDarwin && updateIcon(false)
    })
    mb.on('after-show', () => {
      console.log('Showing menubar at', mb.window && mb.window.getBounds())
    })
    mb.tray.on('click', (e, bounds) => {
      console.log('Clicked tray icon:', bounds)
    })
  })

  // Work around an OS X bug that leaves a gap in the status bar if you exit
  // without removing your status bar icon.
  if (isDarwin) {
    mb.app.on('before-quit', () => {
      mb.tray && mb.tray.destroy()
    })
  }
}
<|endoftext|>


<commit_before>var CBI_VERSION = "Casio Basic Interpreter 0.1.8.x";
var CBI_BUILD_DATE = "2014-10-08";

var TEXT_SCREEN_WIDTH = 21;
var TEXT_SCREEN_HEIGHT = 7;

function cbiGetVersion(withBuildDate) {
  toReturn = CBI_VERSION;
  if (withBuildDate) {
    toReturn += ' (built: '+CBI_BUILD_DATE+')';
  }
  return toReturn;
}

var nextLine = NaN; // index in the programLines array

var textScreenLines = new Array();
var idTimerMain = 0;

var currentLineBuffer = null;

function calcHandleOnKeyDown(e) {

  // Disable back button acting like history previous / back
  var doPrevent = false;
  if (event.keyCode === 8) {
    var d = event.srcElement || event.target;
    if ((d.tagName.toUpperCase() === 'INPUT' && (d.type.toUpperCase() === 'TEXT' || d.type.toUpperCase() === 'PASSWORD'))
         || d.tagName.toUpperCase() === 'TEXTAREA') {
        doPrevent = d.readOnly || d.disabled;
    } else {
      doPrevent = true;
    }
  }
  if (doPrevent) {
    event.preventDefault();
  }

  if ((e.keyCode==8 || e.keyCode==46) && editMode && currentLineBuffer.length>0) {
    currentLineBuffer = currentLineBuffer.substring(0,currentLineBuffer.length-1);
    cursorMode = " "; clignoteCurseur(); // Clear old position
    drawTextLine(textScreenLines.length,currentLineBuffer+" ");
    //if (cursorCol>1) { cursorCol--; }
    cursorCol--;
    cursorMode = "_"; clignoteCurseur(); // Cursor at new pos
  }

  if (e.keyCode==13 && editMode) { // 13 is "ENTER / CARRIAGE RETURN"
    editModeOff();

    /* Un-pause programe execution */
    paused = false;
    idTimerMain = setTimeout('executeNextLine()',10);
  }

}

function reset() {
  editMode = false;
  paused = false;
  stockVarName = ""; // Destination of input
  cursorMode = "_";
  cursorCol = 1;
  cursorLine = 1;
  currentLineBuffer = null;
  programLines = new Array();
  programLabels = new Array();
  nextLine = NaN; // index in the programLines array
  textScreenLines = new Array();
  clearInterval(idTimerMain); idTimerMain = 0;
  clearInterval(idTimerCursor); idTimerCursor = 0;
}

var editMode = false;
var paused = false;
var stockVarName = ""; // Destination of input
var cursorMode = "_";
var cursorCol = 1;
var cursorLine = 1;
var idTimerCursor;

function editModeOn() {
  console.log("editModeOn");
  editMode = true;
  currentLineBuffer = "";
  print("");
  currentLineIndex = textScreenLines.length - 1;
  cursorLine = textScreenLines.length;
  cursorCol = 1;
  idTimerCursor = setInterval('clignoteCurseur()',500);
}

function editModeOff() {
  console.log("editModeOff");
  editMode = false;
  if (currentLineBuffer=="") { // If line is empty when exit edit mode, remove line from textscreenline
    textScreenLines.pop();
  } else {

  }
  letvar(stockVarName, parseFloat(currentLineBuffer));
  currentLineBuffer = null;
  clearInterval(idTimerCursor);
  cursorMode = " "; clignoteCurseur(); // Clear old position
}

function clignoteCurseur() {
  var charW = 6;
  var charH = 8;
  var y = (cursorLine-1) * charH + 1;
  var x = (cursorCol-1) * charW + 1;
  ctx.drawImage(imageObj, cursorMode.charCodeAt(0)*6, 0, charW, charH, x, y, charW, charH);
  if (cursorMode == "_") {
    cursorMode = " ";
  } else {
    cursorMode = "_";
  }
}

function calcHandleOnKeyPress(e) {
  if (editMode) {
    var charCode = e.charCode;
    if (charCode==46 || (charCode >= 48 && charCode <= 57)) {
      var currentLineIndex = textScreenLines.length - 1;
      if (currentLineBuffer!==null && currentLineBuffer.length<20) {
        currentLineBuffer += String.fromCharCode(charCode);
        textScreenLines[currentLineIndex] = currentLineBuffer;
        drawTextLine(currentLineIndex+1,currentLineBuffer);
        cursorCol+=1;
      }
    }
  }
}

//Interpreting functions

// Clear the graphic screen
function cls() {
  ctx.fillStyle="#FFFFFF";
  ctx.fillRect(1,1,127,63);
}

// Redraw all screen
function redrawAllTextScreen() {
  cls();
  for (var i=0; i<textScreenLines.length; i++) {
    lineNb = i+1;
    drawTextLine(lineNb,textScreenLines[i]);
  }
}

function print(str) {
  str += " ";
  while (str.length>TEXT_SCREEN_WIDTH) {
    textScreenLines.push(str.substring(0,TEXT_SCREEN_WIDTH));
    str = str.substring(TEXT_SCREEN_WIDTH);
  }
  textScreenLines.push(str);
  while (textScreenLines.length > TEXT_SCREEN_HEIGHT) {
    textScreenLines.shift();
  }
  redrawAllTextScreen();
}

function locate(col,ligne,str) {
  if (col<1 || col>21) return; // Should generate a runtimeError, do nothing for now !
  if (ligne<1 || ligne>7) return; // Should generate a runtimeError, do nothing for now !
  while (textScreenLines.length < ligne) {
    textScreenLines.push("                       ");
  }
  currentLine = textScreenLines[ligne-1];
  if (currentLine.length<col-1) {
    currentLine = currentLine + "                       ".substring(0,(col-1)-currentLine.length);
  }
  newLine = currentLine.substring(0,col-1) + str + currentLine.substring(col-1+str.length);
  textScreenLines[ligne-1] = newLine;
  redrawAllTextScreen();
}

function cleartext() {
  console.log("cleartext called !");
  textScreenLines = new Array();
  redrawAllTextScreen();
}

function drawTextLine(lineNb,str) {
  imageObj = document.getElementById('casioFont');
  var charW = 6;
  var charH = 8;
  var y = (lineNb-1) * charH + 1;
  var x = 0;
  str = str.substring(0,21); // 21 first char
  for (var i=0; i<str.length; i++) {
    x = i * 6 + 1;
    ctx.drawImage(imageObj, str.charCodeAt(i)*6, 0, charW, charH, x, y, charW, charH);
  }
}

var plots = Array();
var xmin = 1;
var xmax = 127;
var xscl = 0;
var ymin = 1;
var ymax = 63;
var yscl = 0;

function setPixel(x,y) {
  x = Math.round(x);
  y = Math.round(y);
  ctx.fillStyle = "black";
  ctx.fillRect(x,y,1,1);
}

// draw a line using "Bresenham's line algorithm"
function bline(x0, y0, x1, y1) {
  x0 = Math.round(x0);
  y0 = Math.round(y0);
  x1 = Math.round(x1);
  y1 = Math.round(y1);
  ctx.fillStyle = "black";
  var dx = Math.abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
  var dy = Math.abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
  var err = (dx>dy ? dx : -dy)/2;

  while (true) {
    setPixel(x0,y0);
    if (x0 === x1 && y0 === y1) break;
    var e2 = err;
    if (e2 > -dx) { err -= dy; x0 += sx; }
    if (e2 < dy) { err += dx; y0 += sy; }
  }
}

function plot(x, y) {
  plots.push([x,y]);
  if (plots.length>2) {
    plots.shift();
  }
  letvar("A_24", x);
  letvar("A_25", y);
  setPixel(xtoR(x), ytoR(y));
}

function range(xmin,xmax,xscl,ymin,ymax,yscl) {
  this.xmin = xmin;
  this.xmax = xmax;
  this.xscl = xscl;
  this.ymin = ymin;
  this.ymax = ymax;
  this.yscl = yscl;
}

function xtoR(x) {
  return ((x-this.xmin)*(this.casioScreenW-1)/(this.xmax-this.xmin))+1;
}

function ytoR(y) {
  return ((this.casioScreenH-1)-((y-this.ymin)*(this.casioScreenH-1)/(this.ymax-this.ymin))+1);
}

function line() {
  bline(xtoR(plots[0][0]),ytoR(plots[0][1]),xtoR(plots[1][0]),ytoR(plots[1][1]));
}

// Reset all vars to 0
function mcl() {
	for(i=0;i<v_values.length;i++) {
  	v_values[i] = 0;
  }
}

<commit_msg>Update build date<commit_after>var CBI_VERSION = "Casio Basic Interpreter 0.1.8.x";
var CBI_BUILD_DATE = "2014-10-10";

var TEXT_SCREEN_WIDTH = 21;
var TEXT_SCREEN_HEIGHT = 7;

function cbiGetVersion(withBuildDate) {
  toReturn = CBI_VERSION;
  if (withBuildDate) {
    toReturn += ' (built: '+CBI_BUILD_DATE+')';
  }
  return toReturn;
}

var nextLine = NaN; // index in the programLines array

var textScreenLines = new Array();
var idTimerMain = 0;

var currentLineBuffer = null;

function calcHandleOnKeyDown(e) {

  // Disable back button acting like history previous / back
  var doPrevent = false;
  if (event.keyCode === 8) {
    var d = event.srcElement || event.target;
    if ((d.tagName.toUpperCase() === 'INPUT' && (d.type.toUpperCase() === 'TEXT' || d.type.toUpperCase() === 'PASSWORD'))
         || d.tagName.toUpperCase() === 'TEXTAREA') {
        doPrevent = d.readOnly || d.disabled;
    } else {
      doPrevent = true;
    }
  }
  if (doPrevent) {
    event.preventDefault();
  }

  if ((e.keyCode==8 || e.keyCode==46) && editMode && currentLineBuffer.length>0) {
    currentLineBuffer = currentLineBuffer.substring(0,currentLineBuffer.length-1);
    cursorMode = " "; clignoteCurseur(); // Clear old position
    drawTextLine(textScreenLines.length,currentLineBuffer+" ");
    //if (cursorCol>1) { cursorCol--; }
    cursorCol--;
    cursorMode = "_"; clignoteCurseur(); // Cursor at new pos
  }

  if (e.keyCode==13 && editMode) { // 13 is "ENTER / CARRIAGE RETURN"
    editModeOff();

    /* Un-pause programe execution */
    paused = false;
    idTimerMain = setTimeout('executeNextLine()',10);
  }

}

function reset() {
  editMode = false;
  paused = false;
  stockVarName = ""; // Destination of input
  cursorMode = "_";
  cursorCol = 1;
  cursorLine = 1;
  currentLineBuffer = null;
  programLines = new Array();
  programLabels = new Array();
  nextLine = NaN; // index in the programLines array
  textScreenLines = new Array();
  clearInterval(idTimerMain); idTimerMain = 0;
  clearInterval(idTimerCursor); idTimerCursor = 0;
}

var editMode = false;
var paused = false;
var stockVarName = ""; // Destination of input
var cursorMode = "_";
var cursorCol = 1;
var cursorLine = 1;
var idTimerCursor;

function editModeOn() {
  console.log("editModeOn");
  editMode = true;
  currentLineBuffer = "";
  print("");
  currentLineIndex = textScreenLines.length - 1;
  cursorLine = textScreenLines.length;
  cursorCol = 1;
  idTimerCursor = setInterval('clignoteCurseur()',500);
}

function editModeOff() {
  console.log("editModeOff");
  editMode = false;
  if (currentLineBuffer=="") { // If line is empty when exit edit mode, remove line from textscreenline
    textScreenLines.pop();
  } else {

  }
  letvar(stockVarName, parseFloat(currentLineBuffer));
  currentLineBuffer = null;
  clearInterval(idTimerCursor);
  cursorMode = " "; clignoteCurseur(); // Clear old position
}

function clignoteCurseur() {
  var charW = 6;
  var charH = 8;
  var y = (cursorLine-1) * charH + 1;
  var x = (cursorCol-1) * charW + 1;
  ctx.drawImage(imageObj, cursorMode.charCodeAt(0)*6, 0, charW, charH, x, y, charW, charH);
  if (cursorMode == "_") {
    cursorMode = " ";
  } else {
    cursorMode = "_";
  }
}

function calcHandleOnKeyPress(e) {
  if (editMode) {
    var charCode = e.charCode;
    if (charCode==46 || (charCode >= 48 && charCode <= 57)) {
      var currentLineIndex = textScreenLines.length - 1;
      if (currentLineBuffer!==null && currentLineBuffer.length<20) {
        currentLineBuffer += String.fromCharCode(charCode);
        textScreenLines[currentLineIndex] = currentLineBuffer;
        drawTextLine(currentLineIndex+1,currentLineBuffer);
        cursorCol+=1;
      }
    }
  }
}

//Interpreting functions

// Clear the graphic screen
function cls() {
  ctx.fillStyle="#FFFFFF";
  ctx.fillRect(1,1,127,63);
}

// Redraw all screen
function redrawAllTextScreen() {
  cls();
  for (var i=0; i<textScreenLines.length; i++) {
    lineNb = i+1;
    drawTextLine(lineNb,textScreenLines[i]);
  }
}

function print(str) {
  str += " ";
  while (str.length>TEXT_SCREEN_WIDTH) {
    textScreenLines.push(str.substring(0,TEXT_SCREEN_WIDTH));
    str = str.substring(TEXT_SCREEN_WIDTH);
  }
  textScreenLines.push(str);
  while (textScreenLines.length > TEXT_SCREEN_HEIGHT) {
    textScreenLines.shift();
  }
  redrawAllTextScreen();
}

function locate(col,ligne,str) {
  if (col<1 || col>21) return; // Should generate a runtimeError, do nothing for now !
  if (ligne<1 || ligne>7) return; // Should generate a runtimeError, do nothing for now !
  while (textScreenLines.length < ligne) {
    textScreenLines.push("                       ");
  }
  currentLine = textScreenLines[ligne-1];
  if (currentLine.length<col-1) {
    currentLine = currentLine + "                       ".substring(0,(col-1)-currentLine.length);
  }
  newLine = currentLine.substring(0,col-1) + str + currentLine.substring(col-1+str.length);
  textScreenLines[ligne-1] = newLine;
  redrawAllTextScreen();
}

function cleartext() {
  console.log("cleartext called !");
  textScreenLines = new Array();
  redrawAllTextScreen();
}

function drawTextLine(lineNb,str) {
  imageObj = document.getElementById('casioFont');
  var charW = 6;
  var charH = 8;
  var y = (lineNb-1) * charH + 1;
  var x = 0;
  str = str.substring(0,21); // 21 first char
  for (var i=0; i<str.length; i++) {
    x = i * 6 + 1;
    ctx.drawImage(imageObj, str.charCodeAt(i)*6, 0, charW, charH, x, y, charW, charH);
  }
}

var plots = Array();
var xmin = 1;
var xmax = 127;
var xscl = 0;
var ymin = 1;
var ymax = 63;
var yscl = 0;

function setPixel(x,y) {
  x = Math.round(x);
  y = Math.round(y);
  ctx.fillStyle = "black";
  ctx.fillRect(x,y,1,1);
}

// draw a line using "Bresenham's line algorithm"
function bline(x0, y0, x1, y1) {
  x0 = Math.round(x0);
  y0 = Math.round(y0);
  x1 = Math.round(x1);
  y1 = Math.round(y1);
  ctx.fillStyle = "black";
  var dx = Math.abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
  var dy = Math.abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
  var err = (dx>dy ? dx : -dy)/2;

  while (true) {
    setPixel(x0,y0);
    if (x0 === x1 && y0 === y1) break;
    var e2 = err;
    if (e2 > -dx) { err -= dy; x0 += sx; }
    if (e2 < dy) { err += dx; y0 += sy; }
  }
}

function plot(x, y) {
  plots.push([x,y]);
  if (plots.length>2) {
    plots.shift();
  }
  letvar("A_24", x);
  letvar("A_25", y);
  setPixel(xtoR(x), ytoR(y));
}

function range(xmin,xmax,xscl,ymin,ymax,yscl) {
  this.xmin = xmin;
  this.xmax = xmax;
  this.xscl = xscl;
  this.ymin = ymin;
  this.ymax = ymax;
  this.yscl = yscl;
}

function xtoR(x) {
  return ((x-this.xmin)*(this.casioScreenW-1)/(this.xmax-this.xmin))+1;
}

function ytoR(y) {
  return ((this.casioScreenH-1)-((y-this.ymin)*(this.casioScreenH-1)/(this.ymax-this.ymin))+1);
}

function line() {
  bline(xtoR(plots[0][0]),ytoR(plots[0][1]),xtoR(plots[1][0]),ytoR(plots[1][1]));
}

// Reset all vars to 0
function mcl() {
	for(i=0;i<v_values.length;i++) {
  	v_values[i] = 0;
  }
}

<|endoftext|>