<commit_before>"use strict";
/*exported Source, SourceArray*/

var Source = gpf.define("Source", {

    "private": {

        //@property {SourceArray} Source array
        _array: null,

        //@property {String} Source name
        "[_name]": [gpf.$ClassProperty()],
        _name: "",

        //@property {String} Source description
        "[_description]": [gpf.$ClassProperty(true)],
        _description: "",

        //@property {Number} Source index
        "[_index]": [gpf.$ClassProperty(true)],
        _index: -1,

        //@property {Boolean} Source is loaded
        "[_load]": [gpf.$ClassProperty()],
        _load: false,

        //@property {Boolean} Source has a test counterpart
        "[_test]": [gpf.$ClassProperty()],
        _test: false,

        //@property {Boolean} Documentation should be extracted from this source
        "[_doc]": [gpf.$ClassProperty()],
        _doc: false,

        //@property {String[]} List of dependencies (boot is excluded)
        "[_dependsOn]": [gpf.$ClassProperty(false, "dependencies")],
        _dependsOn: [],

        //@property {String[]} List of module dependencies
        "[_dependencyOf]": [gpf.$ClassProperty()],
        _dependencyOf: [],

        /**
         * Extract from the dependencies dictionary
         *
         * @param {Object} dependencies dictionary
         */
        _processDependencies: function (dependencies) {
            var myDependencies = dependencies[this._name] || [];
            this._dependsOn = myDependencies;
            this._dependencyOf = [];
            Object.keys(dependencies).forEach(function (name) {
                var nameDependencies = dependencies[name];
                if (nameDependencies.indexOf(this._name) > -1) {
                    this._dependencyOf.push(name);
                }
            }, this);
        },

        //@property {Object[]} List of implemented items
        "[_items]": [gpf.$ClassProperty()],
        _items: [],

        /**
         * Extract implementation details
         *
         * @param {Object} source contains raw implementation
         */
        _processImplementation: function (source) {
            var item = {};
            if (source.method) {
                item.type = Source.IMPLEMENTS_TYPE_METHOD;
                item.name = source.method;
            } else if (source["class"]) {
                item.type = Source.IMPLEMENTS_TYPE_CLASS;
                item.name = source["class"];
            }
            if (item.type) {
                item.internal = item.name.charAt(0) === "_";
                this._items = [item];
            }
        },

        /**
         * Change the load setting
         *
         * @param {Boolean} value
         * @return {Boolean} Update done
         */
        _setLoad: function (value) {
            if (!value) {
                // Allow only if all dependencies are not loaded
                if (this._dependencyOf.some(function (name) {
                    return this._array.byName(name).getLoad();
                }, this)) {
                    return false;
                }
            }
            this._load = value;
            return true;
        },

        /**
         * Change the load setting
         *
         * @param {Boolean} value
         * @return {Boolean} Update done
         */
        _setTest: function (value) {
            this._test = value;
            return true;
        },

        /**
         * Change the doc setting
         *
         * @param {Boolean} value
         * @return {Boolean} Update done
         */
        _setDoc: function (value) {
            this._doc = value;
            return true;
        }
    },

    "public": {

        constructor: function (array, source, dependencies) {
            this._array = array;
            this._name = source.name;
            this._description = source.description;
            this._index = array.getLength();
            if (source.load !== false) {
                this._load = true;
            }
            if (source.test !== false) {
                this._test = true;
            }
            if (source.doc === true) {
                this._doc = true;
            }
            this._processImplementation(source);
            this._processDependencies(dependencies);
        },

        isReadOnly: function () {
            return this._name === "boot";
        },

        testProperty: function (propertyName) {
            if (!this._load) {
                return false;
            }
            if ("test" === propertyName) {
                return this._test;
            } else if ("doc" === propertyName) {
                return this._doc;
            }
            return true;
        },

        setProperty: function (propertyName, value) {
            if ("load" === propertyName) {
                return this._setLoad(value);
            }
            if ("test" === propertyName) {
                return this._setTest(value);
            }
            if ("doc" === propertyName) {
                this._setDoc(value);
            }
        },

        hasDependencies: function () {
            return this._dependsOn.length > 0;
        }

    },

    "static": {
        IMPLEMENTS_TYPE_METHOD: "method",
        IMPLEMENTS_TYPE_CLASS: "class"
    }

});

var SourceArray = gpf.define("SourceArray", {

    "private": {

        // @property {Object} dictionary of sources indexed by name
        _sources: []

    },

    "public": {

        constructor: function (sourcesJSON, dependenciesJSON) {
            var dependencies = JSON.parse(dependenciesJSON);
            JSON.parse(sourcesJSON).forEach(function (source) {
                this._sources.push(new Source(this, source, dependencies));
            }, this);
        },

        /**
         * Get the number of sources
         *
         * @return {Number}
         */
        getLength: function () {
            return this._sources.length;
        },

        /**
         * Enumerate all sources
         *
         * @param {Function} callback
         * @param {*} thisArg
         */
        forEach: function (callback, thisArg) {
            this._sources.forEach(callback, thisArg);
        },

        /**
         * Get the source by name
         *
         * @param {String} name
         * @return {Source}
         */
        byName: function (name) {
            var result;
            this._sources.every(function (source) {
                if (source.getName() === name) {
                    result = source;
                    return false;
                }
                return true;
            });
            return result;
        },

        /**
         * Get the source by index
         *
         * @param {Number} index
         * @return {Source}
         */
        byIndex: function (index) {
            return this._sources[index];
        },

        /**
         * Get all module names
         *
         * @return {String[]}
         */
        getNames: function () {
            return this._sources.map(function (source) {
                return source.getName();
            });
        },

        /**
         * Based on its dependencies, compute the minimum index of the module.
         *
         * @param {String} name
         * @return {Number}
         */
        getMinIndexFor: function (name) {
            var dependencies = this.byName(name).getDependencies(),
                names = this.getNames(),
                minIndex = 1; // 0 being boot
            dependencies.forEach(function (dependencyName) {
                var index = names.indexOf(dependencyName) + 1;
                if (index > minIndex) {
                    minIndex = index;
                }
            });
            return minIndex;
        }

    }

});
<commit_msg>Adds references<commit_after>"use strict";
/*exported Source, SourceArray*/

var Source = gpf.define("Source", {

    "private": {

        //@property {SourceArray} Source array
        _array: null,

        //@property {String} Source name
        "[_name]": [gpf.$ClassProperty()],
        _name: "",

        //@property {String} Source description
        "[_description]": [gpf.$ClassProperty(true)],
        _description: "",

        //@property {Number} Source index
        "[_index]": [gpf.$ClassProperty(true)],
        _index: -1,

        //@property {Boolean} Source is loaded
        "[_load]": [gpf.$ClassProperty()],
        _load: false,

        //@property {Boolean} Source has a test counterpart
        "[_test]": [gpf.$ClassProperty()],
        _test: false,

        //@property {Boolean} Documentation should be extracted from this source
        "[_doc]": [gpf.$ClassProperty()],
        _doc: false,

        //@property {String[]} List of dependencies (boot is excluded)
        "[_dependsOn]": [gpf.$ClassProperty(false, "dependencies")],
        _dependsOn: [],

        //@property {String[]} List of module dependencies
        "[_dependencyOf]": [gpf.$ClassProperty()],
        _dependencyOf: [],

        /**
         * Extract from the dependencies dictionary
         *
         * @param {Object} dependencies dictionary
         */
        _processDependencies: function (dependencies) {
            var myDependencies = dependencies[this._name] || [];
            this._dependsOn = myDependencies;
            this._dependencyOf = [];
            Object.keys(dependencies).forEach(function (name) {
                var nameDependencies = dependencies[name];
                if (nameDependencies.indexOf(this._name) > -1) {
                    this._dependencyOf.push(name);
                }
            }, this);
        },

        //@property {Object[]} List of implemented items
        "[_items]": [gpf.$ClassProperty()],
        _items: [],

        /**
         * Extract implementation details
         *
         * @param {Object} source contains raw implementation
         */
        _processImplementation: function (source) {
            var item = {};
            if (source.method) {
                item.type = Source.IMPLEMENTS_TYPE_METHOD;
                item.name = source.method;
            } else if (source["class"]) {
                item.type = Source.IMPLEMENTS_TYPE_CLASS;
                item.name = source["class"];
            }
            if (item.type) {
                item.internal = item.name.charAt(0) === "_";
                this._items = [item];
            }
        },

        /**
         * Change the load setting
         *
         * @param {Boolean} value
         * @return {Boolean} Update done
         */
        _setLoad: function (value) {
            if (!value) {
                // Allow only if all dependencies are not loaded
                if (this._dependencyOf.some(function (name) {
                    return this._array.byName(name).getLoad();
                }, this)) {
                    return false;
                }
            }
            this._load = value;
            return true;
        },

        /**
         * Change the load setting
         *
         * @param {Boolean} value
         * @return {Boolean} Update done
         */
        _setTest: function (value) {
            this._test = value;
            return true;
        },

        /**
         * Change the doc setting
         *
         * @param {Boolean} value
         * @return {Boolean} Update done
         */
        _setDoc: function (value) {
            this._doc = value;
            return true;
        }
    },

    "public": {

        constructor: function (array, source, dependencies) {
            this._array = array;
            this._name = source.name;
            this._description = source.description;
            this._index = array.getLength();
            if (source.load !== false) {
                this._load = true;
            }
            if (source.test !== false) {
                this._test = true;
            }
            if (source.doc === true) {
                this._doc = true;
            }
            this._processImplementation(source);
            this._processDependencies(dependencies);
        },

        isReadOnly: function () {
            return this._name === "boot";
        },

        testProperty: function (propertyName) {
            if (!this._load) {
                return false;
            }
            if ("test" === propertyName) {
                return this._test;
            } else if ("doc" === propertyName) {
                return this._doc;
            }
            return true;
        },

        setProperty: function (propertyName, value) {
            if ("load" === propertyName) {
                return this._setLoad(value);
            }
            if ("test" === propertyName) {
                return this._setTest(value);
            }
            if ("doc" === propertyName) {
                this._setDoc(value);
            }
        },

        hasDependencies: function () {
            return this._dependsOn.length > 0;
        },

        isReferenced: function () {
            return this._dependencyOf.length > 0;
        }

    },

    "static": {
        IMPLEMENTS_TYPE_METHOD: "method",
        IMPLEMENTS_TYPE_CLASS: "class"
    }

});

