<commit_before>import { options } from 'preact';

/** @type {number} */
let currentIndex;

/** @type {import('./internal').Component} */
let currentComponent;

/** @type {Array<import('./internal').Component>} */
let afterPaintEffects = [];

/** @type {Array<import('./internal').Component>} */
let layoutEffects = [];

let oldBeforeRender = options._render;
options._render = vnode => {
	if (oldBeforeRender) oldBeforeRender(vnode);

	currentComponent = vnode._component;
	currentIndex = 0;

	if (currentComponent.__hooks) {
		currentComponent.__hooks._pendingEffects = handleEffects(currentComponent.__hooks._pendingEffects);
	}
};

let oldCommit = options._commit;
options._commit = vnode => {
	if (oldCommit) oldCommit(vnode);
	flushLayoutEffects();
}

let oldBeforeUnmount = options.unmount;
options.unmount = vnode => {
	if (oldBeforeUnmount) oldBeforeUnmount(vnode);

	const c = vnode._component;
	if (!c) return;

	const hooks = c.__hooks;
	if (hooks) {
		hooks._list.forEach(hook => hook._cleanup && hook._cleanup());
	}
};

/**
 * Get a hook's state from the currentComponent
 * @param {number} index The index of the hook to get
 * @returns {import('./internal').HookState}
 */
function getHookState(index) {
	if (options._hook) options._hook(currentComponent);
	// Largely inspired by:
	// * https://github.com/michael-klein/funcy.js/blob/f6be73468e6ec46b0ff5aa3cc4c9baf72a29025a/src/hooks/core_hooks.mjs
	// * https://github.com/michael-klein/funcy.js/blob/650beaa58c43c33a74820a3c98b3c7079cf2e333/src/renderer.mjs
	// Other implementations to look at:
	// * https://codesandbox.io/s/mnox05qp8
	const hooks = currentComponent.__hooks || (currentComponent.__hooks = { _list: [], _pendingEffects: [], _pendingLayoutEffects: [] });

	if (index >= hooks._list.length) {
		hooks._list.push({});
	}
	return hooks._list[index];
}

/**
 * @param {import('./index').StateUpdater<any>} initialState
 */
export function useState(initialState) {
	return useReducer(invokeOrReturn, initialState);
}

/**
 * @param {import('./index').Reducer<any, any>} reducer
 * @param {import('./index').StateUpdater<any>} initialState
 * @param {(initialState: any) => void} [init]
 * @returns {[ any, (state: any) => void ]}
 */
export function useReducer(reducer, initialState, init) {

	/** @type {import('./internal').ReducerHookState} */
	const hookState = getHookState(currentIndex++);
	if (!hookState._component) {
		hookState._component = currentComponent;

		hookState._value = [
			!init ? invokeOrReturn(undefined, initialState) : init(initialState),

			action => {
				const nextValue = reducer(hookState._value[0], action);
				if (hookState._value[0]!==nextValue) {
					hookState._value[0] = nextValue;
					hookState._component.setState({});
				}
			}
		];
	}

	return hookState._value;
}

/**
 * @param {import('./internal').Effect} callback
 * @param {any[]} args
 */
export function useEffect(callback, args) {

	/** @type {import('./internal').EffectHookState} */
	const state = getHookState(currentIndex++);
	if (argsChanged(state._args, args)) {
		state._value = callback;
		state._args = args;

		currentComponent.__hooks._pendingEffects.push(state);
		afterPaint(currentComponent);
	}
}

/**
 * @param {import('./internal').Effect} callback
 * @param {any[]} args
 */
export function useLayoutEffect(callback, args) {

	/** @type {import('./internal').EffectHookState} */
	const state = getHookState(currentIndex++);
	if (argsChanged(state._args, args)) {
		state._value = callback;
		state._args = args;
		currentComponent.__hooks._pendingLayoutEffects.push(state);
		if(!currentComponent._layoutEffectsQueued) {
			currentComponent._layoutEffectsQueued = layoutEffects.push(currentComponent);
		}
	}
}

export function useRef(initialValue) {
	return useMemo(() => ({ current: initialValue }), []);
}

/**
 * @param {object} ref
 * @param {() => object} createHandle
 * @param {any[]} args
 */
export function useImperativeHandle(ref, createHandle, args) {
	useLayoutEffect(() => {
		if (typeof ref === 'function') ref(createHandle());
		else if (ref) ref.current = createHandle();
	}, args == null ? args : args.concat(ref));
}

/**
 * @param {() => any} callback
 * @param {any[]} args
 */
export function useMemo(callback, args) {

	/** @type {import('./internal').MemoHookState} */
	const state = getHookState(currentIndex++);
	if (argsChanged(state._args, args)) {
		state._args = args;
		state._callback = callback;
		return state._value = callback();
	}

	return state._value;
}

/**
 * @param {() => void} callback
 * @param {any[]} args
 */
export function useCallback(callback, args) {
	return useMemo(() => callback, args);
}

/**
 * @param {import('./internal').PreactContext} context
 */
export function useContext(context) {
	const provider = currentComponent.context[context._id];
	if (!provider) return context._defaultValue;
	const state = getHookState(currentIndex++);
	// This is probably not safe to convert to "!"
	if (state._value == null) {
		state._value = true;
		provider.sub(currentComponent);
	}
	return provider.props.value;
}

/**
 * Display a custom label for a custom hook for the devtools panel
 * @type {<T>(value: T, cb?: (value: T) => string | number) => void}
 */
export function useDebugValue(value, formatter) {
	if (options.useDebugValue) {
		options.useDebugValue(formatter ? formatter(value) : value);
	}
}

// Note: if someone used Component.debounce = requestAnimationFrame,
// then effects will ALWAYS run on the NEXT frame instead of the current one, incurring a ~16ms delay.
// Perhaps this is not such a big deal.
/**
 * Invoke a component's pending effects after the next frame renders
 * @type {(component: import('./internal').Component) => void}
 */
/* istanbul ignore next */
let afterPaint = () => {};

/**
 * Layout effects consumer
 */
function flushLayoutEffects() {
	layoutEffects.some(component => {
		component._layoutEffectsQueued = 0;
		component.__hooks._pendingLayoutEffects = handleEffects(component.__hooks._pendingLayoutEffects);
	});
	layoutEffects = [];
}

/**
 * After paint effects consumer.
 */
function flushAfterPaintEffects() {
	afterPaintEffects.some(component => {
		component._afterPaintQueued = 0;
		if (component._parentDom) {
			component.__hooks._pendingEffects = handleEffects(component.__hooks._pendingEffects);
		}
	});
	afterPaintEffects = [];
}

const RAF_TIMEOUT = 100;

/**
 * Schedule a callback to be invoked after the browser has a chance to paint a new frame.
 * Do this by combining requestAnimationFrame (rAF) + setTimeout to invoke a callback after
 * the next browser frame.
 *
 * Also, schedule a timeout in parallel to the the rAF to ensure the callback is invoked
 * even if RAF doesn't fire (for example if the browser tab is not visible)
 */
function afterNextFrame(callback) {
	const done = () => {
		clearTimeout(timeout);
		cancelAnimationFrame(raf);
		setTimeout(callback);
	};
	const timeout = setTimeout(done, RAF_TIMEOUT);
	const raf = requestAnimationFrame(done);
}

/* istanbul ignore else */
if (typeof window !== 'undefined') {
	let prevRaf = options.requestAnimationFrame;
	afterPaint = (component) => {
		if (
			(!component._afterPaintQueued && (component._afterPaintQueued = afterPaintEffects.push(component)) === 1)
			|| prevRaf !== options.requestAnimationFrame
		) {
			prevRaf = options.requestAnimationFrame;

			/* istanbul ignore next */
			(prevRaf || afterNextFrame)(flushAfterPaintEffects);
		}
	};
}

/**
 * @param {import('./internal').EffectHookState[]} effects
 */
function handleEffects(effects) {
	effects.forEach(invokeCleanup);
	effects.forEach(invokeEffect);
	return [];
}

/**
 * @param {import('./internal').EffectHookState} hook
 */
function invokeCleanup(hook) {
	if (hook._cleanup) hook._cleanup();
}

/**
 * Invoke a Hook's effect
 * @param {import('./internal').EffectHookState} hook
 */
function invokeEffect(hook) {
	const result = hook._value();
	if (typeof result === 'function') hook._cleanup = result;
}

/**
 * @param {any[]} oldArgs
 * @param {any[]} newArgs
 */
function argsChanged(oldArgs, newArgs) {
	return !oldArgs || newArgs.some((arg, index) => arg !== oldArgs[index]);
}

function invokeOrReturn(arg, f) {
	return typeof f === 'function' ? f(arg) : f;
}
<commit_msg>Reverse the effect queues before running them (+8 B)<commit_after>import { options } from 'preact';

/** @type {number} */
let currentIndex;

/** @type {import('./internal').Component} */
let currentComponent;

/** @type {Array<import('./internal').Component>} */
let afterPaintEffects = [];

/** @type {Array<import('./internal').Component>} */
let layoutEffects = [];

let oldBeforeRender = options._render;
options._render = vnode => {
	if (oldBeforeRender) oldBeforeRender(vnode);

	currentComponent = vnode._component;
	currentIndex = 0;

	if (currentComponent.__hooks) {
		currentComponent.__hooks._pendingEffects = handleEffects(currentComponent.__hooks._pendingEffects);
	}
};