var SourceArray = gpf.define("SourceArray", {

    "private": {

        // @property {Object} dictionary of sources indexed by name
        _sources: []

    },

    "public": {

        constructor: function (sourcesJSON, dependenciesJSON) {
            var dependencies = JSON.parse(dependenciesJSON);
            JSON.parse(sourcesJSON).forEach(function (source) {
                this._sources.push(new Source(this, source, dependencies));
            }, this);
        },

        /**
         * Get the number of sources
         *
         * @return {Number}
         */
        getLength: function () {
            return this._sources.length;
        },

        /**
         * Enumerate all sources
         *
         * @param {Function} callback
         * @param {*} thisArg
         */
        forEach: function (callback, thisArg) {
            this._sources.forEach(callback, thisArg);
        },

        /**
         * Get the source by name
         *
         * @param {String} name
         * @return {Source}
         */
        byName: function (name) {
            var result;
            this._sources.every(function (source) {
                if (source.getName() === name) {
                    result = source;
                    return false;
                }
                return true;
            });
            return result;
        },

        /**
         * Get the source by index
         *
         * @param {Number} index
         * @return {Source}
         */
        byIndex: function (index) {
            return this._sources[index];
        },

        /**
         * Get all module names
         *
         * @return {String[]}
         */
        getNames: function () {
            return this._sources.map(function (source) {
                return source.getName();
            });
        },

        /**
         * Based on its dependencies, compute the minimum index of the module.
         *
         * @param {String} name
         * @return {Number}
         */
        getMinIndexFor: function (name) {
            var dependencies = this.byName(name).getDependencies(),
                names = this.getNames(),
                minIndex = 1; // 0 being boot
            dependencies.forEach(function (dependencyName) {
                var index = names.indexOf(dependencyName) + 1;
                if (index > minIndex) {
                    minIndex = index;
                }
            });
            return minIndex;
        }

    }

});
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react'
import FormBuilderPropTypes from '../../FormBuilderPropTypes'
import RenderField from './RenderField'
import ObjectContainer from './ObjectContainer'
import Fieldset from 'part:@sanity/components/fieldsets/default'
import arrify from 'arrify'

export default class Obj extends React.PureComponent {
  static displayName = 'Object'

  static valueContainer = ObjectContainer;

  static propTypes = {
    type: FormBuilderPropTypes.type,
    field: FormBuilderPropTypes.field,
    validation: PropTypes.shape(FormBuilderPropTypes.validation),
    value: PropTypes.object,
    focus: PropTypes.bool,
    onChange: PropTypes.func,
    onEnter: PropTypes.func,
    level: PropTypes.number,
    isRoot: PropTypes.bool
  };

  static defaultProps = {
    onChange() {},
    onEnter() {},
    level: 0
  };

  static contextTypes = {
    resolveInputComponent: PropTypes.func,
    formBuilder: PropTypes.object
  };

  handleFieldChange = (event, fieldName) => {
    const {onChange} = this.props

    const patches = arrify(event.patch).map(patch => {
      return {
        ...patch,
        path: [fieldName, ...(patch.path || [])]
      }
    })
    onChange({patch: patches})
  }

  handleFieldEnter = (event, fieldName) => {
    this.props.onEnter(fieldName)
  }

  renderField(field, level, index) {
    const {value, focus, validation} = this.props
    const fieldValidation = validation && validation.fields[field.name]

    const fieldValue = value.getAttribute(field.name)

    return (
      <RenderField
        key={field.name}
        focus={focus && index === 0}
        fieldName={field.name}
        field={field}
        value={fieldValue}
        onChange={this.handleFieldChange}
        onEnter={this.handleFieldEnter}
        validation={fieldValidation}
        level={level}
      />
    )
  }

  renderFieldset(fieldset, level, index) {
    const columns = fieldset.options && fieldset.options.columns
    const collapsable = fieldset.options && fieldset.options.collapsable
    return (
      <Fieldset
        key={fieldset.name}
        legend={fieldset.title}
        description={fieldset.description}
        level={level}
        columns={columns}
        collapsable={collapsable}
      >
        {fieldset.fields.map((field, fieldIndex) => {
          return this.renderField(field, level + 1, index + fieldIndex)
        })}
      </Fieldset>
    )
  }

  render() {
    const {isRoot, field, type, level} = this.props

    const renderedFields = type.fieldsets.map((fieldset, i) => {
      return fieldset.single
            ? this.renderField(fieldset.field, isRoot ? level : level + 1, i)
            : this.renderFieldset(fieldset, level, i)
    })

    if (isRoot) {
      return
{renderedFields}

    }

    const columns = field.options && field.options.columns
    const collapsable = field.options && field.options.collapsable

    return (
      <Fieldset
        level={level}
        legend={field.title}
        description={field.description}
        columns={columns}
        collapsable={collapsable}
      >
        {renderedFields}
      </Fieldset>
    )
  }
}
<commit_msg>[form-builder] emit setIfMissing patches for objects<commit_after>import React, {PropTypes} from 'react'
import FormBuilderPropTypes from '../../FormBuilderPropTypes'
import RenderField from './RenderField'
import ObjectContainer from './ObjectContainer'
import Fieldset from 'part:@sanity/components/fieldsets/default'
import arrify from 'arrify'

export default class Obj extends React.PureComponent {
  static displayName = 'Object'

  static valueContainer = ObjectContainer;

  static propTypes = {
    type: FormBuilderPropTypes.type,
    field: FormBuilderPropTypes.field,
    validation: PropTypes.shape(FormBuilderPropTypes.validation),
    value: PropTypes.object,
    focus: PropTypes.bool,
    onChange: PropTypes.func,
    onEnter: PropTypes.func,
    level: PropTypes.number,
    isRoot: PropTypes.bool
  };

  static defaultProps = {
    onChange() {},
    onEnter() {},
    level: 0
  };

  static contextTypes = {
    resolveInputComponent: PropTypes.func,
    formBuilder: PropTypes.object
  };

  handleFieldChange = (event, fieldName) => {
    const {onChange, isRoot, type} = this.props

    const setIfMissingPatch = isRoot ? [] : [{
      type: 'setIfMissing',
      value: type.name === 'object' ? {} : {_type: type.name}
    }]
    const patches = setIfMissingPatch.concat(arrify(event.patch).map(patch => {
      return {
        ...patch,
        path: [fieldName, ...(patch.path || [])]
      }
    }))
    onChange({patch: patches})
  }

  handleFieldEnter = (event, fieldName) => {
    this.props.onEnter(fieldName)
  }

  renderField(field, level, index) {
    const {value, focus, validation} = this.props
    const fieldValidation = validation && validation.fields[field.name]

    const fieldValue = value.getAttribute(field.name)

    return (
      <RenderField
        key={field.name}
        focus={focus && index === 0}
        fieldName={field.name}
        field={field}
        value={fieldValue}
        onChange={this.handleFieldChange}
        onEnter={this.handleFieldEnter}
        validation={fieldValidation}
        level={level}
      />
    )
  }

  renderFieldset(fieldset, level, index) {
    const columns = fieldset.options && fieldset.options.columns
    const collapsable = fieldset.options && fieldset.options.collapsable
    return (
      <Fieldset
        key={fieldset.name}
        legend={fieldset.title}
        description={fieldset.description}
        level={level}
        columns={columns}
        collapsable={collapsable}
      >
        {fieldset.fields.map((field, fieldIndex) => {
          return this.renderField(field, level + 1, index + fieldIndex)
        })}
      </Fieldset>
    )
  }

  render() {
    const {isRoot, field, type, level} = this.props

    const renderedFields = type.fieldsets.map((fieldset, i) => {
      return fieldset.single
            ? this.renderField(fieldset.field, isRoot ? level : level + 1, i)
            : this.renderFieldset(fieldset, level, i)
    })

    if (isRoot) {
      return
{renderedFields}

    }

    const columns = field.options && field.options.columns
    const collapsable = field.options && field.options.collapsable

    return (
      <Fieldset
        level={level}
        legend={field.title}
        description={field.description}
        columns={columns}
        collapsable={collapsable}
      >
        {renderedFields}
      </Fieldset>
    )
  }
}
<|endoftext|>


<commit_before>var Module = require('meanio').Module;

exports.get = function(req, res) {
	var _module = new Module(req.params.name);

	_module.settings(function(err, settings) {
		if (err) return res.status(500).send(err);
		if (settings) return res.jsonp(settings.settings);
		res.jsonp({});
	});
};

exports.save = function(req, res) {
	var _module = new Module(req.params.name);
	var settings = req.body;

	_module.settings(settings, function (err, settings) {
		if (err) return res.status(500).send(err);
		res.jsonp(settings.settings);
	});
};

exports.update = function(req, res) {
	var _module = new Module(req.params.name);
	var updatedSettings = req.body;

	_module.settings(function(err, settings) {
		if (!settings) settings = {};
		else settings = settings.settings;

		if (err) return res.status(500).send(err);
		for (var index in updatedSettings)
			settings[index] = updatedSettings[index];

		_module.settings(settings, function (err, settingsObj) {
			if (err) return res.status(500).send(err);
			res.jsonp(settingsObj.settings);
		});
	});
};<commit_msg>admin settings<commit_after>var Module = require('meanio').Module;

exports.get = function(req, res) {
	var _module = new Module(req.params.name);

	_module.settings(function(err, settings) {
		if (err) return res.status(500).send(err);
		if (settings) return res.jsonp(settings.settings);
		res.jsonp({});
	});
};

exports.save = function(req, res) {
	var _module = new Module(req.params.name);
	var settings = req.body;

	_module.settings(settings, function (err, settings) {
		if (err) return res.status(500).send(err);
		res.jsonp(settings.settings);
	});
};

exports.update = function(req, res) {
	var _module = new Module(req.params.name);
	var updatedSettings = req.body;

	_module.settings(function(err, settings) {
		if (!settings) settings = {};
		else settings = settings.settings;

		if (err) return res.status(500).send(err);
		for (var index in updatedSettings)
			settings[index] = updatedSettings[index];

		_module.settings(settings, function (err, settingsObj) {
			if (err) return res.status(500).send(err);
			res.jsonp(settingsObj);
		});
	});
};<|endoftext|>


<commit_before>/*
Copyright 2015, 2016 OpenMarket Ltd

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

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

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

'use strict';

import React from 'react';
import PropTypes from 'prop-types';
import { MatrixClient } from 'matrix-js-sdk';

import MFileBody from './MFileBody';
import ImageUtils from '../../../ImageUtils';
import Modal from '../../../Modal';
import sdk from '../../../index';
import dis from '../../../dispatcher';
import { decryptFile, readBlobAsDataUri } from '../../../utils/DecryptFile';
import Promise from 'bluebird';
import { _t } from '../../../languageHandler';
import SettingsStore from "../../../settings/SettingsStore";

export default class extends React.Component {
    displayName: 'MImageBody'

    static propTypes = {
        /* the MatrixEvent to show */
        mxEvent: PropTypes.object.isRequired,

        /* called when the image has loaded */
        onWidgetLoad: PropTypes.func.isRequired,
    }

    static contextTypes = {
        matrixClient: PropTypes.instanceOf(MatrixClient),
    }

    constructor(props) {
        super(props);

        this.onAction = this.onAction.bind(this);
        this.onImageEnter = this.onImageEnter.bind(this);
        this.onImageLeave = this.onImageLeave.bind(this);
        this.onClientSync = this.onClientSync.bind(this);
        this.onClick = this.onClick.bind(this);
        this.fixupHeight = this.fixupHeight.bind(this);
        this._isGif = this._isGif.bind(this);

        this.state = {
            decryptedUrl: null,
            decryptedThumbnailUrl: null,
            decryptedBlob: null,
            error: null,
            imgError: false,
        };
    }

    componentWillMount() {
        this.unmounted = false;
        this.context.matrixClient.on('sync', this.onClientSync);
    }

    onClientSync(syncState, prevState) {
        if (this.unmounted) return;
        // Consider the client reconnected if there is no error with syncing.
        // This means the state could be RECONNECTING, SYNCING or PREPARED.
        const reconnected = syncState !== "ERROR" && prevState !== syncState;
        if (reconnected && this.state.imgError) {
            // Load the image again
            this.setState({
                imgError: false,
            });
        }
    }

    onClick(ev) {
        if (ev.button == 0 && !ev.metaKey) {
            ev.preventDefault();
            const content = this.props.mxEvent.getContent();
            const httpUrl = this._getContentUrl();
            const ImageView = sdk.getComponent("elements.ImageView");
            const params = {
                src: httpUrl,
                name: content.body && content.body.length > 0 ? content.body : _t('Attachment'),
                mxEvent: this.props.mxEvent,
            };

            if (content.info) {
                params.width = content.info.w;
                params.height = content.info.h;
                params.fileSize = content.info.size;
            }

            Modal.createDialog(ImageView, params, "mx_Dialog_lightbox");
        }
    }

    _isGif() {
        const content = this.props.mxEvent.getContent();
        return (
          content &&
          content.info &&
          content.info.mimetype === "image/gif"
        );
    }

    onImageEnter(e) {
        if (!this._isGif() || SettingsStore.getValue("autoplayGifsAndVideos")) {
            return;
        }
        const imgElement = e.target;
        imgElement.src = this._getContentUrl();
    }

    onImageLeave(e) {
        if (!this._isGif() || SettingsStore.getValue("autoplayGifsAndVideos")) {
            return;
        }
        const imgElement = e.target;
        imgElement.src = this._getThumbUrl();
    }

    onImageError() {
        this.setState({
            imgError: true,
        });
    }

    _getContentUrl() {
        const content = this.props.mxEvent.getContent();
        if (content.file !== undefined) {
            return this.state.decryptedUrl;
        } else {
            return this.context.matrixClient.mxcUrlToHttp(content.url);
        }
    }

    _getThumbUrl() {
        const content = this.props.mxEvent.getContent();
        if (content.file !== undefined) {
            // Don't use the thumbnail for clients wishing to autoplay gifs.
            if (this.state.decryptedThumbnailUrl) {
                return this.state.decryptedThumbnailUrl;
            }
            return this.state.decryptedUrl;
        } else {
            return this.context.matrixClient.mxcUrlToHttp(content.url, 800, 600);
        }
    }

    componentDidMount() {
        this.dispatcherRef = dis.register(this.onAction);
        this.fixupHeight();
        const content = this.props.mxEvent.getContent();
        if (content.file !== undefined && this.state.decryptedUrl === null) {
            let thumbnailPromise = Promise.resolve(null);
            if (content.info.thumbnail_file) {
                thumbnailPromise = decryptFile(
                    content.info.thumbnail_file,
                ).then(function(blob) {
                    return readBlobAsDataUri(blob);
                });
            }
            let decryptedBlob;
            thumbnailPromise.then((thumbnailUrl) => {
                return decryptFile(content.file).then(function(blob) {
                    decryptedBlob = blob;
                    return readBlobAsDataUri(blob);
                }).then((contentUrl) => {
                    this.setState({
                        decryptedUrl: contentUrl,
                        decryptedThumbnailUrl: thumbnailUrl,
                        decryptedBlob: decryptedBlob,
                    });
                    this.props.onWidgetLoad();
                });
            }).catch((err) => {
                console.warn("Unable to decrypt attachment: ", err);
                // Set a placeholder image when we can't decrypt the image.
                this.setState({
                    error: err,
                });
            }).done();
        }
        this._afterComponentDidMount();
    }

    // To be overridden by subclasses (e.g. MStickerBody) for further
    // initialisation after componentDidMount
    _afterComponentDidMount() {
    }

    componentWillUnmount() {
        this.unmounted = true;
        dis.unregister(this.dispatcherRef);
        this.context.matrixClient.removeListener('sync', this.onClientSync);
        this._afterComponentWillUnmount();
    }

    // To be overridden by subclasses (e.g. MStickerBody) for further
    // cleanup after componentWillUnmount
    _afterComponentWillUnmount() {
    }

    onAction(payload) {
        if (payload.action === "timeline_resize") {
            this.fixupHeight();
        }
    }

    fixupHeight() {
        if (!this.refs.image) {
            console.warn(`Refusing to fix up height on ${this.displayName} with no image element`);
            return;
        }

        const content = this.props.mxEvent.getContent();
        const timelineWidth = this.refs.body.offsetWidth;
        const maxHeight = 600; // let images take up as much width as they can so long as the height doesn't exceed 600px.
        // the alternative here would be 600*timelineWidth/800; to scale them down to fit inside a 4:3 bounding box

        //console.log("trying to fit image into timelineWidth of " + this.refs.body.offsetWidth + " or " + this.refs.body.clientWidth);
        let thumbHeight = null;
        if (content.info) {
            thumbHeight = ImageUtils.thumbHeight(content.info.w, content.info.h, timelineWidth, maxHeight);
        }
        this.refs.image.style.height = thumbHeight + "px";
        // console.log("Image height now", thumbHeight);
    }

    _messageContent(contentUrl, thumbUrl, content) {
        return (

                <MFileBody {...this.props} decryptedBlob={this.state.decryptedBlob} />

      );
    }

    render() {
        const content = this.props.mxEvent.getContent();

        if (this.state.error !== null) {
            return (

                    { _t("Error decrypting image") }

            );
        }

        if (content.file !== undefined && this.state.decryptedUrl === null) {
            // Need to decrypt the attachment
            // The attachment is decrypted in componentDidMount.
            // For now add an img tag with a spinner.
            return (

            );
        }

        if (this.state.imgError) {
            return (

                    { _t("This image cannot be displayed.") }

            );
        }

        const contentUrl = this._getContentUrl();
        let thumbUrl;
        if (this._isGif() && SettingsStore.getValue("autoplayGifsAndVideos")) {
          thumbUrl = contentUrl;
        } else {
          thumbUrl = this._getThumbUrl();
        }

        if (thumbUrl) {
            return this._messageContent(contentUrl, thumbUrl, content);
        } else if (content.body) {
            return (

                    { _t("Image '%(Body)s' cannot be displayed.", {Body: content.body}) }

            );
        } else {
            return (

                    { _t("This image cannot be displayed.") }

            );
        }
    }
}
<commit_msg>Bind onImageError in constructor<commit_after>/*
Copyright 2015, 2016 OpenMarket Ltd

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

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

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

'use strict';

import React from 'react';
import PropTypes from 'prop-types';
import { MatrixClient } from 'matrix-js-sdk';

import MFileBody from './MFileBody';
import ImageUtils from '../../../ImageUtils';
import Modal from '../../../Modal';
import sdk from '../../../index';
import dis from '../../../dispatcher';
import { decryptFile, readBlobAsDataUri } from '../../../utils/DecryptFile';
import Promise from 'bluebird';
import { _t } from '../../../languageHandler';
import SettingsStore from "../../../settings/SettingsStore";

export default class extends React.Component {
    displayName: 'MImageBody'

    static propTypes = {
        /* the MatrixEvent to show */
        mxEvent: PropTypes.object.isRequired,

        /* called when the image has loaded */
        onWidgetLoad: PropTypes.func.isRequired,
    }

    static contextTypes = {
        matrixClient: PropTypes.instanceOf(MatrixClient),
    }

    constructor(props) {
        super(props);

        this.onAction = this.onAction.bind(this);
        this.onImageError = this.onImageError.bind(this);
        this.onImageEnter = this.onImageEnter.bind(this);
        this.onImageLeave = this.onImageLeave.bind(this);
        this.onClientSync = this.onClientSync.bind(this);
        this.onClick = this.onClick.bind(this);
        this.fixupHeight = this.fixupHeight.bind(this);
        this._isGif = this._isGif.bind(this);

        this.state = {
            decryptedUrl: null,
            decryptedThumbnailUrl: null,
            decryptedBlob: null,
            error: null,
            imgError: false,
        };
    }

    componentWillMount() {
        this.unmounted = false;
        this.context.matrixClient.on('sync', this.onClientSync);
    }

    onClientSync(syncState, prevState) {
        if (this.unmounted) return;
        // Consider the client reconnected if there is no error with syncing.
        // This means the state could be RECONNECTING, SYNCING or PREPARED.
        const reconnected = syncState !== "ERROR" && prevState !== syncState;
        if (reconnected && this.state.imgError) {
            // Load the image again
            this.setState({
                imgError: false,
            });
        }
    }

    onClick(ev) {
        if (ev.button == 0 && !ev.metaKey) {
            ev.preventDefault();
            const content = this.props.mxEvent.getContent();
            const httpUrl = this._getContentUrl();
            const ImageView = sdk.getComponent("elements.ImageView");
            const params = {
                src: httpUrl,
                name: content.body && content.body.length > 0 ? content.body : _t('Attachment'),
                mxEvent: this.props.mxEvent,
            };

            if (content.info) {
                params.width = content.info.w;
                params.height = content.info.h;
                params.fileSize = content.info.size;
            }

            Modal.createDialog(ImageView, params, "mx_Dialog_lightbox");
        }
    }

    _isGif() {
        const content = this.props.mxEvent.getContent();
        return (
          content &&
          content.info &&
          content.info.mimetype === "image/gif"
        );
    }

    onImageEnter(e) {
        if (!this._isGif() || SettingsStore.getValue("autoplayGifsAndVideos")) {
            return;
        }
        const imgElement = e.target;
        imgElement.src = this._getContentUrl();
    }

    onImageLeave(e) {
        if (!this._isGif() || SettingsStore.getValue("autoplayGifsAndVideos")) {
            return;
        }
        const imgElement = e.target;
        imgElement.src = this._getThumbUrl();
    }

    onImageError() {
        this.setState({
            imgError: true,
        });
    }

    _getContentUrl() {
        const content = this.props.mxEvent.getContent();
        if (content.file !== undefined) {
            return this.state.decryptedUrl;
        } else {
            return this.context.matrixClient.mxcUrlToHttp(content.url);
        }
    }

    _getThumbUrl() {
        const content = this.props.mxEvent.getContent();
        if (content.file !== undefined) {
            // Don't use the thumbnail for clients wishing to autoplay gifs.
            if (this.state.decryptedThumbnailUrl) {
                return this.state.decryptedThumbnailUrl;
            }
            return this.state.decryptedUrl;
        } else {
            return this.context.matrixClient.mxcUrlToHttp(content.url, 800, 600);
        }
    }

    componentDidMount() {
        this.dispatcherRef = dis.register(this.onAction);
        this.fixupHeight();
        const content = this.props.mxEvent.getContent();
        if (content.file !== undefined && this.state.decryptedUrl === null) {
            let thumbnailPromise = Promise.resolve(null);
            if (content.info.thumbnail_file) {
                thumbnailPromise = decryptFile(
                    content.info.thumbnail_file,
                ).then(function(blob) {
                    return readBlobAsDataUri(blob);
                });
            }
            let decryptedBlob;
            thumbnailPromise.then((thumbnailUrl) => {
                return decryptFile(content.file).then(function(blob) {
                    decryptedBlob = blob;
                    return readBlobAsDataUri(blob);
                }).then((contentUrl) => {
                    this.setState({
                        decryptedUrl: contentUrl,
                        decryptedThumbnailUrl: thumbnailUrl,
                        decryptedBlob: decryptedBlob,
                    });
                    this.props.onWidgetLoad();
                });
            }).catch((err) => {
                console.warn("Unable to decrypt attachment: ", err);
                // Set a placeholder image when we can't decrypt the image.
                this.setState({
                    error: err,
                });
            }).done();
        }
        this._afterComponentDidMount();
    }

    // To be overridden by subclasses (e.g. MStickerBody) for further
    // initialisation after componentDidMount
    _afterComponentDidMount() {
    }

    componentWillUnmount() {
        this.unmounted = true;
        dis.unregister(this.dispatcherRef);
        this.context.matrixClient.removeListener('sync', this.onClientSync);
        this._afterComponentWillUnmount();
    }

    // To be overridden by subclasses (e.g. MStickerBody) for further
    // cleanup after componentWillUnmount
    _afterComponentWillUnmount() {
    }

    onAction(payload) {
        if (payload.action === "timeline_resize") {
            this.fixupHeight();
        }
    }

    fixupHeight() {
        if (!this.refs.image) {
            console.warn(`Refusing to fix up height on ${this.displayName} with no image element`);
            return;
        }

        const content = this.props.mxEvent.getContent();
        const timelineWidth = this.refs.body.offsetWidth;
        const maxHeight = 600; // let images take up as much width as they can so long as the height doesn't exceed 600px.
        // the alternative here would be 600*timelineWidth/800; to scale them down to fit inside a 4:3 bounding box

        //console.log("trying to fit image into timelineWidth of " + this.refs.body.offsetWidth + " or " + this.refs.body.clientWidth);
        let thumbHeight = null;
        if (content.info) {
            thumbHeight = ImageUtils.thumbHeight(content.info.w, content.info.h, timelineWidth, maxHeight);
        }
        this.refs.image.style.height = thumbHeight + "px";
        // console.log("Image height now", thumbHeight);
    }

    _messageContent(contentUrl, thumbUrl, content) {
        return (

                <MFileBody {...this.props} decryptedBlob={this.state.decryptedBlob} />

      );
    }

    render() {
        const content = this.props.mxEvent.getContent();

        if (this.state.error !== null) {
            return (

                    { _t("Error decrypting image") }

            );
        }

        if (content.file !== undefined && this.state.decryptedUrl === null) {
            // Need to decrypt the attachment
            // The attachment is decrypted in componentDidMount.
            // For now add an img tag with a spinner.
            return (

            );
        }

        if (this.state.imgError) {
            return (

                    { _t("This image cannot be displayed.") }

            );
        }

        const contentUrl = this._getContentUrl();
        let thumbUrl;
        if (this._isGif() && SettingsStore.getValue("autoplayGifsAndVideos")) {
          thumbUrl = contentUrl;
        } else {
          thumbUrl = this._getThumbUrl();
        }

        if (thumbUrl) {
            return this._messageContent(contentUrl, thumbUrl, content);
        } else if (content.body) {
            return (

                    { _t("Image '%(Body)s' cannot be displayed.", {Body: content.body}) }

            );
        } else {
            return (

                    { _t("This image cannot be displayed.") }

            );
        }
    }
}
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { TabViewAnimated, TabBar, SceneMap } from 'react-native-tab-view';
import { List, ListItem } from 'react-native-elements';
import * as shortid from 'shortid';