let oldCommit = options._commit;
options._commit = vnode => {
	if (oldCommit) oldCommit(vnode);
	flushLayoutEffects();
}

let oldBeforeUnmount = options.unmount;
options.unmount = vnode => {
	if (oldBeforeUnmount) oldBeforeUnmount(vnode);

	const c = vnode._component;
	if (!c) return;

	const hooks = c.__hooks;
	if (hooks) {
		hooks._list.forEach(hook => hook._cleanup && hook._cleanup());
	}
};

/**
 * Get a hook's state from the currentComponent
 * @param {number} index The index of the hook to get
 * @returns {import('./internal').HookState}
 */
function getHookState(index) {
	if (options._hook) options._hook(currentComponent);
	// Largely inspired by:
	// * https://github.com/michael-klein/funcy.js/blob/f6be73468e6ec46b0ff5aa3cc4c9baf72a29025a/src/hooks/core_hooks.mjs
	// * https://github.com/michael-klein/funcy.js/blob/650beaa58c43c33a74820a3c98b3c7079cf2e333/src/renderer.mjs
	// Other implementations to look at:
	// * https://codesandbox.io/s/mnox05qp8
	const hooks = currentComponent.__hooks || (currentComponent.__hooks = { _list: [], _pendingEffects: [], _pendingLayoutEffects: [] });

	if (index >= hooks._list.length) {
		hooks._list.push({});
	}
	return hooks._list[index];
}

/**
 * @param {import('./index').StateUpdater<any>} initialState
 */
export function useState(initialState) {
	return useReducer(invokeOrReturn, initialState);
}

/**
 * @param {import('./index').Reducer<any, any>} reducer
 * @param {import('./index').StateUpdater<any>} initialState
 * @param {(initialState: any) => void} [init]
 * @returns {[ any, (state: any) => void ]}
 */
export function useReducer(reducer, initialState, init) {

	/** @type {import('./internal').ReducerHookState} */
	const hookState = getHookState(currentIndex++);
	if (!hookState._component) {
		hookState._component = currentComponent;

		hookState._value = [
			!init ? invokeOrReturn(undefined, initialState) : init(initialState),

			action => {
				const nextValue = reducer(hookState._value[0], action);
				if (hookState._value[0]!==nextValue) {
					hookState._value[0] = nextValue;
					hookState._component.setState({});
				}
			}
		];
	}

	return hookState._value;
}

/**
 * @param {import('./internal').Effect} callback
 * @param {any[]} args
 */
export function useEffect(callback, args) {

	/** @type {import('./internal').EffectHookState} */
	const state = getHookState(currentIndex++);
	if (argsChanged(state._args, args)) {
		state._value = callback;
		state._args = args;

		currentComponent.__hooks._pendingEffects.push(state);
		afterPaint(currentComponent);
	}
}

/**
 * @param {import('./internal').Effect} callback
 * @param {any[]} args
 */
export function useLayoutEffect(callback, args) {

	/** @type {import('./internal').EffectHookState} */
	const state = getHookState(currentIndex++);
	if (argsChanged(state._args, args)) {
		state._value = callback;
		state._args = args;
		currentComponent.__hooks._pendingLayoutEffects.push(state);
		if(!currentComponent._layoutEffectsQueued) {
			currentComponent._layoutEffectsQueued = layoutEffects.push(currentComponent);
		}
	}
}

export function useRef(initialValue) {
	return useMemo(() => ({ current: initialValue }), []);
}

/**
 * @param {object} ref
 * @param {() => object} createHandle
 * @param {any[]} args
 */
export function useImperativeHandle(ref, createHandle, args) {
	useLayoutEffect(() => {
		if (typeof ref === 'function') ref(createHandle());
		else if (ref) ref.current = createHandle();
	}, args == null ? args : args.concat(ref));
}

/**
 * @param {() => any} callback
 * @param {any[]} args
 */
export function useMemo(callback, args) {

	/** @type {import('./internal').MemoHookState} */
	const state = getHookState(currentIndex++);
	if (argsChanged(state._args, args)) {
		state._args = args;
		state._callback = callback;
		return state._value = callback();
	}

	return state._value;
}

/**
 * @param {() => void} callback
 * @param {any[]} args
 */
export function useCallback(callback, args) {
	return useMemo(() => callback, args);
}

/**
 * @param {import('./internal').PreactContext} context
 */
export function useContext(context) {
	const provider = currentComponent.context[context._id];
	if (!provider) return context._defaultValue;
	const state = getHookState(currentIndex++);
	// This is probably not safe to convert to "!"
	if (state._value == null) {
		state._value = true;
		provider.sub(currentComponent);
	}
	return provider.props.value;
}

/**
 * Display a custom label for a custom hook for the devtools panel
 * @type {<T>(value: T, cb?: (value: T) => string | number) => void}
 */
export function useDebugValue(value, formatter) {
	if (options.useDebugValue) {
		options.useDebugValue(formatter ? formatter(value) : value);
	}
}

// Note: if someone used Component.debounce = requestAnimationFrame,
// then effects will ALWAYS run on the NEXT frame instead of the current one, incurring a ~16ms delay.
// Perhaps this is not such a big deal.
/**
 * Invoke a component's pending effects after the next frame renders
 * @type {(component: import('./internal').Component) => void}
 */
/* istanbul ignore next */
let afterPaint = () => {};

/**
 * Layout effects consumer
 */
function flushLayoutEffects() {
	layoutEffects.reverse().some(component => {
		component._layoutEffectsQueued = 0;
		component.__hooks._pendingLayoutEffects = handleEffects(component.__hooks._pendingLayoutEffects);
	});
	layoutEffects = [];
}

/**
 * After paint effects consumer.
 */
function flushAfterPaintEffects() {
	afterPaintEffects.reverse().some(component => {
		component._afterPaintQueued = 0;
		if (component._parentDom) {
			component.__hooks._pendingEffects = handleEffects(component.__hooks._pendingEffects);
		}
	});
	afterPaintEffects = [];
}

const RAF_TIMEOUT = 100;

/**
 * Schedule a callback to be invoked after the browser has a chance to paint a new frame.
 * Do this by combining requestAnimationFrame (rAF) + setTimeout to invoke a callback after
 * the next browser frame.
 *
 * Also, schedule a timeout in parallel to the the rAF to ensure the callback is invoked
 * even if RAF doesn't fire (for example if the browser tab is not visible)
 */
function afterNextFrame(callback) {
	const done = () => {
		clearTimeout(timeout);
		cancelAnimationFrame(raf);
		setTimeout(callback);
	};
	const timeout = setTimeout(done, RAF_TIMEOUT);
	const raf = requestAnimationFrame(done);
}

/* istanbul ignore else */
if (typeof window !== 'undefined') {
	let prevRaf = options.requestAnimationFrame;
	afterPaint = (component) => {
		if (
			(!component._afterPaintQueued && (component._afterPaintQueued = afterPaintEffects.push(component)) === 1)
			|| prevRaf !== options.requestAnimationFrame
		) {
			prevRaf = options.requestAnimationFrame;

			/* istanbul ignore next */
			(prevRaf || afterNextFrame)(flushAfterPaintEffects);
		}
	};
}

/**
 * @param {import('./internal').EffectHookState[]} effects
 */
function handleEffects(effects) {
	effects.forEach(invokeCleanup);
	effects.forEach(invokeEffect);
	return [];
}

/**
 * @param {import('./internal').EffectHookState} hook
 */
function invokeCleanup(hook) {
	if (hook._cleanup) hook._cleanup();
}

/**
 * Invoke a Hook's effect
 * @param {import('./internal').EffectHookState} hook
 */
function invokeEffect(hook) {
	const result = hook._value();
	if (typeof result === 'function') hook._cleanup = result;
}

/**
 * @param {any[]} oldArgs
 * @param {any[]} newArgs
 */
function argsChanged(oldArgs, newArgs) {
	return !oldArgs || newArgs.some((arg, index) => arg !== oldArgs[index]);
}

function invokeOrReturn(arg, f) {
	return typeof f === 'function' ? f(arg) : f;
}
<|endoftext|>


<commit_before>var _ = require('underscore')
    , q = require('q')
    , AWS = require('aws-sdk')
    , archiver = require('archiver')
    , util = require('util')
    , path = require('path')
    , fs = require('fs')
    , config = require('./configuration')
    , s3utils = require('./s3utils');

module.exports.createArchive = function(destinationName, sourcePath, callback) {
    var deferred;

    if (typeof callback !== 'function') {
        callback = function() {};
        deferred = q.defer();
    }

    if (!path.extname(destinationName)) {
        destinationName += '.tgz';
    }

    var tempdir = '/tmp/';
    var destinationPath = path.join(tempdir, destinationName);

    if (destinationPath.indexOf(tempdir) !== 0) {
        throw new Error('createArchive: destinationName should not try to exit its sandbox');
    }

    var output = fs.createWriteStream(destinationPath);
    var archive = archiver('tar', {
        gzip: true,
    });

    output.on('close', function() {
        console.log(archive.pointer() + ' total bytes');
        console.log('archiver has been finalized and the output file descriptor has closed.');
        callback(null, destinationPath);
        deferred && deferred.resolve(destinationPath);
    });

    archive.on('error', function(err) {
        callback(err);
        deferred && deferred.reject(err);
    });

    archive.pipe(output);

    archive
        .directory(sourcePath)
        .finalize();

    return deferred ? deferred.promise : undefined;
};