import SECTIONS from '../../../constants/SECTIONS';

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});

class SectionPage extends Component {
  static componentName = 'SectionPage';

  static propTypes = {
    sectionIndex: PropTypes.number.isRequired,
    subSectionIndex: PropTypes.number.isRequired,
  };

  state = {
    index: 0,
    sectionInfo: [],
    routes: [
      { key: '1', title: '文章' },
      { key: '2', title: '洞见' },
    ],
  };

  componentWillMount() {
    const sectionIndex = this.props.subSectionIndex;
    const sectionInfo = SECTIONS[this.props.sectionIndex].subSections[sectionIndex];

    this.setState({
      sectionInfo,
    });
  }

  handleChangeTab = index => this.setState({ index });

  renderHeader = props => <TabBar {...props} />;

  renderScene = SceneMap({
    1: () => {
      const articlesView = this.state.sectionInfo.articlesView;

      if (!articlesView) {
        return <Text />;
      }

      const articleViewComponent = articlesView[0].articles.map(article => (
        <ListItem
          key={shortid.generate()}
          title={article.title}
        />
      ));

      return (
        <View>
          <View style={{ backgroundColor: '#2d89ef' }}>
            <Text style={{ margin: 10, color: '#fff', textAlign: 'center' }}>了解优秀软件工程实践所需的信息</Text>
          </View>
          <List>
            {articleViewComponent}
          </List>
        </View>
      );
    },

    2: () => (
      <View>
        <Text>扩展自己的知识视野</Text>
        {
          this.state.sectionInfo.growthView ?
            this.state.sectionInfo.growthView[0].sections.map(section => (
              <ListItem
                key={shortid.generate()}
                title={section.title}
              />
            )) : ''
        }
        <Text>TODO</Text>
        {
          this.state.sectionInfo.todoView ?
            this.state.sectionInfo.todoView.map(todo => (
              <ListItem
                key={shortid.generate()}
                title={todo.title}
              />
            )) : ''
        }
      </View>
    ),
  });

  render() {
    return (
      <TabViewAnimated
        style={styles.container}
        navigationState={this.state}
        renderScene={this.renderScene}
        renderHeader={this.renderHeader}
        onRequestChangeTab={this.handleChangeTab}
      />
    );
  }
}

export default SectionPage;
<commit_msg>[Home] SectionPage: add insight view<commit_after>import React, { Component, PropTypes } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { TabViewAnimated, TabBar, SceneMap } from 'react-native-tab-view';
import { List, ListItem } from 'react-native-elements';
import * as shortid from 'shortid';

import SECTIONS from '../../../constants/SECTIONS';

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});

class SectionPage extends Component {
  static componentName = 'SectionPage';

  static propTypes = {
    sectionIndex: PropTypes.number.isRequired,
    subSectionIndex: PropTypes.number.isRequired,
  };

  state = {
    index: 0,
    sectionInfo: [],
    routes: [
      { key: '1', title: '文章' },
      { key: '2', title: '洞见' },
    ],
  };

  componentWillMount() {
    const sectionIndex = this.props.subSectionIndex;
    const sectionInfo = SECTIONS[this.props.sectionIndex].subSections[sectionIndex];

    this.setState({
      sectionInfo,
    });
  }

  handleChangeTab = index => this.setState({ index });

  renderHeader = props => <TabBar {...props} />;

  renderScene = SceneMap({
    1: () => {
      const articlesView = this.state.sectionInfo.articlesView;

      if (!articlesView) {
        return <Text />;
      }

      const articleViewComponent = articlesView[0].articles.map(article => (
        <ListItem
          key={shortid.generate()}
          title={article.title}
        />
      ));

      return (
        <View>
          <View style={{ backgroundColor: '#2d89ef' }}>
            <Text style={{ margin: 10, color: '#fff', textAlign: 'center' }}>了解优秀软件工程实践所需的信息</Text>
          </View>
          <List>
            {articleViewComponent}
          </List>
        </View>
      );
    },

    2: () => {
      const growthView = this.state.sectionInfo.growthView;
      const todoView = this.state.sectionInfo.todoView;

      const growthViewComponent = growthView ? growthView[0].sections.map(section => (
        <ListItem
          key={shortid.generate()}
          title={section.title}
        />
      )) : <View />;

      const todoViewComponent = todoView ? todoView.map(todo => (
        <ListItem
          key={shortid.generate()}
          title={todo.title}
        />
        )) : <View />;

      return (
        <View>
          <View style={{ backgroundColor: '#2d89ef' }}>
            <Text style={{ margin: 10, color: '#fff', textAlign: 'center' }}>扩展自己的知识视野</Text>
          </View>
          <List>
            { growthViewComponent }
          </List>
          {
            todoView ? <Text style={{ marginTop: 15, textAlign: 'center' }}>TODO</Text> : null
          }
          <List>
            { todoViewComponent }
          </List>
        </View>
      );
    },
  });

  render() {
    return (
      <TabViewAnimated
        style={styles.container}
        navigationState={this.state}
        renderScene={this.renderScene}
        renderHeader={this.renderHeader}
        onRequestChangeTab={this.handleChangeTab}
      />
    );
  }
}

export default SectionPage;
<|endoftext|>


<commit_before>// ==UserScript==
// @name           CosmicWin
// @namespace      CosmicWin
// @description    Makes the new YouTube homepage better.
// @include        https://*.youtube.com/
// @include        http://*.youtube.com/
// @include        https://youtube.com/
// @include        http://youtube.com/
// ==/UserScript==

(function() {
	// Confirugation
	var config = {
		NoSideBar: false,				// Removes the left sidebar
		FullContent: true,				// Makes the homepage content width 100%

		NoGooglePlus: true,				// Removes Google+ from the sidebar
		NoFacebook: true,				// Removes Facebook from the sidebar
		NoChannels: true,				// Removes subscribed channels from the NoSideBar
		NoTrends: true,					// Removes trends from the sidebar

		NoRecommended: true,			// Removes recommended videos
		NoRecommendedChannels: true,	// Removes recommended channels from the sidebar

		NoAggregate: true,				// Removes the "X videos more" button from videos
		NoLoadMore: true,				// Removes the "Load More" button from the page (recommended, it's glitchy)

		ColumnCount: 4,					// Amount of columns

		SmallRows: true,				// Makes rows smaller
		SmallRowsHeight: 65,			// The height of the rows (I suggest 65)

		Categorize: true,				// Categorize uploaded videos on user

		LoadAllThumbnails: true,		// Load all the thumbnails automatically (required if you have multiple columns)

		NoFeatureLinks: true,			// Removes ?feature=X from any homepage link
		NoGuideBars: true,				// Removes the red/gray bars from the sidebar
		NoSecondUploader: true,			// Removes the uploaders name that shows up before the "X times viewed"
		NoAddTo: true,					// Removes the "Add To..." buttons when you hover over videos

		CosmicDebug: false				// Enables the debugger output
	};

	// a.js, 2-12-2011, edited
	function _$(s,url,data,callback) {
		var src = document;
		var ret = false;

		if(url != undefined && data != undefined) {
			var req;

			if(s != "POST" && callback == undefined)
				callback = data;

			if(window.XMLHttpRequest)
				req = new XMLHttpRequest();
			else
				req = new ActiveXObject("Microsoft.XMLHTTP");

			if(req) {
				req.onreadystatechange = function() {
					if(req.readyState == 4 && req.status == 200)
						callback(req.responseText);
				};

				req.open(s, url, true);

				if(s == "POST") {
					req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
					req.setRequestHeader("Content-length", data.length);
					req.setRequestHeader("Connection", "close");
					req.send(data);
				} else {
					req.send();
				}
			}
		} else {
			switch(typeof(s)) {
				case "string":
					if(s != "") {
						var isID = s[0] == "#";
						var isClass = s[0] == ".";
						var isTag = (!isID && !isClass);

						if(isID || isClass)
							s = s.substr(1);

						var sIndex = -1;
						var sMatches = s.match(/^(.+)(\[([0-9]+)\])$/);
						if(sMatches) {
							sIndex = parseInt(sMatches[3]);
							s = sMatches[1];
						}

						var elms = [];
						if(isID)
							ret = src.getElementById(s);
						else if(isClass)
							elms = src.getElementsByClassName(s);
						else if(isTag)
							elms = src.getElementsByTagName(s);

						if(!ret) {
							if(elms.length == 1)
								ret = elms[0];
							else {
								ret = elms;
								if(sIndex != -1)
									ret = elms[sIndex];
							}
						}
					}
					break;
				case "function":
					document.addEventListener("DOMContentLoaded", s, false);
					break;
				default:
					console.log("Unknown type in a.js: '" + typeof(s) + "'");
					break;
			}
		}

		if(ret !== false) {
			ret._$ = _$;
			ret.append = function(c) { ret.innerHTML += c; return this; };
			ret.prepend = function(c) { ret.innerHTML = c + ret.innerHTML;  return this; };
			ret.set = function(c) { ret.innerHTML = c; return this; }
			ret.get = function() { return ret.innerHTML; }
			ret.clear = function() { ret.innerHTML = "";  return this; }
		}

		return ret;
	}

	var debugElement = null;
	function addDebugLog(str) {
		if(! config.CosmicDebug)
			return;

		debugElement.value = str + "\n" + debugElement.value;
	}

	if(config.CosmicDebug) {
		debugElement = document.createElement("textarea");
		debugElement.style.width = "430px";
		debugElement.style.height = "200px";
		debugElement.style.position = "fixed";
		debugElement.style.left = "0px";
		debugElement.style.bottom = "0px";
		debugElement.style.fontFamily = "monospace";
		_$("body").appendChild(debugElement);
	}

	var changedFeedWidth = false;

	var addCSS = document.createElement("style");
	addCSS.innerHTML = "";

	if(config.NoSideBar) {
		addCSS.innerHTML += ".guide-container,guide-background { display:none; }";
		addCSS.innerHTML += "#feed { margin-left:0px;width:970px; }";
		addCSS.innerHTML += "#feed-background { left:0px;width:970px; }";
		addCSS.innerHTML += ".feed-header { border-radius:4px 0px 0px 0px; }";

		changedFeedWidth = true;
	}else{
		if(config.NoFacebook || config.NoChannels) {
			var elms = _$(".guide-item-container");
			for(i = 0; i < elms.length; i++) {
				var elm = elms[i];
				var elmItem = elm.children[0].children[0];

				if(elmItem != null) {
					var elmImage = elmItem.children[0];

					if(elmImage != null) {
						if(config.NoGooglePlus) {
							if(elmImage.className.match(/ google-plus$/))
								elm.style.display = "none";
						}

						if(config.NoFacebook) {
							if(elmImage.className.match(/ facebook$/))
								elm.style.display = "none";
						}

						if(config.NoChannels) {
							if(elmImage.className.match(/ ux-thumb-profile-([0-9]+)$/))
								elm.style.display = "none";
						}
					}
				}
			}
		}
	}

	if(config.FullContent) {
		addCSS.innerHTML += "#content { width:95%; }";
		addCSS.innerHTMl += ".guide-layout-container { width:100%; }";
		addCSS.innerHTML += "#feed { width:-moz-calc(100% - 200px) !important;width:-webkit-calc(100% - 200px) !important; }";
		addCSS.innerHTML += "#feed-background { width:100% !important; }";
	}

	if(config.VisitedLinks) {
		addCSS.innerHTML += "a:visited { color:#00a; }";
	}

	if(config.NoTrends) {
		var elms = _$(".guide-section");
		for(i = 0; i < elms.length; i++) {
			var elmItem = elms[i].children[0].children[0];

			if(elmItem.getAttribute("data-feed-name") == "youtube")
				elms[i].style.display = "none";
		}
	}

	if(config.NoRecommended) {
		addCSS.innerHTML += "#video-sidebar { display:none; }";
		if(!changedFeedWidth)
			addCSS.innerHTML += "#feed,#feed-background { width:770px; }";

		if(config.NoRecommendedChannels) {
			var elms = _$(".guide-section");
			for(i = 0; i < elms.length; i++) {
				var elmIcon = elms[i].children[0].children[0];

				if(elmIcon.getAttribute("data-feed-name") == "channels")
					elms[i].style.display = "none";
			}
		}
	}

	if(config.NoAggregate) {
		addCSS.innerHTML += ".feed-item-show-aggregate { display:none !important; }";
	}

	var columns = [];

	addCSS.innerHTML += "." + (config.Categorize ? "cosmic-win-container" : "feed-item-main") + " { width:" + (100 / config.ColumnCount * 0.92) + "%;float:left;margin-left:10px; }";
	addCSS.innerHTML += ".feed-load-more-container { width:100%;float:left; }";

	var feedContainer = _$(".feed-container");
	if(feedContainer.length != undefined)
		feedContainer = feedContainer[0];
	for(i = 0; i < config.ColumnCount; i++) {
		var newColumn = document.createElement("div");
		newColumn.className = "cosmic-win-container";

		feedContainer.appendChild(newColumn);
		columns.push([0, newColumn]);
	}

	if(config.NoLoadMore) {
		_$(".feed-load-more").style.display = "none";
	}

	if(config.SmallRows) {
		// Thumb
		addCSS.innerHTML += ".video-thumb {" +
							"	width:" + (config.SmallRowsHeight + 16) + "px;" +
							"	height:" + config.SmallRowsHeight + "px;" +
							"}";

		// Thumb Image
		addCSS.innerHTML += ".feed-item-thumb img {" +
							"	width:auto;" +
							"	height:" + config.SmallRowsHeight + "px;" +
							"	top:0px;" +
							"	left:8px;" +
							"}";

		// Item Content
		addCSS.innerHTML += ".feed-item-content {" +
							"	margin-left:" + (config.SmallRowsHeight + 20) + "px !important;" +
							"	margin-right:0px !important;" +
							"	padding-top:0px;" +
							"}";

		// Item Title
		addCSS.innerHTML += ".feed-item-visual-content h4 {" +
							"	width:100% !important;" +
							"}";
	}

	var users = [];
	if(config.Categorize) {
		var elms = _$(".feed-item-outer");
		for(i = 0; i < elms.length; i++) {
			var elm = elms[i];

			if(elm.parentNode.className == "")
				continue;

			var elmOwnerTitle;
			var elmOwner;
			if(elm.children[0].children[2].children.length == 3) {
				elmOwner = elm.children[0].children[2].children[2].children[1].children[0];
				elmOwnerTitle = elm.children[0].children[2].children[2];
			} else {
				elmOwner = elm.children[0].children[2].children[3].children[1].children[0];
				elmOwnerTitle = elm.children[0].children[2].children[3];
			}
			var elmVisual = elm.children[0];

			var userName = elmOwner.innerHTML;
			addDebugLog("'" + userName + "'");
			if(users[userName] == undefined)
				users[userName] = [elm, elmOwnerTitle];
			else
				elmOwnerTitle.style.display = "none";

			users[userName].push([elm, elmVisual]);

			for(j = 0; j < elm.children.length; j++) {
				var child = elm.children[j];
				if(child.className == "feed-item-sub-items") {
					for(k = 0; k < child.children; k++)
						users[userName].push([elm, child.children[k].children[0]]);
				}
			}
		}

		addCSS.innerHTML += ".feed-item-author { position:inherit !important; }";
		addCSS.innerHTML += ".feed-item-outer { padding:0px; }";
		addCSS.innerHTML += ".feed-item-time { top:inherit !important; bottom:0px; }";
		addCSS.innerHTML += ".feed-item-actions-line { padding-top:10px; }";

		for(uID in users) {
			addDebugLog("Categorize: " + uID + " has " + users[uID].length + " videos.");

			var user = users[uID];
			var userElm = user[0];
			var userElmTitle = user[1];

			for(i = 2; i < user.length; i++) {
				var post = user[i];

				if(post[1] != null) {
					userElm.appendChild(post[1]);
				}
			}

			var addToColumn = columns[0];

			for(i = 0; i < columns.length; i++) {
				var columnPostCount = columns[i][0];

				if(columnPostCount < addToColumn[0])
					addToColumn = columns[i];
			}

			addToColumn[1].appendChild(userElmTitle);
			addToColumn[1].appendChild(userElm);
			addToColumn[0] += user.length;
		}

		_$(".feed-page").style.display = "none";
	}

	if(config.LoadAllThumbnails) {
		var elms = _$("img");
		for(i = 0; i < elms.length; i++) {
			var elm = elms[i];
			var newURL = elm.getAttribute("data-thumb");
			if(newURL != null) {
				if(elm.src != newURL)
					elm.src = newURL;
			}
		}
	}

	if(config.NoFeatureLinks) {
		var elms = _$("a");
		for(i = 0; i < elms.length; i++)
			elms[i].href = elms[i].href.replace(/^(.+)(&|\?)feature=(.+)$/, "$1");
	}

	if(config.NoGuideBars) {
		addCSS.innerHTML += ".guide-item.selected,.guide-item.selected:hover { border-right:0px !important; }";
		addCSS.innerHTML += ".guide-item:hover { border-right:0px !important; }";
	}

	if(config.NoSecondUploader) {
		addCSS.innerHTML += ".metadata .yt-user-name { display:none; }";
	}

	if(config.NoAddTo) {
		addCSS.innerHTML += ".addto-button { display:none; }";
	}

	document.head.appendChild(addCSS);

	addDebugLog("Script successfully started.");
})();<commit_msg>Items in the video feed now have some more padding.<commit_after>// ==UserScript==
// @name           CosmicWin
// @namespace      CosmicWin
// @description    Makes the new YouTube homepage better.
// @include        https://*.youtube.com/
// @include        http://*.youtube.com/
// @include        https://youtube.com/
// @include        http://youtube.com/
// ==/UserScript==