module.exports.deployArchive = function(sourcePath, callback) {
    var deferred;

    if (typeof callback !== 'function') {
        callback = function() {};
        deferred = q.defer();
    }

    var sourceStream = fs.createReadStream(sourcePath);

    var destinationKeyName = path.basename(sourcePath);

    var bucketname = config.s3.bucket;
    var region = config.s3.region;
    var deploymentDateString = config.currentDeployment.date.format();
    var deploymentId = config.currentDeployment.id;
    var keypath = util.format('%s%s/%s/%s/artifacts/%s',
        config.s3.keyPrefix,
        config.currentDeployment.ref.project,
        config.currentDeployment.ref.component,
        deploymentId,
        destinationKeyName);

    var params = {
        Bucket: bucketname,
        Key: keypath,
        Body: sourceStream,
    };

    var s3 = new AWS.S3({ region : region });
    s3.upload(params, function(err, data) {
        if (err) {
            callback(err);
            deferred && deferred.reject(err);
            return;
        }
        var url = s3utils.urlForUploadParams(region, params);
        var result = {
            bucket: bucketname,
            key: keypath,
            url: url,
        };
        callback(null, result);
        deferred && deferred.resolve(result);
    });
};
<commit_msg>Fixed generated .tgz file<commit_after>var _ = require('underscore')
    , q = require('q')
    , AWS = require('aws-sdk')
    , archiver = require('archiver')
    , util = require('util')
    , path = require('path')
    , fs = require('fs')
    , config = require('./configuration')
    , s3utils = require('./s3utils');

module.exports.createArchive = function(destinationName, sourcePath, callback) {
    var deferred;

    if (typeof callback !== 'function') {
        callback = function() {};
        deferred = q.defer();
    }

    if (!path.extname(destinationName)) {
        destinationName += '.tgz';
    }

    var tempdir = '/tmp/';
    var destinationPath = path.join(tempdir, destinationName);

    if (destinationPath.indexOf(tempdir) !== 0) {
        throw new Error('createArchive: destinationName should not try to exit its sandbox');
    }

    var output = fs.createWriteStream(destinationPath);
    var archive = archiver('tar', {
        gzip: true,
    });

    output.on('close', function() {
        console.log(archive.pointer() + ' total bytes');
        console.log('archiver has been finalized and the output file descriptor has closed.');
        callback(null, destinationPath);
        deferred && deferred.resolve(destinationPath);
    });

    archive.on('error', function(err) {
        callback(err);
        deferred && deferred.reject(err);
    });

    archive.pipe(output);

    archive
        .directory(sourcePath, false)
        .finalize();

    return deferred ? deferred.promise : undefined;
};

module.exports.deployArchive = function(sourcePath, callback) {
    var deferred;

    if (typeof callback !== 'function') {
        callback = function() {};
        deferred = q.defer();
    }

    var sourceStream = fs.createReadStream(sourcePath);

    var destinationKeyName = path.basename(sourcePath);

    var bucketname = config.s3.bucket;
    var region = config.s3.region;
    var deploymentDateString = config.currentDeployment.date.format();
    var deploymentId = config.currentDeployment.id;
    var keypath = util.format('%s%s/%s/%s/artifacts/%s',
        config.s3.keyPrefix,
        config.currentDeployment.ref.project,
        config.currentDeployment.ref.component,
        deploymentId,
        destinationKeyName);

    var params = {
        Bucket: bucketname,
        Key: keypath,
        Body: sourceStream,
    };

    var s3 = new AWS.S3({ region : region });
    s3.upload(params, function(err, data) {
        if (err) {
            callback(err);
            deferred && deferred.reject(err);
            return;
        }
        var url = s3utils.urlForUploadParams(region, params);
        var result = {
            bucket: bucketname,
            key: keypath,
            url: url,
        };
        callback(null, result);
        deferred && deferred.resolve(result);
    });
};
<|endoftext|>


<commit_before>import { assert } from 'chai';
import sinon from 'sinon';
import Cell from '../../src/Cell';

describe('Cell', () => {
  it('Should properly create cell with default arguments', () => {
    const cell = new Cell(' ', {x: 0, y: 10});

    assert.instanceOf(cell, Cell);
    assert.equal(cell._x, 0);
    assert.equal(cell._y, 10);
    assert.notOk(cell._background);
    assert.notOk(cell._foreground);
    assert.notOk(cell._display);
  });

  it('Should properly get/set char', () => {
    const cell = new Cell(' ', {x: 0, y: 10});

    assert.equal(cell.getChar(), ' ');
    assert.instanceOf(cell.setChar('t'), Cell);
    assert.equal(cell.getChar(), 't');
    assert.instanceOf(cell.setChar('long text'), Cell);
    assert.equal(cell.getChar(), 'l');
  });

  it('Should properly get/set X coordinate', () => {
    const cell = new Cell(' ', {x: 0, y: 10});

    assert.equal(cell.getX(), 0);
    assert.instanceOf(cell.setX(40), Cell);
    assert.equal(cell.getX(), 40);
    assert.instanceOf(cell.setX(50.99), Cell);
    assert.equal(cell.getX(), 50);
  });

  it('Should properly get/set Y coordinate', () => {
    const cell = new Cell(' ', {x: 0, y: 10});

    assert.equal(cell.getY(), 10);
    assert.instanceOf(cell.setY(40), Cell);
    assert.equal(cell.getY(), 40);
    assert.instanceOf(cell.setY(50.99), Cell);
    assert.equal(cell.getY(), 50);
  });

  it('Should properly get/set background color', () => {
    const cell = new Cell(' ', {x: 0, y: 10});

    assert.notOk(cell.getBackground());
    assert.instanceOf(cell.setBackground({r: 0, g: 100, b: 200}), Cell);
    assert.deepEqual(cell.getBackground(), {r: 0, g: 100, b: 200});
    assert.instanceOf(cell.setBackground(false), Cell);
    assert.notOk(cell.getBackground());
  });

  it('Should properly get/set foreground color', () => {
    const cell = new Cell(' ', {x: 0, y: 10});

    assert.notOk(cell.getForeground());
    assert.instanceOf(cell.setForeground({r: 0, g: 100, b: 200}), Cell);
    assert.deepEqual(cell.getForeground(), {r: 0, g: 100, b: 200});
    assert.instanceOf(cell.setForeground(false), Cell);
    assert.notOk(cell.getForeground());
  });

  it('Should properly get/set display modes', () => {
    const cell = new Cell(' ', {x: 0, y: 10});

    assert.notOk(cell.getDisplay());
    assert.instanceOf(cell.setDisplay({bold: true, underlined: true, dim: false}), Cell);
    assert.deepEqual(cell.getDisplay(), {bold: true, underlined: true, dim: false});
    assert.instanceOf(cell.setDisplay(false), Cell);
    assert.notOk(cell.getDisplay());
  });

  it('Should properly convert Cell into ASCII sequence', () => {
    const cell = new Cell(' ', {x: 0, y: 10});

    assert.equal(cell.toString(), '\u001b[11;1f \u001b[0m');
    assert.instanceOf(cell.setBackground({r: 0, g: 100, b: 200}), Cell);
    assert.equal(cell.toString(), '\u001b[11;1f\u001b[48;2;0;100;200m \u001b[0m');
    assert.instanceOf(cell.setForeground({r: 200, g: 100, b: 0}), Cell);
    assert.equal(cell.toString(), '\u001b[11;1f\u001b[48;2;0;100;200m\u001b[38;2;200;100;0m \u001b[0m');
    assert.instanceOf(cell.setDisplay({bold: true, underlined: true, dim: false}), Cell);
    assert.equal(cell.toString(), '\u001b[11;1f\u001b[48;2;0;100;200m\u001b[38;2;200;100;0m\u001b[1m\u001b[4m \u001b[0m');
  });

  it('Should properly create Cell instance from static create()', () => {
    const cell = Cell.create(' ', {x: 0, y: 10});

    assert.instanceOf(cell, Cell);
    assert.equal(cell._x, 0);
    assert.equal(cell._y, 10);
    assert.notOk(cell._background);
    assert.notOk(cell._foreground);
    assert.notOk(cell._display);
  })
});
<commit_msg>test(cell): Add few more tests<commit_after>import { assert } from 'chai';
import sinon from 'sinon';
import Cell from '../../src/Cell';

describe('Cell', () => {
  it('Should properly create cell with default arguments', () => {
    const cell = new Cell(' ', {x: 0, y: 10});

    assert.instanceOf(cell, Cell);
    assert.equal(cell._char, ' ');
    assert.equal(cell._x, 0);
    assert.equal(cell._y, 10);
    assert.notOk(cell._background);
    assert.notOk(cell._foreground);
    assert.notOk(cell._display);
  });

  it('Should properly get/set char', () => {
    const cell = new Cell(' ', {x: 0, y: 10});

    assert.equal(cell.getChar(), ' ');
    assert.instanceOf(cell.setChar('t'), Cell);
    assert.equal(cell.getChar(), 't');
    assert.instanceOf(cell.setChar('long text'), Cell);
    assert.equal(cell.getChar(), 'l');
  });

  it('Should properly get/set X coordinate', () => {
    const cell = new Cell(' ', {x: 0, y: 10});

    assert.equal(cell.getX(), 0);
    assert.instanceOf(cell.setX(40), Cell);
    assert.equal(cell.getX(), 40);
    assert.instanceOf(cell.setX(50.99), Cell);
    assert.equal(cell.getX(), 50);
  });

  it('Should properly get/set Y coordinate', () => {
    const cell = new Cell(' ', {x: 0, y: 10});

    assert.equal(cell.getY(), 10);
    assert.instanceOf(cell.setY(40), Cell);
    assert.equal(cell.getY(), 40);
    assert.instanceOf(cell.setY(50.99), Cell);
    assert.equal(cell.getY(), 50);
  });

  it('Should properly get/set background color', () => {
    const cell = new Cell(' ', {x: 0, y: 10});

    assert.notOk(cell.getBackground());
    assert.instanceOf(cell.setBackground({r: 0, g: 100, b: 200}), Cell);
    assert.deepEqual(cell.getBackground(), {r: 0, g: 100, b: 200});
    assert.instanceOf(cell.setBackground(false), Cell);
    assert.notOk(cell.getBackground());
  });

  it('Should properly get/set foreground color', () => {
    const cell = new Cell(' ', {x: 0, y: 10});

    assert.notOk(cell.getForeground());
    assert.instanceOf(cell.setForeground({r: 0, g: 100, b: 200}), Cell);
    assert.deepEqual(cell.getForeground(), {r: 0, g: 100, b: 200});
    assert.instanceOf(cell.setForeground(false), Cell);
    assert.notOk(cell.getForeground());
  });

  it('Should properly get/set display modes', () => {
    const cell = new Cell(' ', {x: 0, y: 10});

    assert.notOk(cell.getDisplay());
    assert.instanceOf(cell.setDisplay({bold: true, underlined: true, dim: false}), Cell);
    assert.deepEqual(cell.getDisplay(), {bold: true, underlined: true, dim: false});
    assert.instanceOf(cell.setDisplay(false), Cell);
    assert.notOk(cell.getDisplay());
  });

  it('Should properly mark cell as modified', () => {
    const cell = new Cell(' ', {x: 0, y: 10});

    assert.ok(cell.isModified());
    assert.instanceOf(cell.setModified(false), Cell);
    assert.notOk(cell.isModified());
    assert.instanceOf(cell.setModified(), Cell);
    assert.ok(cell.isModified());
  });

  it('Should properly convert Cell into ASCII sequence', () => {
    const cell = new Cell(' ', {x: 0, y: 10});

    assert.equal(cell.toString(), '\u001b[11;1f \u001b[0m');
    assert.instanceOf(cell.setBackground({r: 0, g: 100, b: 200}), Cell);
    assert.equal(cell.toString(), '\u001b[11;1f\u001b[48;2;0;100;200m \u001b[0m');
    assert.instanceOf(cell.setForeground({r: 200, g: 100, b: 0}), Cell);
    assert.equal(cell.toString(), '\u001b[11;1f\u001b[48;2;0;100;200m\u001b[38;2;200;100;0m \u001b[0m');
    assert.instanceOf(cell.setDisplay({bold: true, underlined: true, dim: false}), Cell);
    assert.equal(cell.toString(), '\u001b[11;1f\u001b[48;2;0;100;200m\u001b[38;2;200;100;0m\u001b[1m\u001b[4m \u001b[0m');
  });

  it('Should properly create Cell instance from static create()', () => {
    const cell = Cell.create(' ', {x: 0, y: 10});

    assert.instanceOf(cell, Cell);
    assert.equal(cell._char, ' ');
    assert.equal(cell._x, 0);
    assert.equal(cell._y, 10);
    assert.notOk(cell._background);
    assert.notOk(cell._foreground);
    assert.notOk(cell._display);
  })
});
<|endoftext|>


<commit_before>import { options } from 'preact';

/** @type {number} */
let currentIndex;

/** @type {import('./internal').Component} */
let currentComponent;

/** @type {number} */
let currentHook = 0;

/** @type {Array<import('./internal').Component>} */
let afterPaintEffects = [];

let oldBeforeRender = options._render;
let oldAfterDiff = options.diffed;
let oldCommit = options._commit;
let oldBeforeUnmount = options.unmount;

const RAF_TIMEOUT = 100;
let prevRaf;

options._render = vnode => {
	if (oldBeforeRender) oldBeforeRender(vnode);

	currentComponent = vnode._component;
	currentIndex = 0;

	const hooks = currentComponent.__hooks;
	if (hooks) {
		hooks._pendingEffects.forEach(invokeCleanup);
		hooks._pendingEffects.forEach(invokeEffect);
		hooks._pendingEffects = [];
	}
};

options.diffed = vnode => {
	if (oldAfterDiff) oldAfterDiff(vnode);

	const c = vnode._component;
	if (c && c.__hooks && c.__hooks._pendingEffects.length) {
		afterPaint(afterPaintEffects.push(c));
	}
};

options._commit = (vnode, commitQueue) => {
	commitQueue.some(component => {
		try {
			component._renderCallbacks.forEach(invokeCleanup);
			component._renderCallbacks = component._renderCallbacks.filter(cb =>
				cb._value ? invokeEffect(cb) : true
			);
		} catch (e) {
			commitQueue.some(c => {
				if (c._renderCallbacks) c._renderCallbacks = [];
			});
			commitQueue = [];
			options._catchError(e, component._vnode);
		}
	});

	if (oldCommit) oldCommit(vnode, commitQueue);
};

options.unmount = vnode => {
	if (oldBeforeUnmount) oldBeforeUnmount(vnode);

	const c = vnode._component;
	if (c && c.__hooks) {
		try {
			c.__hooks._list.forEach(hook => hook._cleanup && hook._cleanup());
		} catch (e) {
			options._catchError(e, c._vnode);
		}
	}
};

/**
 * Get a hook's state from the currentComponent
 * @param {number} index The index of the hook to get
 * @param {number} type The index of the hook to get
 * @returns {import('./internal').HookState}
 */
function getHookState(index, type) {
	if (options._hook) {
		options._hook(currentComponent, index, currentHook || type);
	}
	currentHook = 0;

	// Largely inspired by:
	// * https://github.com/michael-klein/funcy.js/blob/f6be73468e6ec46b0ff5aa3cc4c9baf72a29025a/src/hooks/core_hooks.mjs
	// * https://github.com/michael-klein/funcy.js/blob/650beaa58c43c33a74820a3c98b3c7079cf2e333/src/renderer.mjs
	// Other implementations to look at:
	// * https://codesandbox.io/s/mnox05qp8
	const hooks =
		currentComponent.__hooks ||
		(currentComponent.__hooks = {
			_list: [],
			_pendingEffects: []
		});

	if (index >= hooks._list.length) {
		hooks._list.push({});
	}
	return hooks._list[index];
}

/**
 * @param {import('./index').StateUpdater<any>} initialState
 */
export function useState(initialState) {
	currentHook = 1;
	return useReducer(invokeOrReturn, initialState);
}

/**
 * @param {import('./index').Reducer<any, any>} reducer
 * @param {import('./index').StateUpdater<any>} initialState
 * @param {(initialState: any) => void} [init]
 * @returns {[ any, (state: any) => void ]}
 */
export function useReducer(reducer, initialState, init) {
	/** @type {import('./internal').ReducerHookState} */
	const hookState = getHookState(currentIndex++, 2);
	if (!hookState._component) {
		hookState._component = currentComponent;

		hookState._value = [
			!init ? invokeOrReturn(undefined, initialState) : init(initialState),

			action => {
				const nextValue = reducer(hookState._value[0], action);
				if (hookState._value[0] !== nextValue) {
					hookState._value[0] = nextValue;
					hookState._component.setState({});
				}
			}
		];
	}

	return hookState._value;
}

/**
 * @param {import('./internal').Effect} callback
 * @param {any[]} args
 */
export function useEffect(callback, args) {
	/** @type {import('./internal').EffectHookState} */
	const state = getHookState(currentIndex++, 3);
	if (!options._skipEffects && argsChanged(state._args, args)) {
		state._value = callback;
		state._args = args;

		currentComponent.__hooks._pendingEffects.push(state);
	}
}

/**
 * @param {import('./internal').Effect} callback
 * @param {any[]} args
 */
export function useLayoutEffect(callback, args) {
	/** @type {import('./internal').EffectHookState} */
	const state = getHookState(currentIndex++, 4);
	if (!options._skipEffects && argsChanged(state._args, args)) {
		state._value = callback;
		state._args = args;

		currentComponent._renderCallbacks.push(state);
	}
}

export function useRef(initialValue) {
	currentHook = 5;
	return useMemo(() => ({ current: initialValue }), []);
}

/**
 * @param {object} ref
 * @param {() => object} createHandle
 * @param {any[]} args
 */
export function useImperativeHandle(ref, createHandle, args) {
	currentHook = 6;
	useLayoutEffect(
		() => {
			if (typeof ref == 'function') ref(createHandle());
			else if (ref) ref.current = createHandle();
		},
		args == null ? args : args.concat(ref)
	);
}

/**
 * @param {() => any} factory
 * @param {any[]} args
 */
export function useMemo(factory, args) {
	/** @type {import('./internal').MemoHookState} */
	const state = getHookState(currentIndex++, 7);
	if (argsChanged(state._args, args)) {
		state._args = args;
		state._factory = factory;
		return (state._value = factory());
	}

	return state._value;
}

/**
 * @param {() => void} callback
 * @param {any[]} args
 */
export function useCallback(callback, args) {
	currentHook = 8;
	return useMemo(() => callback, args);
}