(function() {
	// Confirugation
	var config = {
		NoSideBar: false,				// Removes the left sidebar
		FullContent: true,				// Makes the homepage content width 100%

		NoGooglePlus: true,				// Removes Google+ from the sidebar
		NoFacebook: true,				// Removes Facebook from the sidebar
		NoChannels: true,				// Removes subscribed channels from the NoSideBar
		NoTrends: true,					// Removes trends from the sidebar

		NoRecommended: true,			// Removes recommended videos
		NoRecommendedChannels: true,	// Removes recommended channels from the sidebar

		NoAggregate: true,				// Removes the "X videos more" button from videos
		NoLoadMore: true,				// Removes the "Load More" button from the page (recommended, it's glitchy)

		ColumnCount: 4,					// Amount of columns

		SmallRows: true,				// Makes rows smaller
		SmallRowsHeight: 65,			// The height of the rows (I suggest 65)

		Categorize: true,				// Categorize uploaded videos on user

		LoadAllThumbnails: true,		// Load all the thumbnails automatically (required if you have multiple columns)

		NoFeatureLinks: true,			// Removes ?feature=X from any homepage link
		NoGuideBars: true,				// Removes the red/gray bars from the sidebar
		NoSecondUploader: true,			// Removes the uploaders name that shows up before the "X times viewed"
		NoAddTo: true,					// Removes the "Add To..." buttons when you hover over videos

		CosmicDebug: false				// Enables the debugger output
	};

	// a.js, 2-12-2011, edited
	function _$(s,url,data,callback) {
		var src = document;
		var ret = false;

		if(url != undefined && data != undefined) {
			var req;

			if(s != "POST" && callback == undefined)
				callback = data;

			if(window.XMLHttpRequest)
				req = new XMLHttpRequest();
			else
				req = new ActiveXObject("Microsoft.XMLHTTP");

			if(req) {
				req.onreadystatechange = function() {
					if(req.readyState == 4 && req.status == 200)
						callback(req.responseText);
				};

				req.open(s, url, true);

				if(s == "POST") {
					req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
					req.setRequestHeader("Content-length", data.length);
					req.setRequestHeader("Connection", "close");
					req.send(data);
				} else {
					req.send();
				}
			}
		} else {
			switch(typeof(s)) {
				case "string":
					if(s != "") {
						var isID = s[0] == "#";
						var isClass = s[0] == ".";
						var isTag = (!isID && !isClass);

						if(isID || isClass)
							s = s.substr(1);

						var sIndex = -1;
						var sMatches = s.match(/^(.+)(\[([0-9]+)\])$/);
						if(sMatches) {
							sIndex = parseInt(sMatches[3]);
							s = sMatches[1];
						}

						var elms = [];
						if(isID)
							ret = src.getElementById(s);
						else if(isClass)
							elms = src.getElementsByClassName(s);
						else if(isTag)
							elms = src.getElementsByTagName(s);

						if(!ret) {
							if(elms.length == 1)
								ret = elms[0];
							else {
								ret = elms;
								if(sIndex != -1)
									ret = elms[sIndex];
							}
						}
					}
					break;
				case "function":
					document.addEventListener("DOMContentLoaded", s, false);
					break;
				default:
					console.log("Unknown type in a.js: '" + typeof(s) + "'");
					break;
			}
		}

		if(ret !== false) {
			ret._$ = _$;
			ret.append = function(c) { ret.innerHTML += c; return this; };
			ret.prepend = function(c) { ret.innerHTML = c + ret.innerHTML;  return this; };
			ret.set = function(c) { ret.innerHTML = c; return this; }
			ret.get = function() { return ret.innerHTML; }
			ret.clear = function() { ret.innerHTML = "";  return this; }
		}

		return ret;
	}

	var debugElement = null;
	function addDebugLog(str) {
		if(! config.CosmicDebug)
			return;

		debugElement.value = str + "\n" + debugElement.value;
	}

	if(config.CosmicDebug) {
		debugElement = document.createElement("textarea");
		debugElement.style.width = "430px";
		debugElement.style.height = "200px";
		debugElement.style.position = "fixed";
		debugElement.style.left = "0px";
		debugElement.style.bottom = "0px";
		debugElement.style.fontFamily = "monospace";
		_$("body").appendChild(debugElement);
	}

	var changedFeedWidth = false;

	var addCSS = document.createElement("style");
	addCSS.innerHTML = "";

	if(config.NoSideBar) {
		addCSS.innerHTML += ".guide-container,guide-background { display:none; }";
		addCSS.innerHTML += "#feed { margin-left:0px;width:970px; }";
		addCSS.innerHTML += "#feed-background { left:0px;width:970px; }";
		addCSS.innerHTML += ".feed-header { border-radius:4px 0px 0px 0px; }";

		changedFeedWidth = true;
	}else{
		if(config.NoFacebook || config.NoChannels) {
			var elms = _$(".guide-item-container");
			for(i = 0; i < elms.length; i++) {
				var elm = elms[i];
				var elmItem = elm.children[0].children[0];

				if(elmItem != null) {
					var elmImage = elmItem.children[0];

					if(elmImage != null) {
						if(config.NoGooglePlus) {
							if(elmImage.className.match(/ google-plus$/))
								elm.style.display = "none";
						}

						if(config.NoFacebook) {
							if(elmImage.className.match(/ facebook$/))
								elm.style.display = "none";
						}

						if(config.NoChannels) {
							if(elmImage.className.match(/ ux-thumb-profile-([0-9]+)$/))
								elm.style.display = "none";
						}
					}
				}
			}
		}
	}

	if(config.FullContent) {
		addCSS.innerHTML += "#content { width:95%; }";
		addCSS.innerHTMl += ".guide-layout-container { width:100%; }";
		addCSS.innerHTML += "#feed { width:-moz-calc(100% - 200px) !important;width:-webkit-calc(100% - 200px) !important; }";
		addCSS.innerHTML += "#feed-background { width:100% !important; }";
	}

	if(config.VisitedLinks) {
		addCSS.innerHTML += "a:visited { color:#00a; }";
	}

	if(config.NoTrends) {
		var elms = _$(".guide-section");
		for(i = 0; i < elms.length; i++) {
			var elmItem = elms[i].children[0].children[0];

			if(elmItem.getAttribute("data-feed-name") == "youtube")
				elms[i].style.display = "none";
		}
	}

	if(config.NoRecommended) {
		addCSS.innerHTML += "#video-sidebar { display:none; }";
		if(!changedFeedWidth)
			addCSS.innerHTML += "#feed,#feed-background { width:770px; }";

		if(config.NoRecommendedChannels) {
			var elms = _$(".guide-section");
			for(i = 0; i < elms.length; i++) {
				var elmIcon = elms[i].children[0].children[0];

				if(elmIcon.getAttribute("data-feed-name") == "channels")
					elms[i].style.display = "none";
			}
		}
	}

	if(config.NoAggregate) {
		addCSS.innerHTML += ".feed-item-show-aggregate { display:none !important; }";
	}

	var columns = [];

	addCSS.innerHTML += "." + (config.Categorize ? "cosmic-win-container" : "feed-item-main") + " { width:" + (100 / config.ColumnCount * 0.92) + "%;float:left;margin-left:10px; }";
	addCSS.innerHTML += ".feed-load-more-container { width:100%;float:left; }";

	var feedContainer = _$(".feed-container");
	if(feedContainer.length != undefined)
		feedContainer = feedContainer[0];
	for(i = 0; i < config.ColumnCount; i++) {
		var newColumn = document.createElement("div");
		newColumn.className = "cosmic-win-container";

		feedContainer.appendChild(newColumn);
		columns.push([0, newColumn]);
	}

	if(config.NoLoadMore) {
		_$(".feed-load-more").style.display = "none";
	}

	if(config.SmallRows) {
		// Padding for each video in pixels
		var feedItemPadding = 8;

		// Thumb
		addCSS.innerHTML += ".video-thumb {" +
							"	width:" + (config.SmallRowsHeight + 16) + "px;" +
							"	height:" + config.SmallRowsHeight + "px;" +
							"}";

		// Thumb Image
		addCSS.innerHTML += ".feed-item-thumb img {" +
							"	width:auto;" +
							"	height:" + config.SmallRowsHeight + "px;" +
							"	top:0px;" +
							"	left:8px;" +
							"}";

		// Main (feed) item
		addCSS.innerHTML += ".feed-item-main {" +
							"	padding: " + feedItemPadding + "px;" +
							"}";

		// Item Content
		addCSS.innerHTML += ".feed-item-content {" +
							"	margin-left:" + (config.SmallRowsHeight + 20) + "px !important;" +
							"	margin-right:0px !important;" +
							"	padding-top:0px;" +
							"}";

		// Item Title
		addCSS.innerHTML += ".feed-item-visual-content h4 {" +
							"	width:100% !important;" +
							"}";

		// Item time
		addCSS.innerHTML += ".feed-item-time {" +
							"	bottom:" + feedItemPadding + "px;" +
							"}";
	}

	var users = [];
	if(config.Categorize) {
		var elms = _$(".feed-item-outer");
		for(i = 0; i < elms.length; i++) {
			var elm = elms[i];

			if(elm.parentNode.className == "")
				continue;

			var elmOwnerTitle;
			var elmOwner;
			if(elm.children[0].children[2].children.length == 3) {
				elmOwner = elm.children[0].children[2].children[2].children[1].children[0];
				elmOwnerTitle = elm.children[0].children[2].children[2];
			} else {
				elmOwner = elm.children[0].children[2].children[3].children[1].children[0];
				elmOwnerTitle = elm.children[0].children[2].children[3];
			}
			var elmVisual = elm.children[0];

			var userName = elmOwner.innerHTML;
			addDebugLog("'" + userName + "'");
			if(users[userName] == undefined)
				users[userName] = [elm, elmOwnerTitle];
			else
				elmOwnerTitle.style.display = "none";

			users[userName].push([elm, elmVisual]);

			for(j = 0; j < elm.children.length; j++) {
				var child = elm.children[j];
				if(child.className == "feed-item-sub-items") {
					for(k = 0; k < child.children; k++)
						users[userName].push([elm, child.children[k].children[0]]);
				}
			}
		}

		addCSS.innerHTML += ".feed-item-author { position:inherit !important; }";
		addCSS.innerHTML += ".feed-item-outer { padding:0px; }";
		addCSS.innerHTML += ".feed-item-time { top:inherit !important; bottom:0px; }";
		addCSS.innerHTML += ".feed-item-actions-line { padding-top:10px; }";

		for(uID in users) {
			addDebugLog("Categorize: " + uID + " has " + users[uID].length + " videos.");

			var user = users[uID];
			var userElm = user[0];
			var userElmTitle = user[1];

			for(i = 2; i < user.length; i++) {
				var post = user[i];

				if(post[1] != null) {
					userElm.appendChild(post[1]);
				}
			}

			var addToColumn = columns[0];

			for(i = 0; i < columns.length; i++) {
				var columnPostCount = columns[i][0];

				if(columnPostCount < addToColumn[0])
					addToColumn = columns[i];
			}

			addToColumn[1].appendChild(userElmTitle);
			addToColumn[1].appendChild(userElm);
			addToColumn[0] += user.length;
		}

		_$(".feed-page").style.display = "none";
	}

	if(config.LoadAllThumbnails) {
		var elms = _$("img");
		for(i = 0; i < elms.length; i++) {
			var elm = elms[i];
			var newURL = elm.getAttribute("data-thumb");
			if(newURL != null) {
				if(elm.src != newURL)
					elm.src = newURL;
			}
		}
	}

	if(config.NoFeatureLinks) {
		var elms = _$("a");
		for(i = 0; i < elms.length; i++)
			elms[i].href = elms[i].href.replace(/^(.+)(&|\?)feature=(.+)$/, "$1");
	}

	if(config.NoGuideBars) {
		addCSS.innerHTML += ".guide-item.selected,.guide-item.selected:hover { border-right:0px !important; }";
		addCSS.innerHTML += ".guide-item:hover { border-right:0px !important; }";
	}

	if(config.NoSecondUploader) {
		addCSS.innerHTML += ".metadata .yt-user-name { display:none; }";
	}

	if(config.NoAddTo) {
		addCSS.innerHTML += ".addto-button { display:none; }";
	}

	document.head.appendChild(addCSS);

	addDebugLog("Script successfully started.");
})();<|endoftext|>


<commit_before>// ==UserScript==
// @name         NATO Enhancements - FireFoxBullshitHack
// @namespace    http://github.com/Tiny-Giant
// @version      1.0.0.0
// @description  Includes the actual post on the new answers to old questions page of the 10k tools.
// @author       @TinyGiant
// @include      /https?:\/\/(meta\.)?stackoverflow.com\/tools\/new-answers-old-questions.*/
// @grant        GM_addStyle
// ==/UserScript==
/* jshint -W097 */
/* jshint esversion: 6 */
'use strict';

let FirefoxBullshitHack = function(){
    'use strict';
    let css = [
        '.question, .answer {',
        '    width: 730px !important',
        '}',
        'h1, h2, h3, h4, h5, h6 {',
        '    font-weight: normal',
        '}',
        '.answer {',
        '    background: RGBA(249, 253, 66, 0.5);',
        '}'
    ].join('\n');

    if (false);
    else if ("undefined" != typeof GM_addStyle) GM_addStyle(css);
    else if ("undefined" != typeof PRO_addStyle) PRO_addStyle(css);
    else if ("undefined" != typeof addStyle) addStyle(css);
    else(document.body || document.getElementsByTagName("body")[0]).appendChild(document.createElement("style").appendChild(document.createTextNode(css)).parentNode);

    StackExchange.using("inlineEditing", function()
    {
        StackExchange.inlineEditing.init();
    });

    let posts = [],
        post = {},
        funcs = {},
        complete, Q = 1,
        A = 2;

    funcs.showComments = (post) =>
    {
        post.wrap.querySelector('.js-show-link.comments-link').click();
    }

    funcs.initQuestion = (post, votes) =>
    {
        StackExchange.question.init(
        {
            votesCast: votes,
            canViewVoteCounts: true,
            questionId: post.id
        });
    }

    funcs.replacePost = (post, html) =>
    {
        let osnippets = Array.from(post.wrap.querySelectorAll('.snippet'));

        post.wrap.innerHTML = html;

        let nsnippets = Array.from(post.wrap.querySelectorAll('.snippet'));

        while (nsnippets.length > 0 && osnippets.length > 0)
        {
            let nsnippet = nsnippets.shift();
            let osnippet = osnippets.shift();

            nsnippet.parentNode.insertBefore(osnippet, nsnippet);
            nsnippet.parentNode.removeChild(nsnippet);
        }
    }

    funcs.fetchVotes = (post, complete) =>
    {
        let xhr = new XMLHttpRequest();

        xhr.addEventListener('load', event =>
        {
            if (xhr.status !== 200)
            {
                console.log(xhr.status, xhr.statusText, xhr.responseText);
                return;
            }

            if (typeof complete === 'function')
            {
                complete(JSON.parse(xhr.responseText));
            }
        }, false);

        xhr.open('GET', '/posts/' + post.id + '/votes');

        xhr.send();
    };

    funcs.fetchPost = (post, complete) =>
    {
        let xhr = new XMLHttpRequest();

        xhr.addEventListener('load', event =>
        {
            if (xhr.status !== 200)
            {
                console.log(xhr.status, xhr.statusText, xhr.responseText);
                return;
            }

            if (typeof complete === 'function')
            {
                complete(xhr.responseText);
            }
        }, false);

        xhr.open('GET', '/posts/ajax-load-realtime/' + post.id);

        xhr.send();
    };

    funcs.fetchAllPosts = () =>
    {
        post = posts.shift();

        funcs.fetchPost(post.question, questionHTML =>
        {
            funcs.fetchPost(post.answer, answerHTML =>
            {
                funcs.fetchVotes(post.question, votes =>
                {
                    post.answer.wrap.className = '';
                    funcs.replacePost(post.question, questionHTML);
                    funcs.replacePost(post.answer, answerHTML);
                    funcs.initQuestion(post.question, votes);
                    funcs.showComments(post.question);
                    funcs.showComments(post.question);

                    if (posts.length > 0)
                    {
                        funcs.fetchAllPosts();
                    }
                });
            });
        });
    }

    funcs.getPosts = () =>
    {
        let postTexts = Array.from(document.querySelectorAll('.post-text'));

        for (let postText of postTexts)
        {
            let parent = postText.parentNode;
            let details = parent.nextElementSibling;
            parent.parentNode.removeChild(details);

            let questionWrap = document.createElement('div');
            parent.insertBefore(questionWrap, postText);

            let separator = document.createElement('hr');
            parent.insertBefore(separator, postText);

            let postLink = parent.querySelector('.answer-hyperlink');

            postLink.parentNode.removeChild(postLink.nextElementSibling);
            postLink.parentNode.removeChild(postLink.nextElementSibling);

            postLink.outerHTML = '
' + postLink.outerHTML + '
';

            let postIDs = /(\d+).*?(\d+)$/.exec(postLink.href);

            posts.push(
            {
                answer:
                {
                    id: postIDs[2],
                    wrap: postText
                },
                question:
                {
                    id: postIDs[1],
                    wrap: questionWrap
                }
            });
        }
    };

    funcs.getPosts();
    funcs.fetchAllPosts();
};

let FirefoxBullshitHackScript = document.createElement('script');
FirefoxBullshitHackScript.textContent = '(' + FirefoxBullshitHack.toString() + ')()';
document.body.appendChild(FirefoxBullshitHackScript);
<commit_msg>Updated the answer color<commit_after>// ==UserScript==
// @name         NATO Enhancements - FirefoxBullshitHack
// @namespace    http://github.com/Tiny-Giant
// @version      1.0.0.1
// @description  Includes the actual post on the new answers to old questions page of the 10k tools.
// @author       @TinyGiant
// @include      /https?:\/\/(meta\.)?stackoverflow.com\/tools\/new-answers-old-questions.*/
// @grant        GM_addStyle
// ==/UserScript==
/* jshint -W097 */
/* jshint esversion: 6 */
'use strict';

let FirefoxBullshitHack = function(){
    'use strict';

    let css = [
        '.question, .answer {',
        '    width: 730px !important',
        '}',
        'h1, h2, h3, h4, h5, h6 {',
        '    font-weight: normal',
        '}',
        '.answer {',
        '    background: RGBA(255,153,0, 0.1);',
        '}'
    ].join('\n');

    if (false);
    else if ("undefined" != typeof GM_addStyle)  GM_addStyle(css);
    else if ("undefined" != typeof PRO_addStyle) PRO_addStyle(css);
    else if ("undefined" != typeof addStyle)     addStyle(css);
    else (document.body || document.getElementsByTagName("body")[0]).appendChild(document.createElement("style").appendChild(document.createTextNode(css)).parentNode);

    StackExchange.using("inlineEditing", function () {
        StackExchange.inlineEditing.init();
    });

    let posts = [], post = {}, funcs = {}, complete, Q = 1, A = 2;

    funcs.showComments = (post) =>
    {
        post.wrap.querySelector('.js-show-link.comments-link').click();
    }

    funcs.initQuestion = (post, votes) =>
    {
        StackExchange.question.init({
            votesCast: votes,
            canViewVoteCounts: true,
            questionId: post.id
        });
    }

    funcs.replacePost = (post, html) =>
    {
        let osnippets = Array.from(post.wrap.querySelectorAll('.snippet'));

        post.wrap.innerHTML = html;

        let nsnippets = Array.from(post.wrap.querySelectorAll('.snippet'));

        while(nsnippets.length > 0 && osnippets.length > 0)
        {
            let nsnippet = nsnippets.shift();
            let osnippet = osnippets.shift();

            nsnippet.parentNode.insertBefore(osnippet, nsnippet);
            nsnippet.parentNode.removeChild(nsnippet);
        }
    }

    funcs.fetchVotes = (post, complete) =>
    {
        let xhr = new XMLHttpRequest();

        xhr.addEventListener('load', event =>
        {
            if (xhr.status !== 200)
            {
                console.log(xhr.status, xhr.statusText, xhr.responseText);
                return;
            }

            if (typeof complete === 'function')
            {
                complete(JSON.parse(xhr.responseText));
            }
        }, false);

        xhr.open('GET', '/posts/' + post.id + '/votes');

        xhr.send();
    };

    funcs.fetchPost = (post, complete) =>
    {
        let xhr = new XMLHttpRequest();

        xhr.addEventListener('load', event =>
        {
            if (xhr.status !== 200)
            {
                console.log(xhr.status, xhr.statusText, xhr.responseText);
                return;
            }

            if (typeof complete === 'function')
            {
                complete(xhr.responseText);
            }
        }, false);

        xhr.open('GET', '/posts/ajax-load-realtime/' + post.id);

        xhr.send();
    };

    funcs.fetchAllPosts = () =>
    {
        post = posts.shift();

        funcs.fetchPost(post.question, questionHTML =>
        {
            funcs.fetchPost(post.answer, answerHTML =>
            {
                funcs.fetchVotes(post.question, votes =>
                {
                    post.answer.wrap.className = '';
                    funcs.replacePost(post.question,  questionHTML);
                    funcs.replacePost(post.answer,    answerHTML);
                    funcs.initQuestion(post.question, votes);
                    funcs.showComments(post.question);
                    funcs.showComments(post.question);

                    if (posts.length > 0)
                    {
                        funcs.fetchAllPosts();
                    }
                });
            });
        });
    }

    funcs.getPosts = () =>
    {
        let postTexts = Array.from(document.querySelectorAll('.post-text'));

        for(let postText of postTexts)
        {
            let parent = postText.parentNode;
            let details = parent.nextElementSibling;
            parent.parentNode.removeChild(details);

            let questionWrap = document.createElement('div');
            parent.insertBefore(questionWrap, postText);

            let separator = document.createElement('hr');
            parent.insertBefore(separator, postText);

            let postLink = parent.querySelector('.answer-hyperlink');

            postLink.parentNode.removeChild(postLink.nextElementSibling);
            postLink.parentNode.removeChild(postLink.nextElementSibling);

            postLink.outerHTML = '
' + postLink.outerHTML + '
';

            let postIDs   = /(\d+).*?(\d+)$/.exec(postLink.href);

            posts.push({
                answer: {
                    id:   postIDs[2],
                    wrap: postText
                },
                question: {
                    id:   postIDs[1],
                    wrap: questionWrap
                }
            });
        }
    };

    funcs.getPosts();
    funcs.fetchAllPosts();
};

let FirefoxBullshitHackScript = document.createElement('script');
FirefoxBullshitHackScript.textContent = '(' + FirefoxBullshitHack.toString() + ')()';
document.body.appendChild(FirefoxBullshitHackScript);
<|endoftext|>


<commit_before>/*
 *  GameoverScene.js
 *  2014/06/23
 *  @auther minimo
 *  This Program is MIT license.
 *
 */