/**
 * @param {import('./internal').PreactContext} context
 */
export function useContext(context) {
	const provider = currentComponent.context[context._id];
	// We could skip this call here, but than we'd not call
	// `options._hook`. We need to do that in order to make
	// the devtools aware of this hook.
	const state = getHookState(currentIndex++, 9);
	// The devtools needs access to the context object to
	// be able to pull of the default value when no provider
	// is present in the tree.
	state._context = context;
	if (!provider) return context._defaultValue;
	// This is probably not safe to convert to "!"
	if (state._value == null) {
		state._value = true;
		provider.sub(currentComponent);
	}
	return provider.props.value;
}

/**
 * Display a custom label for a custom hook for the devtools panel
 * @type {<T>(value: T, cb?: (value: T) => string | number) => void}
 */
export function useDebugValue(value, formatter) {
	if (options.useDebugValue) {
		options.useDebugValue(formatter ? formatter(value) : value);
	}
}

export function useErrorBoundary(cb) {
	const state = getHookState(currentIndex++, 10);
	const errState = useState();
	state._value = cb;
	if (!currentComponent.componentDidCatch) {
		currentComponent.componentDidCatch = err => {
			if (state._value) state._value(err);
			errState[1](err);
		};
	}
	return [
		errState[0],
		() => {
			errState[1](undefined);
		}
	];
}

/**
 * After paint effects consumer.
 */
function flushAfterPaintEffects() {
	afterPaintEffects.some(component => {
		if (component._parentDom) {
			try {
				component.__hooks._pendingEffects.forEach(invokeCleanup);
				component.__hooks._pendingEffects.forEach(invokeEffect);
				component.__hooks._pendingEffects = [];
			} catch (e) {
				component.__hooks._pendingEffects = [];
				options._catchError(e, component._vnode);
				return true;
			}
		}
	});
	afterPaintEffects = [];
}

/**
 * Schedule a callback to be invoked after the browser has a chance to paint a new frame.
 * Do this by combining requestAnimationFrame (rAF) + setTimeout to invoke a callback after
 * the next browser frame.
 *
 * Also, schedule a timeout in parallel to the the rAF to ensure the callback is invoked
 * even if RAF doesn't fire (for example if the browser tab is not visible)
 *
 * @param {() => void} callback
 */
function afterNextFrame(callback) {
	const done = () => {
		clearTimeout(timeout);
		cancelAnimationFrame(raf);
		setTimeout(callback);
	};
	const timeout = setTimeout(done, RAF_TIMEOUT);

	let raf;
	if (typeof window != 'undefined') {
		raf = requestAnimationFrame(done);
	}
}

// Note: if someone used options.debounceRendering = requestAnimationFrame,
// then effects will ALWAYS run on the NEXT frame instead of the current one, incurring a ~16ms delay.
// Perhaps this is not such a big deal.
/**
 * Schedule afterPaintEffects flush after the browser paints
 * @param {number} newQueueLength
 */
function afterPaint(newQueueLength) {
	if (newQueueLength === 1 || prevRaf !== options.requestAnimationFrame) {
		prevRaf = options.requestAnimationFrame;
		(prevRaf || afterNextFrame)(flushAfterPaintEffects);
	}
}

/**
 * @param {import('./internal').EffectHookState} hook
 */
function invokeCleanup(hook) {
	if (hook._cleanup) hook._cleanup();
}

/**
 * Invoke a Hook's effect
 * @param {import('./internal').EffectHookState} hook
 */
function invokeEffect(hook) {
	const result = hook._value();
	if (typeof result == 'function') hook._cleanup = result;
}

/**
 * @param {any[]} oldArgs
 * @param {any[]} newArgs
 */
function argsChanged(oldArgs, newArgs) {
	return !oldArgs || newArgs.some((arg, index) => arg !== oldArgs[index]);
}