tm.define("shotgun.GameoverScene", {
    superClass: tm.app.Scene,

    parentScene: null,
    mode: 0,
    dispExtend: false,

    //ラベル用フォントパラメータ
    headerParam: {fontFamily:"CasinoRegular", align: "center", baseline:"middle", outlineWidth:2 },
    labelParam: {fontFamily:"Yasashisa", align: "center", baseline:"middle", outlineWidth:2 },
    scoreParam: {fontFamily:"Yasashisa", align: "left", baseline:"middle", outlineWidth:2 },
    extendParam: {fontFamily:"Yasashisa", align: "center", baseline:"middle", outlineWidth:2, fillStyle: "red" },

    init: function(parentScene) {
        this.superInit();
        this.background = "rgba(0, 0, 0, 0.0)";

        this.parentScene = parentScene;

        //バックグラウンド
        this.bg = tm.display.RectangleShape(SC_W, SC_H, {fillStyle: appMain.bgColor, strokeStyle: appMain.bgColor})
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.5);

        var that = this;
        var width = SC_W, height = 80;

        //メインとリザルトを分けてレイヤーを作成
        this.mainLayer = tm.app.Object2D().addChildTo(this);
        this.resultLayer = tm.app.Object2D().addChildTo(this);

        this.top = tm.display.OutlineLabel("RESULT", 60)
            .addChildTo(this)
            .setParam(this.headerParam)
            .setPosition(SC_W*0.5, SC_H*0.05);

        //スコア表示
        this.mode = parentScene.mode;
        if (appMain.returnJoker) this.mode += 10;
        this.score = tm.display.OutlineLabel("SCORE "+appMain.lastScore[this.mode], 50)
            .addChildTo(this)
            .setParam(this.labelParam)
            .setPosition(SC_W*0.5, SC_H*0.12);

        this.score = tm.display.OutlineLabel("YOUR BEST SCORE IS "+appMain.highScore[this.mode], 35)
            .addChildTo(this)
            .setParam(this.labelParam)
            .setPosition(SC_W*0.5, SC_H*0.17);
        if (this.parentScene.newRecord) {
            var nr = tm.display.OutlineLabel("NewRecord!!", 20)
                .addChildTo(this)
                .setParam(this.labelParam)
                .setFillStyle("Red")
                .setFillStyleOutline("rgb(255,200,200)")
                .setPosition(SC_W*0.82, SC_H*0.20);
        }

        //役一覧
        for (var i = 0; i < 12; i++) {
            tm.display.OutlineLabel(appMain.handList[i].name+":"+this.parentScene.handCount[appMain.handList[i].point], 35)
                .addChildTo(this.resultLayer)
                .setParam(this.scoreParam)
                .setPosition(SC_W*0.2, SC_H*0.22+(i*42));
        }

        //ボタン用パラメータ
        var param = {flat: appMain.buttonFlat, fontSize:50};

        //全画面広告ボタン
        this.Ad = shotgun.Button(width*0.5, height, "Ad", param)
            .addChildTo(this)
            .setPosition(SC_W*0.25, SC_H*0.71)
            .addEventListener("pushed", function() {
                if(ENABLE_PHONEGAP && AdMob) {
                    AdMob.prepareInterstitial({
                        adId:admobid.interstitial,
                        autoShow:true
                    });
                }
                if (this.mode != GAMEMODE_HARD) appMain.bonusLife = 1;
            });

        //GAMECENTER
        shotgun.Button(width*0.5, height, "RANKING", param)
//            .addChildTo(this)
            .setPosition(SC_W*0.75, SC_H*0.71)
            .addEventListener("pushed", function() {
                var mode = that.parentScene.mode;
                var lb = "Normal";
                if (mode == GAMEMODE_HARD) lb = "Hard";
                if (appMain.returnJoker) lb += "_ReturnJoker";
                showLeadersBoard(lb);
            });

        //リトライボタン
        this.retry = shotgun.Button(width, height, "TRY AGAIN", param)
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.78)
            .addEventListener("pushed", function() {
                var mode = that.parentScene.mode;
                that.parentScene = null;
                that.mask.tweener.clear().fadeIn(300).call(function(){appMain.replaceScene(shotgun.MainScene(mode));});
            });

        //戻るボタン
        this.back = shotgun.Button(width, height, "RETURN TO TITLE", param)
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.85)
            .addEventListener("pushed", function() {
                that.parentScene = null;
                that.mask.tweener.clear().fadeIn(300).call(function(){appMain.replaceScene(shotgun.TitleScene());});
            });

        //目隠し
        this.mask = tm.display.RectangleShape(SC_W, SC_H, {fillStyle: "rgba(0, 0, 0, 1.0)", strokeStyle: "rgba(0, 0, 0, 1.0)"})
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.5);
        this.mask.tweener.clear().fadeOut(200);

        //GameCenter登録
//        this.registScore();
    },

    update: function() {
        if (!this.dispExtend && appMain.bonusLife != 0) {
            var that = this;
            var c = tm.display.Sprite("card", CARD_W, CARD_H)
                .addChildTo(this.retry)
//                .setPosition(SC_W*0.40, SC_H*0.85)
                .setPosition(190, 0)
                .setFrameIndex(13*3)
                .tweener.clear()
                .fadeOut(1)
                .wait(1000)
                .call(function(){
                    that.Ad.remove();
                })
                .wait(1000)
                .fadeIn(1)
                .scale(0.4, 1000, "easeOutBounce")
                .call(function(){
                    tm.display.OutlineLabel("+", 70)
                        .addChildTo(that.retry)
                        .setParam(that.extendParam)
                        .setPosition(150, 0);
                });
            this.dispExtend = true;
        }
    },

    //GameCenterにスコアを登録
    registScore: function() {
        if (ENABLE_GAMECENTER) {
            var lb = "Normal";
            if (this.mode == GAMEMODE_HARD) lb = "Hard";
            if (appMain.returnJoker) lb += "_ReturnJoker";
            var data = {
                score: this.score,
                leaderboardId: lb,
            };
            gamecenter.submitScore(
                function() {
                    if (DEBUG_GAMECENTER) AdvanceAlert('スコア登録に成功しました');
                },
                function() {
                    if (DEBUG_GAMECENTER) AdvanceAlert('スコア登録に失敗しました');
                }, data);
        }
    },

    //タッチorクリック開始処理
    ontouchstart: function(e) {
    },

    //タッチorクリック移動処理
    ontouchmove: function(e) {
    },

    //タッチorクリック終了処理
    ontouchend: function(e) {
    },

});
<commit_msg>ボーナスライフ修正<commit_after>/*
 *  GameoverScene.js
 *  2014/06/23
 *  @auther minimo
 *  This Program is MIT license.
 *
 */

tm.define("shotgun.GameoverScene", {
    superClass: tm.app.Scene,

    parentScene: null,
    mode: 0,
    dispExtend: false,

    //ラベル用フォントパラメータ
    headerParam: {fontFamily:"CasinoRegular", align: "center", baseline:"middle", outlineWidth:2 },
    labelParam: {fontFamily:"Yasashisa", align: "center", baseline:"middle", outlineWidth:2 },
    scoreParam: {fontFamily:"Yasashisa", align: "left", baseline:"middle", outlineWidth:2 },
    extendParam: {fontFamily:"Yasashisa", align: "center", baseline:"middle", outlineWidth:2, fillStyle: "red" },

    init: function(parentScene) {
        this.superInit();
        this.background = "rgba(0, 0, 0, 0.0)";

        this.parentScene = parentScene;

        //バックグラウンド
        this.bg = tm.display.RectangleShape(SC_W, SC_H, {fillStyle: appMain.bgColor, strokeStyle: appMain.bgColor})
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.5);

        var that = this;
        var width = SC_W, height = 80;

        //メインとリザルトを分けてレイヤーを作成
        this.mainLayer = tm.app.Object2D().addChildTo(this);
        this.resultLayer = tm.app.Object2D().addChildTo(this);

        this.top = tm.display.OutlineLabel("RESULT", 60)
            .addChildTo(this)
            .setParam(this.headerParam)
            .setPosition(SC_W*0.5, SC_H*0.05);

        //スコア表示
        this.mode = parentScene.mode;
        if (appMain.returnJoker) this.mode += 10;
        this.score = tm.display.OutlineLabel("SCORE "+appMain.lastScore[this.mode], 50)
            .addChildTo(this)
            .setParam(this.labelParam)
            .setPosition(SC_W*0.5, SC_H*0.12);

        this.score = tm.display.OutlineLabel("YOUR BEST SCORE IS "+appMain.highScore[this.mode], 35)
            .addChildTo(this)
            .setParam(this.labelParam)
            .setPosition(SC_W*0.5, SC_H*0.17);
        if (this.parentScene.newRecord) {
            var nr = tm.display.OutlineLabel("NewRecord!!", 20)
                .addChildTo(this)
                .setParam(this.labelParam)
                .setFillStyle("Red")
                .setFillStyleOutline("rgb(255,200,200)")
                .setPosition(SC_W*0.82, SC_H*0.20);
        }

        //役一覧
        for (var i = 0; i < 12; i++) {
            tm.display.OutlineLabel(appMain.handList[i].name+":"+this.parentScene.handCount[appMain.handList[i].point], 35)
                .addChildTo(this.resultLayer)
                .setParam(this.scoreParam)
                .setPosition(SC_W*0.2, SC_H*0.22+(i*42));
        }

        //ボタン用パラメータ
        var param = {flat: appMain.buttonFlat, fontSize:50};

        //全画面広告ボタン
        this.Ad = shotgun.Button(width*0.5, height, "Ad", param)
            .addChildTo(this)
            .setPosition(SC_W*0.25, SC_H*0.71)
            .addEventListener("pushed", function() {
                if(ENABLE_PHONEGAP && AdMob) {
                    AdMob.prepareInterstitial({
                        adId:admobid.interstitial,
                        autoShow:true
                    });
                }
                if (that.mode != GAMEMODE_HARD && that.mode != GAMEMODE_HARD+10) appMain.bonusLife = 1;
            });

        //GAMECENTER
        shotgun.Button(width*0.5, height, "RANKING", param)
//            .addChildTo(this)
            .setPosition(SC_W*0.75, SC_H*0.71)
            .addEventListener("pushed", function() {
                var mode = that.parentScene.mode;
                var lb = "Normal";
                if (mode == GAMEMODE_HARD) lb = "Hard";
                if (appMain.returnJoker) lb += "_ReturnJoker";
                showLeadersBoard(lb);
            });

        //リトライボタン
        this.retry = shotgun.Button(width, height, "TRY AGAIN", param)
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.78)
            .addEventListener("pushed", function() {
                var mode = that.parentScene.mode;
                that.parentScene = null;
                that.mask.tweener.clear().fadeIn(300).call(function(){appMain.replaceScene(shotgun.MainScene(mode));});
            });

        //戻るボタン
        this.back = shotgun.Button(width, height, "RETURN TO TITLE", param)
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.85)
            .addEventListener("pushed", function() {
                that.parentScene = null;
                that.mask.tweener.clear().fadeIn(300).call(function(){appMain.replaceScene(shotgun.TitleScene());});
            });

        //目隠し
        this.mask = tm.display.RectangleShape(SC_W, SC_H, {fillStyle: "rgba(0, 0, 0, 1.0)", strokeStyle: "rgba(0, 0, 0, 1.0)"})
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.5);
        this.mask.tweener.clear().fadeOut(200);

        //GameCenter登録
//        this.registScore();
    },

    update: function() {
        if (!this.dispExtend && appMain.bonusLife != 0) {
            var that = this;
            var c = tm.display.Sprite("card", CARD_W, CARD_H)
                .addChildTo(this.retry)
//                .setPosition(SC_W*0.40, SC_H*0.85)
                .setPosition(190, 0)
                .setFrameIndex(13*3)
                .tweener.clear()
                .fadeOut(1)
                .wait(1000)
                .call(function(){
                    that.Ad.remove();
                })
                .wait(1000)
                .fadeIn(1)
                .scale(0.4, 1000, "easeOutBounce")
                .call(function(){
                    tm.display.OutlineLabel("+", 70)
                        .addChildTo(that.retry)
                        .setParam(that.extendParam)
                        .setPosition(150, 0);
                });
            this.dispExtend = true;
        }
    },

    //GameCenterにスコアを登録
    registScore: function() {
        if (ENABLE_GAMECENTER) {
            var lb = "Normal";
            if (this.mode == GAMEMODE_HARD) lb = "Hard";
            if (appMain.returnJoker) lb += "_ReturnJoker";
            var data = {
                score: this.score,
                leaderboardId: lb,
            };
            gamecenter.submitScore(
                function() {
                    if (DEBUG_GAMECENTER) AdvanceAlert('スコア登録に成功しました');
                },
                function() {
                    if (DEBUG_GAMECENTER) AdvanceAlert('スコア登録に失敗しました');
                }, data);
        }
    },

    //タッチorクリック開始処理
    ontouchstart: function(e) {
    },

    //タッチorクリック移動処理
    ontouchmove: function(e) {
    },

    //タッチorクリック終了処理
    ontouchend: function(e) {
    },

});
<|endoftext|>