function invokeOrReturn(arg, f) {
	return typeof f == 'function' ? f(arg) : f;
}
<commit_msg>golf effect cleanup (#2494)<commit_after>import { options } from 'preact';

/** @type {number} */
let currentIndex;

/** @type {import('./internal').Component} */
let currentComponent;

/** @type {number} */
let currentHook = 0;

/** @type {Array<import('./internal').Component>} */
let afterPaintEffects = [];

let oldBeforeRender = options._render;
let oldAfterDiff = options.diffed;
let oldCommit = options._commit;
let oldBeforeUnmount = options.unmount;

const RAF_TIMEOUT = 100;
let prevRaf;

options._render = vnode => {
	if (oldBeforeRender) oldBeforeRender(vnode);

	currentComponent = vnode._component;
	currentIndex = 0;

	const hooks = currentComponent.__hooks;
	if (hooks) {
		hooks._pendingEffects.forEach(invokeCleanup);
		hooks._pendingEffects.forEach(invokeEffect);
		hooks._pendingEffects = [];
	}
};

options.diffed = vnode => {
	if (oldAfterDiff) oldAfterDiff(vnode);

	const c = vnode._component;
	if (c && c.__hooks && c.__hooks._pendingEffects.length) {
		afterPaint(afterPaintEffects.push(c));
	}
};

options._commit = (vnode, commitQueue) => {
	commitQueue.some(component => {
		try {
			component._renderCallbacks.forEach(invokeCleanup);
			component._renderCallbacks = component._renderCallbacks.filter(cb =>
				cb._value ? invokeEffect(cb) : true
			);
		} catch (e) {
			commitQueue.some(c => {
				if (c._renderCallbacks) c._renderCallbacks = [];
			});
			commitQueue = [];
			options._catchError(e, component._vnode);
		}
	});

	if (oldCommit) oldCommit(vnode, commitQueue);
};

options.unmount = vnode => {
	if (oldBeforeUnmount) oldBeforeUnmount(vnode);

	const c = vnode._component;
	if (c && c.__hooks) {
		try {
			c.__hooks._list.forEach(hook => hook._cleanup && hook._cleanup());
		} catch (e) {
			options._catchError(e, c._vnode);
		}
	}
};

/**
 * Get a hook's state from the currentComponent
 * @param {number} index The index of the hook to get
 * @param {number} type The index of the hook to get
 * @returns {import('./internal').HookState}
 */
function getHookState(index, type) {
	if (options._hook) {
		options._hook(currentComponent, index, currentHook || type);
	}
	currentHook = 0;

	// Largely inspired by:
	// * https://github.com/michael-klein/funcy.js/blob/f6be73468e6ec46b0ff5aa3cc4c9baf72a29025a/src/hooks/core_hooks.mjs
	// * https://github.com/michael-klein/funcy.js/blob/650beaa58c43c33a74820a3c98b3c7079cf2e333/src/renderer.mjs
	// Other implementations to look at:
	// * https://codesandbox.io/s/mnox05qp8
	const hooks =
		currentComponent.__hooks ||
		(currentComponent.__hooks = {
			_list: [],
			_pendingEffects: []
		});

	if (index >= hooks._list.length) {
		hooks._list.push({});
	}
	return hooks._list[index];
}

/**
 * @param {import('./index').StateUpdater<any>} initialState
 */
export function useState(initialState) {
	currentHook = 1;
	return useReducer(invokeOrReturn, initialState);
}

/**
 * @param {import('./index').Reducer<any, any>} reducer
 * @param {import('./index').StateUpdater<any>} initialState
 * @param {(initialState: any) => void} [init]
 * @returns {[ any, (state: any) => void ]}
 */
export function useReducer(reducer, initialState, init) {
	/** @type {import('./internal').ReducerHookState} */
	const hookState = getHookState(currentIndex++, 2);
	if (!hookState._component) {
		hookState._component = currentComponent;

		hookState._value = [
			!init ? invokeOrReturn(undefined, initialState) : init(initialState),

			action => {
				const nextValue = reducer(hookState._value[0], action);
				if (hookState._value[0] !== nextValue) {
					hookState._value[0] = nextValue;
					hookState._component.setState({});
				}
			}
		];
	}

	return hookState._value;
}

/**
 * @param {import('./internal').Effect} callback
 * @param {any[]} args
 */
export function useEffect(callback, args) {
	/** @type {import('./internal').EffectHookState} */
	const state = getHookState(currentIndex++, 3);
	if (!options._skipEffects && argsChanged(state._args, args)) {
		state._value = callback;
		state._args = args;

		currentComponent.__hooks._pendingEffects.push(state);
	}
}

/**
 * @param {import('./internal').Effect} callback
 * @param {any[]} args
 */
export function useLayoutEffect(callback, args) {
	/** @type {import('./internal').EffectHookState} */
	const state = getHookState(currentIndex++, 4);
	if (!options._skipEffects && argsChanged(state._args, args)) {
		state._value = callback;
		state._args = args;

		currentComponent._renderCallbacks.push(state);
	}
}

export function useRef(initialValue) {
	currentHook = 5;
	return useMemo(() => ({ current: initialValue }), []);
}

/**
 * @param {object} ref
 * @param {() => object} createHandle
 * @param {any[]} args
 */
export function useImperativeHandle(ref, createHandle, args) {
	currentHook = 6;
	useLayoutEffect(
		() => {
			if (typeof ref == 'function') ref(createHandle());
			else if (ref) ref.current = createHandle();
		},
		args == null ? args : args.concat(ref)
	);
}

/**
 * @param {() => any} factory
 * @param {any[]} args
 */
export function useMemo(factory, args) {
	/** @type {import('./internal').MemoHookState} */
	const state = getHookState(currentIndex++, 7);
	if (argsChanged(state._args, args)) {
		state._args = args;
		state._factory = factory;
		return (state._value = factory());
	}

	return state._value;
}

/**
 * @param {() => void} callback
 * @param {any[]} args
 */
export function useCallback(callback, args) {
	currentHook = 8;
	return useMemo(() => callback, args);
}

/**
 * @param {import('./internal').PreactContext} context
 */
export function useContext(context) {
	const provider = currentComponent.context[context._id];
	// We could skip this call here, but than we'd not call
	// `options._hook`. We need to do that in order to make
	// the devtools aware of this hook.
	const state = getHookState(currentIndex++, 9);
	// The devtools needs access to the context object to
	// be able to pull of the default value when no provider
	// is present in the tree.
	state._context = context;
	if (!provider) return context._defaultValue;
	// This is probably not safe to convert to "!"
	if (state._value == null) {
		state._value = true;
		provider.sub(currentComponent);
	}
	return provider.props.value;
}

/**
 * Display a custom label for a custom hook for the devtools panel
 * @type {<T>(value: T, cb?: (value: T) => string | number) => void}
 */
export function useDebugValue(value, formatter) {
	if (options.useDebugValue) {
		options.useDebugValue(formatter ? formatter(value) : value);
	}
}

export function useErrorBoundary(cb) {
	const state = getHookState(currentIndex++, 10);
	const errState = useState();
	state._value = cb;
	if (!currentComponent.componentDidCatch) {
		currentComponent.componentDidCatch = err => {
			if (state._value) state._value(err);
			errState[1](err);
		};
	}
	return [
		errState[0],
		() => {
			errState[1](undefined);
		}
	];
}

/**
 * After paint effects consumer.
 */
function flushAfterPaintEffects() {
	afterPaintEffects.some(component => {
		if (component._parentDom) {
			try {
				component.__hooks._pendingEffects.forEach(invokeCleanup);
				component.__hooks._pendingEffects.forEach(invokeEffect);
				component.__hooks._pendingEffects = [];
			} catch (e) {
				component.__hooks._pendingEffects = [];
				options._catchError(e, component._vnode);
				return true;
			}
		}
	});
	afterPaintEffects = [];
}

/**
 * Schedule a callback to be invoked after the browser has a chance to paint a new frame.
 * Do this by combining requestAnimationFrame (rAF) + setTimeout to invoke a callback after
 * the next browser frame.
 *
 * Also, schedule a timeout in parallel to the the rAF to ensure the callback is invoked
 * even if RAF doesn't fire (for example if the browser tab is not visible)
 *
 * @param {() => void} callback
 */
function afterNextFrame(callback) {
	const done = () => {
		clearTimeout(timeout);
		cancelAnimationFrame(raf);
		setTimeout(callback);
	};
	const timeout = setTimeout(done, RAF_TIMEOUT);

	let raf;
	if (typeof window != 'undefined') {
		raf = requestAnimationFrame(done);
	}
}

// Note: if someone used options.debounceRendering = requestAnimationFrame,
// then effects will ALWAYS run on the NEXT frame instead of the current one, incurring a ~16ms delay.
// Perhaps this is not such a big deal.
/**
 * Schedule afterPaintEffects flush after the browser paints
 * @param {number} newQueueLength
 */
function afterPaint(newQueueLength) {
	if (newQueueLength === 1 || prevRaf !== options.requestAnimationFrame) {
		prevRaf = options.requestAnimationFrame;
		(prevRaf || afterNextFrame)(flushAfterPaintEffects);
	}
}

/**
 * @param {import('./internal').EffectHookState} hook
 */
function invokeCleanup(hook) {
	if (typeof hook._cleanup == 'function') hook._cleanup();
}

/**
 * Invoke a Hook's effect
 * @param {import('./internal').EffectHookState} hook
 */
function invokeEffect(hook) {
	hook._cleanup = hook._value();
}

/**
 * @param {any[]} oldArgs
 * @param {any[]} newArgs
 */
function argsChanged(oldArgs, newArgs) {
	return !oldArgs || newArgs.some((arg, index) => arg !== oldArgs[index]);
}

function invokeOrReturn(arg, f) {
	return typeof f == 'function' ? f(arg) : f;
}
<|endoftext|>


<commit_before>// jshint ignore: start

largeModule('serialize');

var match = function (obj, expect, info) {
    deepEqual(JSON.parse(FIRE.serialize(obj)), expect, info);
};

test('basic test', function() {
    match({}, {}, 'smoke test1');
    match([], [], 'smoke test2');

    var BaseAsset = function () {
        this.inheritProp = 321;
    };

    var MyAsset = (function () {
        var _super = BaseAsset;

        function MyAsset () {
            _super.call(this);

            this.emptyArray = [];
            this.array = [1, '2', {a:3}, [4, [5]], true];
            this.string = 'unknown';
            this.number = 1;
            this.boolean = true;
            this.emptyObj = {};
            this.obj = {};
        }
        FIRE.extend(MyAsset, _super);
        FIRE.registerClass('MyAsset', MyAsset);

        // should not serialize ----------------------------
        MyAsset.staticFunc = function () { };
        MyAsset.staticProp = (function (t) {
            t[t.UseBest    = 0] = 'UseBest';
            t[t.Ascending  = 1] = 'Ascending';
            t[t.Descending = 2] = 'Descending';
            return t;
        })({});
        MyAsset.prototype.protoFunc = function () { };
        MyAsset.prototype.protoProp = 123;
        // -------------------------------------------------

        return MyAsset;
    })();
    var asset = new MyAsset();
    asset.dynamicProp = false;

    var expect = {
        __type__: 'MyAsset',
        emptyArray: [],
        array: [1, '2',  {a:3}, [4, [5]], true],
        string: 'unknown',
        number: 1,
        boolean: true,
        emptyObj: {},
        obj: {},
        dynamicProp: false,
        inheritProp: 321
    };

    match(asset, expect, 'type test');
    match(asset, expect, 'test re-serialize again');

    FIRE.unregisterClass(MyAsset);
});

test('test type derived by FIRE.define', function() {
    var MyAsset = FIRE.define('MyAsset', FIRE.Asset, function () {
                  this.array = [1, '2', {a:3}, [4, [5]], true];
                  })
                      .prop('emptyArray', [])
                      .prop('array', null)
                      .prop('string', 'unknown')
                      .prop('number', 1)
                      .prop('boolean', true)
                      .prop('emptyObj', {})
                      .prop('obj', {});

    // should not serialize ----------------------------
    MyAsset.staticFunc = function () { };
    MyAsset.staticProp = (function (t) {
        t[t.UseBest    = 0] = 'UseBest';
        t[t.Ascending  = 1] = 'Ascending';
        t[t.Descending = 2] = 'Descending';
        return t;
    })({});
    MyAsset.prototype.protoFunc = function () { };
    MyAsset.prototype.protoProp = 123;
    // -------------------------------------------------

    var asset = new MyAsset();
    asset.dynamicProp = false;  // should not serialize

    var expect = {
        __type__: 'MyAsset',
        emptyArray: [],
        array: [1, '2',  {a:3}, [4, [5]], true],
        string: 'unknown',
        number: 1,
        boolean: true,
        emptyObj: {},
        obj: {},
    };

    match(asset, expect, 'type test');

    FIRE.undefine(MyAsset);
});

test('test type created by FIRE.define', function () {
    var Sprite = FIRE.define('Sprite', function () {
        this.image = 'sprite.png';
    })
    Sprite.prop('size', new FIRE.Vec2(128, 128));

    var sprite = new Sprite();
    var actual = JSON.parse(FIRE.serialize(sprite));

    strictEqual(actual.image, undefined, 'should not serialize variable which not defined by property');

    var expected = {
        __type__: 'Sprite',
        size: {
            __type__: "FIRE.Vec2",
            x: 128,
            y: 128
        }
    };

    deepEqual(actual, expected, 'can serialize');

    FIRE.undefine(Sprite);
});

test('test circular reference', function () {
    var MyAsset = (function () {
        var _super = function () {};

        function MyAsset () {
            _super.call(this);
            this.array1 = [1];
            this.array2 = [this.array1, 2];
            this.array1.push(this.array2);
            // array1 = [1, array2]
            // array2 = [array1, 2]
        }
        FIRE.extend(MyAsset, _super);
        FIRE.registerClass('MyAsset', MyAsset);

        return MyAsset;
    })();
    var asset = new MyAsset();

    var expect = [
        {
            __type__: 'MyAsset',
            array1: { __id__: 1 },
            array2: [ { __id__: 1 },  2 ],
        },
        [ 1,  [{ __id__: 1 }, 2] ],  // You'll get two copies of array2
    ];
    match(asset, expect, 'two arrays can circular reference each other');
    match(asset, expect, 'test re-serialize again');
    FIRE.unregisterClass(MyAsset);

    MyAsset = (function () {
        var _super = function () {};

        function MyAsset () {
            _super.call(this);
            this.dict1 = {num: 1};
            this.dict2 = {num: 2, other: this.dict1};
            this.dict1.other = this.dict2;
        }
        FIRE.extend(MyAsset, _super);
        FIRE.registerClass('MyAsset', MyAsset);

        return MyAsset;
    })();
    asset = new MyAsset();

    expect = [
        {
            __type__: 'MyAsset',
            dict1: { __id__: 1 },
            dict2: { /*__id__: 2,*/ num:2, other: {__id__: 1} },
        },
        { /*__id__: 1,*/ num:1, other: {num:2, other: {__id__: 1}} },  // You'll get two copies of dict2
    ];
    match(asset, expect, 'two dicts can circular reference each other');

    //asset.sameRef = asset.dict2;
    //expect[1].sameRef = { __id__: 1 };
    //match(asset, expect, 'more referenced object just serialize its id');

    FIRE.unregisterClass(MyAsset);
});

test('test serializable attributes', function () {
    var Sprite = FIRE.define('Sprite')
                     .prop('trimThreshold', 2, FIRE.EditorOnly)
                     .prop('_isValid', true, FIRE.NonSerialized);

    var sprite = new Sprite();
    var resultInEditor = JSON.parse(FIRE.serialize(sprite));
    var resultInPlayer = JSON.parse(FIRE.serialize(sprite, true));

    strictEqual(resultInEditor.trimThreshold, 2, 'serialize editor only in editor');
    strictEqual(resultInPlayer.trimThreshold, undefined, 'should not serialize editor only in player');

    strictEqual(resultInEditor._isValid, undefined, 'should not serialize non-serialized in editor');
    strictEqual(resultInPlayer._isValid, undefined, 'should not serialize non-serialized in player');

    FIRE.undefine(Sprite);
});

test('test asset property', function () {
    var sprite = new FIRE.Sprite();
    sprite.texture = new FIRE.Texture();
    var uuid = '541020432560';
    sprite.texture._uuid = uuid;

    var result = JSON.parse(FIRE.serialize(sprite));

    deepEqual(result.texture, {__uuid__: uuid}, 'serialize asset as uuid reference');
});

test('test FObject reference', function () {
    var fobj = new FIRE.FObject();
    var asset = { ref1: fobj, ref2: fobj };
    var expected = [
        {
          "ref1": { "__id__": 1 },
          "ref2": { "__id__": 1 }
        },
        { "__type__": "FIRE.FObject" },
    ];
    match(asset, expected, 'references should the same');
});

// jshint ignore: end
<commit_msg>fix serialize unit test error<commit_after>// jshint ignore: start

largeModule('serialize');

var match = function (obj, expect, info) {
    deepEqual(JSON.parse(FIRE.serialize(obj)), expect, info);
};

test('basic test', function() {
    match({}, {}, 'smoke test1');
    match([], [], 'smoke test2');

    var BaseAsset = function () {
        this.inheritProp = 321;
    };

    var MyAsset = (function () {
        var _super = BaseAsset;

        function MyAsset () {
            _super.call(this);

            this.emptyArray = [];
            this.array = [1, '2', {a:3}, [4, [5]], true];
            this.string = 'unknown';
            this.number = 1;
            this.boolean = true;
            this.emptyObj = {};
            this.obj = {};
        }
        FIRE.extend(MyAsset, _super);
        FIRE.registerClass('MyAsset', MyAsset);

        // should not serialize ----------------------------
        MyAsset.staticFunc = function () { };
        MyAsset.staticProp = (function (t) {
            t[t.UseBest    = 0] = 'UseBest';
            t[t.Ascending  = 1] = 'Ascending';
            t[t.Descending = 2] = 'Descending';
            return t;
        })({});
        MyAsset.prototype.protoFunc = function () { };
        MyAsset.prototype.protoProp = 123;
        // -------------------------------------------------

        return MyAsset;
    })();
    var asset = new MyAsset();
    asset.dynamicProp = false;

    var expect = {
        __type__: 'MyAsset',
        emptyArray: [],
        array: [1, '2',  {a:3}, [4, [5]], true],
        string: 'unknown',
        number: 1,
        boolean: true,
        emptyObj: {},
        obj: {},
        dynamicProp: false,
        inheritProp: 321
    };

    match(asset, expect, 'type test');
    match(asset, expect, 'test re-serialize again');

    FIRE.unregisterClass(MyAsset);
});

test('test type derived by FIRE.define', function() {
    var MyAsset = FIRE.define('MyAsset', FIRE.Asset, function () {
                  this.array = [1, '2', {a:3}, [4, [5]], true];
                  })
                      .prop('emptyArray', [])
                      .prop('array', null)
                      .prop('string', 'unknown')
                      .prop('number', 1)
                      .prop('boolean', true)
                      .prop('emptyObj', {})
                      .prop('obj', {});

    // should not serialize ----------------------------
    MyAsset.staticFunc = function () { };
    MyAsset.staticProp = (function (t) {
        t[t.UseBest    = 0] = 'UseBest';
        t[t.Ascending  = 1] = 'Ascending';
        t[t.Descending = 2] = 'Descending';
        return t;
    })({});
    MyAsset.prototype.protoFunc = function () { };
    MyAsset.prototype.protoProp = 123;
    // -------------------------------------------------

    var asset = new MyAsset();
    asset.dynamicProp = false;  // should not serialize

    var expect = {
        __type__: 'MyAsset',
        debugName: "",
        emptyArray: [],
        array: [1, '2',  {a:3}, [4, [5]], true],
        string: 'unknown',
        number: 1,
        boolean: true,
        emptyObj: {},
        obj: {},
    };

    match(asset, expect, 'type test');

    FIRE.undefine(MyAsset);
});

test('test type created by FIRE.define', function () {
    var Sprite = FIRE.define('Sprite', function () {
        this.image = 'sprite.png';
    })
    Sprite.prop('size', new FIRE.Vec2(128, 128));

    var sprite = new Sprite();
    var actual = JSON.parse(FIRE.serialize(sprite));

    strictEqual(actual.image, undefined, 'should not serialize variable which not defined by property');

    var expected = {
        __type__: 'Sprite',
        size: {
            __type__: "FIRE.Vec2",
            x: 128,
            y: 128
        }
    };

    deepEqual(actual, expected, 'can serialize');

    FIRE.undefine(Sprite);
});

test('test circular reference', function () {
    var MyAsset = (function () {
        var _super = function () {};

        function MyAsset () {
            _super.call(this);
            this.array1 = [1];
            this.array2 = [this.array1, 2];
            this.array1.push(this.array2);
            // array1 = [1, array2]
            // array2 = [array1, 2]
        }
        FIRE.extend(MyAsset, _super);
        FIRE.registerClass('MyAsset', MyAsset);

        return MyAsset;
    })();
    var asset = new MyAsset();

    var expect = [
        {
            __type__: 'MyAsset',
            array1: { __id__: 1 },
            array2: [ { __id__: 1 },  2 ],
        },
        [ 1,  [{ __id__: 1 }, 2] ],  // You'll get two copies of array2
    ];
    match(asset, expect, 'two arrays can circular reference each other');
    match(asset, expect, 'test re-serialize again');
    FIRE.unregisterClass(MyAsset);

    MyAsset = (function () {
        var _super = function () {};

        function MyAsset () {
            _super.call(this);
            this.dict1 = {num: 1};
            this.dict2 = {num: 2, other: this.dict1};
            this.dict1.other = this.dict2;
        }
        FIRE.extend(MyAsset, _super);
        FIRE.registerClass('MyAsset', MyAsset);

        return MyAsset;
    })();
    asset = new MyAsset();

    expect = [
        {
            __type__: 'MyAsset',
            dict1: { __id__: 1 },
            dict2: { /*__id__: 2,*/ num:2, other: {__id__: 1} },
        },
        { /*__id__: 1,*/ num:1, other: {num:2, other: {__id__: 1}} },  // You'll get two copies of dict2
    ];
    match(asset, expect, 'two dicts can circular reference each other');

    //asset.sameRef = asset.dict2;
    //expect[1].sameRef = { __id__: 1 };
    //match(asset, expect, 'more referenced object just serialize its id');

    FIRE.unregisterClass(MyAsset);
});

test('test serializable attributes', function () {
    var Sprite = FIRE.define('Sprite')
                     .prop('trimThreshold', 2, FIRE.EditorOnly)
                     .prop('_isValid', true, FIRE.NonSerialized);

    var sprite = new Sprite();
    var resultInEditor = JSON.parse(FIRE.serialize(sprite));
    var resultInPlayer = JSON.parse(FIRE.serialize(sprite, true));

    strictEqual(resultInEditor.trimThreshold, 2, 'serialize editor only in editor');
    strictEqual(resultInPlayer.trimThreshold, undefined, 'should not serialize editor only in player');

    strictEqual(resultInEditor._isValid, undefined, 'should not serialize non-serialized in editor');
    strictEqual(resultInPlayer._isValid, undefined, 'should not serialize non-serialized in player');

    FIRE.undefine(Sprite);
});

test('test asset property', function () {
    var sprite = new FIRE.Sprite();
    sprite.texture = new FIRE.Texture();
    var uuid = '541020432560';
    sprite.texture._uuid = uuid;

    var result = JSON.parse(FIRE.serialize(sprite));

    deepEqual(result.texture, {__uuid__: uuid}, 'serialize asset as uuid reference');
});

test('test FObject reference', function () {
    var fobj = new FIRE.FObject();
    var asset = { ref1: fobj, ref2: fobj };
    var expected = [
        {
          "ref1": { "__id__": 1 },
          "ref2": { "__id__": 1 }
        },
        { "__type__": "FIRE.FObject" },
    ];
    match(asset, expected, 'references should the same');
});

// jshint ignore: end
<|endoftext|>


<commit_before><commit_msg>add subclass test<commit_after><|endoftext|>


<commit_before>describe('Object', function () {
    "use strict";

    describe("Object.keys", function () {
        var obj = {
            "str": "boz",
            "obj": { },
            "arr": [],
            "bool": true,
            "num": 42,
            "null": null,
            "undefined": undefined
        };

        var loopedValues = [];
        for (var k in obj) {
            loopedValues.push(k);
        }

        var keys = Object.keys(obj);
        it('should have correct length', function () {
            expect(keys.length).toBe(7);
        });

        it('should return an Array', function () {
            expect(Array.isArray(keys)).toBe(true);
        });

        it('should return names which are own properties', function () {
            keys.forEach(function (name) {
                expect(obj.hasOwnProperty(name)).toBe(true);
            });
        });

        it('should return names which are enumerable', function () {
            keys.forEach(function (name) {
                expect(loopedValues.indexOf(name)).toNotBe(-1);
            })
        });

        it('should throw error for non object', function () {
            var e = {};
            expect(function () {
                try {
                    Object.keys(42)
                } catch (err) {
                    throw e;
                }
            }).toThrow(e);
        });

        it('should not enumerate over non-enumerable properties', function () {
             var Foo = function () {};
             expect(Object.keys(Foo.prototype)).toEqual([]);
             expect(Object.keys(Boolean.prototype)).toEqual([]);
        });
    });

	describe("Object.isExtensible", function () {
        var obj = { };

        it('should return true if object is extensible', function () {
            expect(Object.isExtensible(obj)).toBe(true);
        });

        it('should return false if object is not extensible', function () {
            expect(Object.isExtensible(Object.preventExtensions(obj))).toBe(false);
        });

        it('should return false if object is seal', function () {
            expect(Object.isExtensible(Object.seal(obj))).toBe(false);
        });

        it('should return false if object is freeze', function () {
            expect(Object.isExtensible(Object.freeze(obj))).toBe(false);
        });

        it('should throw error for non object', function () {
            var e1 = {};
            expect(function () {
                try {
                    Object.isExtensible(42)
                } catch (err) {
                    throw e1;
                }
            }).toThrow(e1);
        });
    });

	describe("Object.defineProperty", function () {
        var obj;

        beforeEach(function() {
           obj = {};

           Object.defineProperty(obj, 'name', {
               value : 'Testing',
               configurable: true,
               enumerable: true,
               writable: true
           });
        });

        it('should return the initial value', function () {
            expect(obj.hasOwnProperty('name')).toBeTruthy();
            expect(obj.name).toBe('Testing');
        });

        it('should be setable', function () {
            obj.name = 'Other';
            expect(obj.name).toBe('Other');
        });

        it('should return the parent initial value', function () {
            var child = Object.create(obj, {});

            expect(child.name).toBe('Testing');
            expect(child.hasOwnProperty('name')).toBeFalsy();
        });

        it('should not override the parent value', function () {
            var child = Object.create(obj, {});

            Object.defineProperty(child, 'name', {
                value : 'Other'
            });

            expect(obj.name).toBe('Testing');
            expect(child.name).toBe('Other');
        });

        it('should throw error for non object', function () {
            expect(function () {
                Object.defineProperty(42, 'name', {});
            }).toThrow();
        });
    });

	describe("Object.getOwnPropertyDescriptor", function () {
        it('should return undefined because the object does not own the property', function () {
            var descr = Object.getOwnPropertyDescriptor({}, 'name');

            expect(descr).toBeUndefined()
        });

        it('should return a data descriptor', function () {
            var descr = Object.getOwnPropertyDescriptor({name: 'Testing'}, 'name');

            expect(descr).not.toBeUndefined();
            expect(descr.value).toBe('Testing');
            expect(descr.writable).toBe(true);
            expect(descr.enumerable).toBe(true);
            expect(descr.configurable).toBe(true);
        });

        it('should return undefined because the object does not own the property', function () {
            var descr = Object.getOwnPropertyDescriptor(Object.create({name: 'Testing'}, {}), 'name');

            expect(descr).toBeUndefined()
        });

        it('should return a data descriptor', function () {
            var obj = Object.create({}, {
                name: {
                    value : 'Testing',
                    configurable: true,
                    enumerable: true,
                    writable: true
                }
            });

            var descr = Object.getOwnPropertyDescriptor(obj, 'name');

            expect(descr).not.toBeUndefined();
            expect(descr.value).toBe('Testing');
            expect(descr.writable).toBe(true);
            expect(descr.enumerable).toBe(true);
            expect(descr.configurable).toBe(true);
        });

    	it('should throw error for non object', function () {
            expect(function () {
                Object.getOwnPropertyDescriptor(42, 'name');
            }).toThrow();
        });
    });
});
<commit_msg>Adding some test cases.<commit_after>describe('Object', function () {
    "use strict";

    describe("Object.keys", function () {
        var obj = {
            "str": "boz",
            "obj": { },
            "arr": [],
            "bool": true,
            "num": 42,
            "null": null,
            "undefined": undefined
        };

        var loopedValues = [];
        for (var k in obj) {
            loopedValues.push(k);
        }

        var keys = Object.keys(obj);
        it('should have correct length', function () {
            expect(keys.length).toBe(7);
        });

        it('should return an Array', function () {
            expect(Array.isArray(keys)).toBe(true);
        });

        it('should return names which are own properties', function () {
            keys.forEach(function (name) {
                expect(obj.hasOwnProperty(name)).toBe(true);
            });
        });

        it('should return names which are enumerable', function () {
            keys.forEach(function (name) {
                expect(loopedValues.indexOf(name)).toNotBe(-1);
            })
        });

        it('should throw error for non object', function () {
            var e = {};
            expect(function () {
                try {
                    Object.keys(42)
                } catch (err) {
                    throw e;
                }
            }).toThrow(e);
        });

        it('should not enumerate over non-enumerable properties', function () {
             var Foo = function () {};
             expect(Object.keys(Foo.prototype)).toEqual([]);
             expect(Object.keys(Boolean.prototype)).toEqual([]);
             expect(Object.keys(Object.prototype)).toEqual([]);
        });
    });

	describe("Object.isExtensible", function () {
        var obj = { };

        it('should return true if object is extensible', function () {
            expect(Object.isExtensible(obj)).toBe(true);
        });

        it('should return false if object is not extensible', function () {
            expect(Object.isExtensible(Object.preventExtensions(obj))).toBe(false);
        });

        it('should return false if object is seal', function () {
            expect(Object.isExtensible(Object.seal(obj))).toBe(false);
        });

        it('should return false if object is freeze', function () {
            expect(Object.isExtensible(Object.freeze(obj))).toBe(false);
        });

        it('should throw error for non object', function () {
            var e1 = {};
            expect(function () {
                try {
                    Object.isExtensible(42)
                } catch (err) {
                    throw e1;
                }
            }).toThrow(e1);
        });
    });

	describe("Object.defineProperty", function () {
        var obj;

        beforeEach(function() {
           obj = {};

           Object.defineProperty(obj, 'name', {
               value : 'Testing',
               configurable: true,
               enumerable: true,
               writable: true
           });
        });

        it('should return the initial value', function () {
            expect(obj.hasOwnProperty('name')).toBeTruthy();
            expect(obj.name).toBe('Testing');
        });

        it('should be setable', function () {
            obj.name = 'Other';
            expect(obj.name).toBe('Other');
        });

        it('should return the parent initial value', function () {
            var child = Object.create(obj, {});

            expect(child.name).toBe('Testing');
            expect(child.hasOwnProperty('name')).toBeFalsy();
        });

        it('should not override the parent value', function () {
            var child = Object.create(obj, {});

            Object.defineProperty(child, 'name', {
                value : 'Other'
            });

            expect(obj.name).toBe('Testing');
            expect(child.name).toBe('Other');
        });

        it('should throw error for non object', function () {
            expect(function () {
                Object.defineProperty(42, 'name', {});
            }).toThrow();
        });
    });

	describe("Object.getOwnPropertyDescriptor", function () {
        it('should return undefined because the object does not own the property', function () {
            var descr = Object.getOwnPropertyDescriptor({}, 'name');

            expect(descr).toBeUndefined()
        });

        it('should return a data descriptor', function () {
            var descr = Object.getOwnPropertyDescriptor({name: 'Testing'}, 'name');

            expect(descr).not.toBeUndefined();
            expect(descr.value).toBe('Testing');
            expect(descr.writable).toBe(true);
            expect(descr.enumerable).toBe(true);
            expect(descr.configurable).toBe(true);
        });

        it('should return undefined because the object does not own the property', function () {
            var descr = Object.getOwnPropertyDescriptor(Object.create({name: 'Testing'}, {}), 'name');

            expect(descr).toBeUndefined()
        });

        it('should return a data descriptor', function () {
            var obj = Object.create({}, {
                name: {
                    value : 'Testing',
                    configurable: true,
                    enumerable: true,
                    writable: true
                }
            });

            var descr = Object.getOwnPropertyDescriptor(obj, 'name');

            expect(descr).not.toBeUndefined();
            expect(descr.value).toBe('Testing');
            expect(descr.writable).toBe(true);
            expect(descr.enumerable).toBe(true);
            expect(descr.configurable).toBe(true);
        });

    	it('should throw error for non object', function () {
            expect(function () {
                Object.getOwnPropertyDescriptor(42, 'name');
            }).toThrow();
        });
    });
});
<|endoftext|>