<commit_before>// This file has evolved from
//    d-mode.js by Matt Godbolt
//    Copyright (c) 2017, Matt Godbolt
//    All rights reserved.
//
//    Redistribution and use in source and binary forms, with or without
//    modification, are permitted provided that the following conditions are met:
//
//        * Redistributions of source code must retain the above copyright notice,
//          this list of conditions and the following disclaimer.
//        * Redistributions in binary form must reproduce the above copyright
//          notice, this list of conditions and the following disclaimer in the
//          documentation and/or other materials provided with the distribution.
//
//    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
//    AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
//    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
//    ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
//    LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
//    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
//    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
//    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
//    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
//    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//    POSSIBILITY OF SUCH DAMAGE.
//
// The lists of keywords, operator, functions, and subroutines have been adopted from
//    vs.language.fortran by Thomas E. Dunn
"use strict";

function definition() {
    return {
	// Fortran is case insensitive, so ignore case...
	ignoreCase: true,

        defaultToken: 'invalid',

        keywords: [
            'abstract',
            'all',
            'allocatable',
            'allocate',
            'assign',
            'assignment',
            'asynchronous',
            'backspace',
            'bind',
            'block',
            'blockdata',
            'character',
            'close',
            'common',
            'complex',
            'concurrent',
            'contiguous',
            'call',
            'case',
            'class',
            'codimension',
            'contains',
            'continue',
            'cycle',
            'data',
            'deallocate',
            'deferred',
            'dimension',
            'do',
            'double',
            'doubleprecision',
            'elemental',
            'else',
            'elsewhere',
            'end',
            'endblock',
            'endblockdata',
            'enddo',
            'endenum',
            'endfile',
            'endforall',
            'endfunction',
            'endif',
            'endinterface',
            'endmodule',
            'endprogram',
            'endselect',
            'endsubmodule',
            'endsubroutine',
            'endtype',
            'endwhere',
            'endwhile',
            'entry',
            'enum',
            'enumerator',
            'equivalence',
            'error',
            'exit',
            'external',
            'final',
            'flush',
            'forall',
            'format',
            'function',
            'generic',
            'go',
            'goto',
            'if',
            'implicit',
            'import',
            'in',
            'include',
            'inout',
            'inquire',
            'intent',
            'interface',
            'intrinsic',
            'is',
            'logical',
            'module',
            'non_overridable',
            'none',
            'nopass',
            'nullify',
            'only',
            'open',
            'operator',
            'optional',
            'out',
            'parameter',
            'pass',
            'pause',
            'pointer',
            'precision',
            'print',
            'private',
            'procedure',
            'program',
            'protected',
            'public',
            'pure',
            'read',
            'real',
            'recursive',
            'result',
            'return',
            'rewind',
            'save',
            'select',
            'sequence',
            'stop',
            'submodule',
            'subroutine',
            'target',
            'then',
            'to',
            'type',
            'use',
            'value',
            'volatile',
            'wait',
            'where',
            'while',
            'write'
        ],

        typeKeywords: [
            'logical',
            'character',
            'real',
            'integer',
            'complex',
            'type'
        ],

        operators: [
            '=',
            '==',
            '/=',
            '>',
            '>=',
            '<',
            '<=',
            '=>',
            '+',
            '-',
            '*',
            '/',
            '**',
            '//',
            '.and.',
            '.eq.',
            '.eqv.',
            '.le.',
            '.lt.',
            '.ge.',
            '.gt.',
            '.ne.',
            '.neqv.',
            '.not.',
            '.or.'
        ],

        functions: [
            'abs',
            'achar',
            'acos',
            'acosh',
            'adjustl',
            'adjustr',
            'aimag',
            'aint',
            'all',
            'allocated',
            'anint',
            'any',
            'asin',
            'asinh',
            'associated',
            'atan',
            'atan2',
            'atanh',
            'bessel_j0',
            'bessel_j1',
            'bessel_jn',
            'bessel_y0',
            'bessel_y1',
            'bessel_yn',
            'bge',
            'bgt',
            'bit_size',
            'ble',
            'blt',
            'btest',
            'c_associated',
            'c_funloc',
            'c_loc',
            'c_sizeof',
            'ceiling',
            'char',
            'cmplx',
            'command_argument_count',
            'compiler_options',
            'compiler_version',
            'conjg',
            'cos',
            'cosh',
            'count',
            'cshift',
            'dble',
            'digits',
            'dim',
            'dot_product',
            'dprod',
            'dshiftl',
            'dshiftr',
            'eoshift',
            'epsilon',
            'erf',
            'erfc',
            'erfc_scaled',
            'exp',
            'exponent',
            'extends_type_of',
            'findloc',
            'floor',
            'fraction',
            'gamma',
            'huge',
            'hypot',
            'iachar',
            'iall',
            'iand',
            'iany',
            'ibclr',
            'ibits',
            'ibset',
            'ichar',
            'ieee_class',
            'ieee_copy_sign',
            'ieee_is_finite',
            'ieee_is_nan',
            'ieee_is_normal',
            'ieee_logb',
            'ieee_next_after',
            'ieee_rem',
            'ieee_rint',
            'ieee_scalb',
            'ieee_selected_real_kind',
            'ieee_support_datatype',
            'ieee_support_denormal',
            'ieee_support_divide',
            'ieee_support_flag',
            'ieee_support_halting',
            'ieee_support_inf',
            'ieee_support_io',
            'ieee_support_nan',
            'ieee_support_rounding',
            'ieee_support_sqrt',
            'ieee_support_standard',
            'ieee_support_underflow_control',
            'ieee_unordered',
            'ieee_value',
            'ieor',
            'image_index',
            'index',
            'int',
            'ior',
            'iparity',
            'ishft',
            'ishftc',
            'is_contiguous',
            'is_iostat_end',
            'is_iostat_eor',
            'kind',
            'lbound',
            'lcobound',
            'leadz',
            'len',
            'len_trim',
            'lge',
            'lgt',
            'lle',
            'llt',
            'log',
            'log_gamma',
            'log10',
            'logical',
            'maskl',
            'maskr',
            'matmul',
            'max',
            'maxexponent',
            'maxloc',
            'maxval',
            'merge',
            'merge_bits',
            'min',
            'minexponent',
            'minloc',
            'minval',
            'mod',
            'modulo',
            'nearest',
            'new_line',
            'nint',
            'norm2',
            'not',
            'null',
            'num_images',
            'pack',
            'parity',
            'popcnt',
            'poppar',
            'precision',
            'present',
            'product',
            'radix',
            'range',
            'real',
            'repeat',
            'reshape',
            'rrspacing',
            'same_type_as',
            'scale',
            'scan',
            'selected_char_kind',
            'selected_int_kind',
            'selected_real_kind',
            'set_exponent',
            'shape',
            'shifta',
            'shiftl',
            'shiftr',
            'sign',
            'sin',
            'sinh',
            'size',
            'spacing',
            'spread',
            'sqrt',
            'storage_size',
            'sum',
            'tan',
            'tanh',
            'this_image',
            'tiny',
            'trailz',
            'transfer',
            'transpose',
            'trim',
            'ubound',
            'ucobound',
            'unpack',
            'verify'
        ],

        subroutines: [
            'c_f_pointer',
            'c_f_procpointer',
            'cpu_time',
            'date_and_time',
            'execute_command_line',
            'get_command',
            'get_command_argument',
            'get_environment_variable',
            'ieee_get_flag',
            'ieee_get_halting_mode',
            'ieee_get_rounding_mode',
            'ieee_get_status',
            'ieee_get_underflow_mode',
            'ieee_set_flag',
            'ieee_set_halting_mode',
            'ieee_set_rounding_mode',
            'ieee_set_status',
            'ieee_set_underflow_mode',
            'move_alloc',
            'mvbits',
            'random_number',
            'random_seed',
            'system_clock'
        ],

        // we include these common regular expressions
        symbols: /[=><!~?:&|+\-*/^%]+/,
        escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,

        // The main tokenizer for our languages
        tokenizer: {
            root: [
		// type names
                [/[a-zA-Z][\w$]*(?=.*\:\:)/, {
		    cases: {
			'@typeKeywords': 'type.identifier',
                        '@keywords': 'keyword',
                        '@default': 'identifier'
		    }
		}],
                // identifiers and keywords
                [/[a-zA-Z][\w$]*/, {
                    cases: {
                        '@keywords': 'keyword',
                        '@functions': 'keyword',
                        '@subroutines': 'keyword',
                        '@default': 'identifier'
                    }
                }],

                // comments
                [/!.*$/, 'comment'],

                // whitespace
                {include: '@whitespace'},

                // delimiters and operators
                [/[{}()[\]]/, '@brackets'],
                [/[<>](?!@symbols)/, '@brackets'],
                [/@symbols/, {
                    cases: {
                        '@operators': 'operator',
                        '@default': ''
                    }
                }],

                // numbers
                [/\d*\.\d+([eE][-+]?\d+)?[fFdD]?/, 'number.float'],
                [/0[xX][0-9a-fA-F_]*[0-9a-fA-F][Ll]?/, 'number.hex'],
                [/0[0-7_]*[0-7][Ll]?/, 'number.octal'],
                [/0[bB][0-1_]*[0-1][Ll]?/, 'number.binary'],
                [/\d+[lL]?/, 'number'],

                // delimiter: after number because of .\d floats
                [/[;,.]/, 'delimiter'],

                // strings
                [/"([^"\\]|\\.)*$/, 'string.invalid'],  // non-teminated string
                [/"/, 'string', '@string'],

                // characters
                [/'[^\\']'/, 'string'],
                [/(')(@escapes)(')/, ['string', 'string.escape', 'string']],
                [/'/, 'string.invalid']
            ],

            whitespace: [
                [/[ \t\r\n]+/, 'white']
            ],

            comment: [
                [/!/, 'comment']
            ],

            string: [
                [/[^\\"]+/, 'string'],
                [/@escapes/, 'string.escape'],
                [/\\./, 'string.escape.invalid'],
                [/"/, 'string', '@pop']
            ],
        }
    };
}

function configuration() {
    return {
        comments: {
            lineComment: '!',
        },

        brackets: [
            ['(/', '/)'],
            ['[', ']'],
            ['(', ')']
        ],

        autoClosingPairs: [
            {open: '[', close: ']'},
            {open: '(', close: ')'},
            {open: '`', close: '`', notIn: ['string','comment']},
            {open: "'", close: "'", notIn: ['string','comment']},
            {open: '"', close: '"', notIn: ['string']}
        ],

        surroundingPairs: [
            {open: '[', close: ']'},
            {open: '(', close: ')'},
            {open: '`', close: '`'},
            {open: "'", close: "'"},
            {open: '"', close: '"'}
        ],

        indentationRules: {
            decreaseIndentPattern: /end\s*(do|if|function|subroutine|program|block|associate|forall)/,
            increaseIndentPattern: /^((?!end).)*(do\s|if(\s|\()|function\s|subroutine\s|program\s|block\s*|associate(\s|\()|forall)/,
            unIndentedLinePattern: null
        }
    };
}

var def = definition();

monaco.languages.register({id: 'fortran'});
monaco.languages.setMonarchTokensProvider('fortran', definition());
monaco.languages.setLanguageConfiguration('fortran', configuration());

module.exports = def;
<commit_msg>Pleasing linter once again<commit_after>// This file has evolved from
//    d-mode.js by Matt Godbolt
//    Copyright (c) 2017, Matt Godbolt
//    All rights reserved.
//
//    Redistribution and use in source and binary forms, with or without
//    modification, are permitted provided that the following conditions are met:
//
//        * Redistributions of source code must retain the above copyright notice,
//          this list of conditions and the following disclaimer.
//        * Redistributions in binary form must reproduce the above copyright
//          notice, this list of conditions and the following disclaimer in the
//          documentation and/or other materials provided with the distribution.
//
//    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
//    AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
//    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
//    ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
//    LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
//    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
//    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
//    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
//    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
//    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//    POSSIBILITY OF SUCH DAMAGE.
//
// The lists of keywords, operator, functions, and subroutines have been adopted from
//    vs.language.fortran by Thomas E. Dunn
"use strict";

function definition() {
    return {
        // Fortran is case insensitive, so ignore case...
        ignoreCase: true,

        defaultToken: 'invalid',

        keywords: [
            'abstract',
            'all',
            'allocatable',
            'allocate',
            'assign',
            'assignment',
            'asynchronous',
            'backspace',
            'bind',
            'block',
            'blockdata',
            'character',
            'close',
            'common',
            'complex',
            'concurrent',
            'contiguous',
            'call',
            'case',
            'class',
            'codimension',
            'contains',
            'continue',
            'cycle',
            'data',
            'deallocate',
            'deferred',
            'dimension',
            'do',
            'double',
            'doubleprecision',
            'elemental',
            'else',
            'elsewhere',
            'end',
            'endblock',
            'endblockdata',
            'enddo',
            'endenum',
            'endfile',
            'endforall',
            'endfunction',
            'endif',
            'endinterface',
            'endmodule',
            'endprogram',
            'endselect',
            'endsubmodule',
            'endsubroutine',
            'endtype',
            'endwhere',
            'endwhile',
            'entry',
            'enum',
            'enumerator',
            'equivalence',
            'error',
            'exit',
            'external',
            'final',
            'flush',
            'forall',
            'format',
            'function',
            'generic',
            'go',
            'goto',
            'if',
            'implicit',
            'import',
            'in',
            'include',
            'inout',
            'inquire',
            'intent',
            'interface',
            'intrinsic',
            'is',
            'logical',
            'module',
            'non_overridable',
            'none',
            'nopass',
            'nullify',
            'only',
            'open',
            'operator',
            'optional',
            'out',
            'parameter',
            'pass',
            'pause',
            'pointer',
            'precision',
            'print',
            'private',
            'procedure',
            'program',
            'protected',
            'public',
            'pure',
            'read',
            'real',
            'recursive',
            'result',
            'return',
            'rewind',
            'save',
            'select',
            'sequence',
            'stop',
            'submodule',
            'subroutine',
            'target',
            'then',
            'to',
            'type',
            'use',
            'value',
            'volatile',
            'wait',
            'where',
            'while',
            'write'
        ],

        typeKeywords: [
            'logical',
            'character',
            'real',
            'integer',
            'complex',
            'type'
        ],

        operators: [
            '=',
            '==',
            '/=',
            '>',
            '>=',
            '<',
            '<=',
            '=>',
            '+',
            '-',
            '*',
            '/',
            '**',
            '//',
            '.and.',
            '.eq.',
            '.eqv.',
            '.le.',
            '.lt.',
            '.ge.',
            '.gt.',
            '.ne.',
            '.neqv.',
            '.not.',
            '.or.'
        ],

        functions: [
            'abs',
            'achar',
            'acos',
            'acosh',
            'adjustl',
            'adjustr',
            'aimag',
            'aint',
            'all',
            'allocated',
            'anint',
            'any',
            'asin',
            'asinh',
            'associated',
            'atan',
            'atan2',
            'atanh',
            'bessel_j0',
            'bessel_j1',
            'bessel_jn',
            'bessel_y0',
            'bessel_y1',
            'bessel_yn',
            'bge',
            'bgt',
            'bit_size',
            'ble',
            'blt',
            'btest',
            'c_associated',
            'c_funloc',
            'c_loc',
            'c_sizeof',
            'ceiling',
            'char',
            'cmplx',
            'command_argument_count',
            'compiler_options',
            'compiler_version',
            'conjg',
            'cos',
            'cosh',
            'count',
            'cshift',
            'dble',
            'digits',
            'dim',
            'dot_product',
            'dprod',
            'dshiftl',
            'dshiftr',
            'eoshift',
            'epsilon',
            'erf',
            'erfc',
            'erfc_scaled',
            'exp',
            'exponent',
            'extends_type_of',
            'findloc',
            'floor',
            'fraction',
            'gamma',
            'huge',
            'hypot',
            'iachar',
            'iall',
            'iand',
            'iany',
            'ibclr',
            'ibits',
            'ibset',
            'ichar',
            'ieee_class',
            'ieee_copy_sign',
            'ieee_is_finite',
            'ieee_is_nan',
            'ieee_is_normal',
            'ieee_logb',
            'ieee_next_after',
            'ieee_rem',
            'ieee_rint',
            'ieee_scalb',
            'ieee_selected_real_kind',
            'ieee_support_datatype',
            'ieee_support_denormal',
            'ieee_support_divide',
            'ieee_support_flag',
            'ieee_support_halting',
            'ieee_support_inf',
            'ieee_support_io',
            'ieee_support_nan',
            'ieee_support_rounding',
            'ieee_support_sqrt',
            'ieee_support_standard',
            'ieee_support_underflow_control',
            'ieee_unordered',
            'ieee_value',
            'ieor',
            'image_index',
            'index',
            'int',
            'ior',
            'iparity',
            'ishft',
            'ishftc',
            'is_contiguous',
            'is_iostat_end',
            'is_iostat_eor',
            'kind',
            'lbound',
            'lcobound',
            'leadz',
            'len',
            'len_trim',
            'lge',
            'lgt',
            'lle',
            'llt',
            'log',
            'log_gamma',
            'log10',
            'logical',
            'maskl',
            'maskr',
            'matmul',
            'max',
            'maxexponent',
            'maxloc',
            'maxval',
            'merge',
            'merge_bits',
            'min',
            'minexponent',
            'minloc',
            'minval',
            'mod',
            'modulo',
            'nearest',
            'new_line',
            'nint',
            'norm2',
            'not',
            'null',
            'num_images',
            'pack',
            'parity',
            'popcnt',
            'poppar',
            'precision',
            'present',
            'product',
            'radix',
            'range',
            'real',
            'repeat',
            'reshape',
            'rrspacing',
            'same_type_as',
            'scale',
            'scan',
            'selected_char_kind',
            'selected_int_kind',
            'selected_real_kind',
            'set_exponent',
            'shape',
            'shifta',
            'shiftl',
            'shiftr',
            'sign',
            'sin',
            'sinh',
            'size',
            'spacing',
            'spread',
            'sqrt',
            'storage_size',
            'sum',
            'tan',
            'tanh',
            'this_image',
            'tiny',
            'trailz',
            'transfer',
            'transpose',
            'trim',
            'ubound',
            'ucobound',
            'unpack',
            'verify'
        ],

        subroutines: [
            'c_f_pointer',
            'c_f_procpointer',
            'cpu_time',
            'date_and_time',
            'execute_command_line',
            'get_command',
            'get_command_argument',
            'get_environment_variable',
            'ieee_get_flag',
            'ieee_get_halting_mode',
            'ieee_get_rounding_mode',
            'ieee_get_status',
            'ieee_get_underflow_mode',
            'ieee_set_flag',
            'ieee_set_halting_mode',
            'ieee_set_rounding_mode',
            'ieee_set_status',
            'ieee_set_underflow_mode',
            'move_alloc',
            'mvbits',
            'random_number',
            'random_seed',
            'system_clock'
        ],

        // we include these common regular expressions
        symbols: /[=><!~?:&|+\-*/^%]+/,
        escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,

        // The main tokenizer for our languages
        tokenizer: {
            root: [
                // type names
                [/[a-zA-Z][\w$]*(?=.*::)/, {
                    cases: {
                        '@typeKeywords': 'type.identifier',
                        '@keywords': 'keyword',
                        '@default': 'identifier'
                    }
                }],
                // identifiers and keywords
                [/[a-zA-Z][\w$]*/, {
                    cases: {
                        '@keywords': 'keyword',
                        '@functions': 'keyword',
                        '@subroutines': 'keyword',
                        '@default': 'identifier'
                    }
                }],

                // comments
                [/!.*$/, 'comment'],

                // whitespace
                {include: '@whitespace'},

                // delimiters and operators
                [/[{}()[\]]/, '@brackets'],
                [/[<>](?!@symbols)/, '@brackets'],
                [/@symbols/, {
                    cases: {
                        '@operators': 'operator',
                        '@default': ''
                    }
                }],

                // numbers
                [/\d*\.\d+([eE][-+]?\d+)?[fFdD]?/, 'number.float'],
                [/0[xX][0-9a-fA-F_]*[0-9a-fA-F][Ll]?/, 'number.hex'],
                [/0[0-7_]*[0-7][Ll]?/, 'number.octal'],
                [/0[bB][0-1_]*[0-1][Ll]?/, 'number.binary'],
                [/\d+[lL]?/, 'number'],

                // delimiter: after number because of .\d floats
                [/[;,.]/, 'delimiter'],

                // strings
                [/"([^"\\]|\\.)*$/, 'string.invalid'],  // non-teminated string
                [/"/, 'string', '@string'],

                // characters
                [/'[^\\']'/, 'string'],
                [/(')(@escapes)(')/, ['string', 'string.escape', 'string']],
                [/'/, 'string.invalid']
            ],

            whitespace: [
                [/[ \t\r\n]+/, 'white']
            ],

            comment: [
                [/!/, 'comment']
            ],

            string: [
                [/[^\\"]+/, 'string'],
                [/@escapes/, 'string.escape'],
                [/\\./, 'string.escape.invalid'],
                [/"/, 'string', '@pop']
            ],
        }
    };
}

function configuration() {
    return {
        comments: {
            lineComment: '!',
        },

        brackets: [
            ['(/', '/)'],
            ['[', ']'],
            ['(', ')']
        ],

        autoClosingPairs: [
            {open: '[', close: ']'},
            {open: '(', close: ')'},
            {open: '`', close: '`', notIn: ['string','comment']},
            {open: "'", close: "'", notIn: ['string','comment']},
            {open: '"', close: '"', notIn: ['string']}
        ],

        surroundingPairs: [
            {open: '[', close: ']'},
            {open: '(', close: ')'},
            {open: '`', close: '`'},
            {open: "'", close: "'"},
            {open: '"', close: '"'}
        ],

        indentationRules: {
            decreaseIndentPattern: /end\s*(do|if|function|subroutine|program|block|associate|forall)/,
            increaseIndentPattern: /^((?!end).)*(do\s|if(\s|\()|function\s|subroutine\s|program\s|block\s*|associate(\s|\()|forall)/,
            unIndentedLinePattern: null
        }
    };
}

var def = definition();

monaco.languages.register({id: 'fortran'});
monaco.languages.setMonarchTokensProvider('fortran', definition());
monaco.languages.setLanguageConfiguration('fortran', configuration());

module.exports = def;
<|endoftext|>


<commit_before>/*jslint indent:2,white:true,sloppy:true,node:true */
/*
 * freedom.js Node runtime
 */

'use strict';

var fdom = module.exports = {};

module.exports.freedom = fdom.setup(global, undefined, {
  portType: 'Node',
  isApp: false,
  stayLocal: true
});
delete global.fdom;
<commit_msg>reapair node node functionality from bad merge<commit_after>
/*jslint indent:2,white:true,sloppy:true,node:true */
/*
 * freedom.js Node runtime
 */

'use strict';

var sources = [
  '/..',
  '/../link',
  '/../proxy',
  '/../../interface'
];

sources.forEach(function(dir) {
  require('fs').readdirSync(__dirname + dir).forEach(function(file) {
    if (file.match(/.+\.js/) !== null) {
      require(__dirname + dir + '/' + file);
    }
  });
});

module.exports.freedom = fdom.setup(global, undefined, {
  portType: 'Node',
  isApp: false,
  stayLocal: true
});
delete global.fdom;
<|endoftext|>


<commit_before>'use strict';

var _ = module.exports;

var TOUCH_EVENT = 1;
var MOUSE_EVENT = 2;
var POINTER_EVENT = 3;

var elementStyle = document.createElement('div').style;

var vendor = (function () {

	var transformNames = {
		standard: 'transform',
		webkit: 'webkitTransform',
		Moz: 'MozTransform',
		O: 'OTransform',
		ms: 'msTransform'
	};

	for (var key in transformNames) {
		if (elementStyle[transformNames[key]] !== undefined) {
			return key;
		}
	}

	return false;
})();

function prefixStyle(style) {
	if (vendor === false)
		return false;

	if (vendor === 'standard') {
		return style;
	}

	return vendor + style.charAt(0).toUpperCase() + style.substr(1);
}

_.extend = function (target, obj) {
	for (var key in obj) {
		target[key] = obj[key];
	}
};

_.addEvent = function (el, type, fn, capture) {
	el.addEventListener(type, fn, !!capture);
};

_.removeEvent = function (el, type, fn, capture) {
	el.removeEventListener(type, fn, !!capture);
};

_.hasClass = function (el, className) {
	var reg = new RegExp('(^|\\s)' + className + '(\\s|$)');
	return reg.test(el.className);
};

_.addClass = function (el, className) {
	if (el.hasClass(el, className))
		return;

	var newClass = el.className.split(' ');
	newClass.push(className);
	el.className = newClass.join(' ');
};

_.removeClass = function (el, className) {
	if (!el.hasClass(el, className))
		return;

	var reg = new RegExp('(^|\\s)' + className + '(\\s|$)', 'g');
	el.className = el.className.replace(reg, ' ');
};

_.offset = function (el) {
	var left = 0;
	var top = 0;

	while (el) {
		left -= el.offsetLeft;
		top -= el.offsetTop;
		el = el.offsetParent;
	}

	return {
		left: left,
		top: top
	};
};

_.prefixPointerEvent = function (pointerEvent) {
	return window.MSPointerEvent ?
	'MSPointer' + pointerEvent.charAt(9).toUpperCase() + pointerEvent.substr(10) :
		pointerEvent;
};

_.preventDefaultException = function (el, exceptions) {
	for (var i in exceptions) {
		if (exceptions[i].test(el)) {
			return true;
		}
	}

	return false;
};

_.tap = function (e, eventName) {
	var ev = document.createEvent('Event');
	ev.initEvent(eventName, true, true);
	ev.pageX = e.pageX;
	ev.pageY = e.pageY;
	e.target.dispatchEvent(ev);
};

_.click = function (e) {
	var target = e.target;

	if (!(/(SELECT|INPUT|TEXTAREA)/i).test(target.tagName)) {
		var ev = new MouseEvent('click', {
			bubbles: true,
			cancelable: true,
			view: e.view,
			screenX: target.screenX,
			screenY: target.screenY,
			clientX: target.clientX,
			clientY: target.clientY,
			ctrlKey: e.ctrlKey,
			altKey: e.altKey,
			shiftKey: e.shiftKey,
			metaKey: e.metaKey
		});
		e._constructed = true;
		target.dispatchEvent(ev);
	}

};

_.momentum = function (current, start, time, lowerMargin, wrapperSize, options) {
	var distance = current - start;
	var speed = Math.abs(distance) / time;

	var deceleration = options.deceleration || 0.001;
	var duration = options.swipeTime || 2500;

	var destination = current + speed / deceleration * ( distance < 0 ? -1 : 1 );

	if (destination < lowerMargin) {
		destination = wrapperSize ? lowerMargin - ( wrapperSize / 2.5 * ( speed / 8 ) ) : lowerMargin;
		duration = (options.swipeBounceTime || 1000) - (options.bounceTime || 400);
		//distance = Math.abs(destination - current);
	} else if (destination > 0) {
		destination = wrapperSize ? wrapperSize / 2.5 * ( speed / 8 ) : 0;
		duration = (options.swipeBounceTime || 1000) - (options.bounceTime || 400);
		//distance = Math.abs(current) + destination;
	}

	return {
		destination: Math.round(destination),
		duration: duration
	};
};

// This should find all Android browsers lower than build 535.19 (both stock browser and webview)
_.isBadAndroid = /Android /.test(window.navigator.appVersion) && !(/Chrome\/\d/.test(window.navigator.appVersion));

var transform = prefixStyle('transform');

_.extend(_, {
	hasTransform: transform !== false,
	hasPerspective: prefixStyle('perspective') in elementStyle,
	hasTouch: 'ontouchstart' in window,
	// IE10 is prefixed
	hasPointer: window.PointerEvent || window.MSPointerEvent,
	hasTransition: prefixStyle('transition') in elementStyle
});

_.style = {};

_.extend(_.style, {
	transform: transform,
	transitionTimingFunction: prefixStyle('transitionTimingFunction'),
	transitionDuration: prefixStyle('transitionDuration'),
	transitionDelay: prefixStyle('transitionDelay'),
	transformOrigin: prefixStyle('transformOrigin'),
	transitionEnd: prefixStyle('transitionEnd')
});

_.eventType = {};

_.extend(_.eventType, {
	touchstart: TOUCH_EVENT,
	touchmove: TOUCH_EVENT,
	touchend: TOUCH_EVENT,

	mousedown: MOUSE_EVENT,
	mousemove: MOUSE_EVENT,
	mouseup: MOUSE_EVENT,

	pointerdown: POINTER_EVENT,
	pointermove: POINTER_EVENT,
	pointerup: POINTER_EVENT,

	MSPointerDown: POINTER_EVENT,
	MSPointerMove: POINTER_EVENT,
	MSPointerUp: POINTER_EVENT
});

_.ease = {};

_.extend(_.ease, {
	//easeOutQuint
	swipe: {
		style: 'cubic-bezier(0.23, 1, 0.32, 1)',
		fn: function (t) {
			return 1 + ( --t * t * t * t * t);
		}
	},
	//easeOutQuard
	swipeBounce: {
		style: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)',
		fn: function (t) {
			return t * (2 - t);
		}
	},
	//easeOutQuart
	bounce: {
		style: 'cubic-bezier(0.165, 0.84, 0.44, 1)',
		fn: function (t) {
			return 1 - ( --t * t * t * t);
		}
	}
});
<commit_msg>bug fi<commit_after>'use strict';

var _ = module.exports;

var TOUCH_EVENT = 1;
var MOUSE_EVENT = 2;
var POINTER_EVENT = 3;

var elementStyle = document.createElement('div').style;

var vendor = (function () {

	var transformNames = {
		standard: 'transform',
		webkit: 'webkitTransform',
		Moz: 'MozTransform',
		O: 'OTransform',
		ms: 'msTransform'
	};

	for (var key in transformNames) {
		if (elementStyle[transformNames[key]] !== undefined) {
			return key;
		}
	}

	return false;
})();

function prefixStyle(style) {
	if (vendor === false)
		return false;

	if (vendor === 'standard') {
		return style;
	}

	return vendor + style.charAt(0).toUpperCase() + style.substr(1);
}

_.extend = function (target, obj) {
	for (var key in obj) {
		target[key] = obj[key];
	}
};

_.addEvent = function (el, type, fn, capture) {
	el.addEventListener(type, fn, !!capture);
};

_.removeEvent = function (el, type, fn, capture) {
	el.removeEventListener(type, fn, !!capture);
};

_.hasClass = function (el, className) {
	var reg = new RegExp('(^|\\s)' + className + '(\\s|$)');
	return reg.test(el.className);
};

_.addClass = function (el, className) {
	if (_.hasClass(el, className))
		return;

	var newClass = el.className.split(' ');
	newClass.push(className);
	el.className = newClass.join(' ');
};

_.removeClass = function (el, className) {
	if (!_.hasClass(el, className))
		return;

	var reg = new RegExp('(^|\\s)' + className + '(\\s|$)', 'g');
	el.className = el.className.replace(reg, ' ');
};

_.offset = function (el) {
	var left = 0;
	var top = 0;

	while (el) {
		left -= el.offsetLeft;
		top -= el.offsetTop;
		el = el.offsetParent;
	}

	return {
		left: left,
		top: top
	};
};

_.prefixPointerEvent = function (pointerEvent) {
	return window.MSPointerEvent ?
	'MSPointer' + pointerEvent.charAt(9).toUpperCase() + pointerEvent.substr(10) :
		pointerEvent;
};

_.preventDefaultException = function (el, exceptions) {
	for (var i in exceptions) {
		if (exceptions[i].test(el)) {
			return true;
		}
	}

	return false;
};

_.tap = function (e, eventName) {
	var ev = document.createEvent('Event');
	ev.initEvent(eventName, true, true);
	ev.pageX = e.pageX;
	ev.pageY = e.pageY;
	e.target.dispatchEvent(ev);
};

_.click = function (e) {
	var target = e.target;

	if (!(/(SELECT|INPUT|TEXTAREA)/i).test(target.tagName)) {
		var ev = new MouseEvent('click', {
			bubbles: true,
			cancelable: true,
			view: e.view,
			screenX: target.screenX,
			screenY: target.screenY,
			clientX: target.clientX,
			clientY: target.clientY,
			ctrlKey: e.ctrlKey,
			altKey: e.altKey,
			shiftKey: e.shiftKey,
			metaKey: e.metaKey
		});
		e._constructed = true;
		target.dispatchEvent(ev);
	}

};

_.momentum = function (current, start, time, lowerMargin, wrapperSize, options) {
	var distance = current - start;
	var speed = Math.abs(distance) / time;

	var deceleration = options.deceleration || 0.001;
	var duration = options.swipeTime || 2500;

	var destination = current + speed / deceleration * ( distance < 0 ? -1 : 1 );

	if (destination < lowerMargin) {
		destination = wrapperSize ? lowerMargin - ( wrapperSize / 2.5 * ( speed / 8 ) ) : lowerMargin;
		duration = (options.swipeBounceTime || 1000) - (options.bounceTime || 400);
		//distance = Math.abs(destination - current);
	} else if (destination > 0) {
		destination = wrapperSize ? wrapperSize / 2.5 * ( speed / 8 ) : 0;
		duration = (options.swipeBounceTime || 1000) - (options.bounceTime || 400);
		//distance = Math.abs(current) + destination;
	}

	return {
		destination: Math.round(destination),
		duration: duration
	};
};

// This should find all Android browsers lower than build 535.19 (both stock browser and webview)
_.isBadAndroid = /Android /.test(window.navigator.appVersion) && !(/Chrome\/\d/.test(window.navigator.appVersion));

var transform = prefixStyle('transform');

_.extend(_, {
	hasTransform: transform !== false,
	hasPerspective: prefixStyle('perspective') in elementStyle,
	hasTouch: 'ontouchstart' in window,
	// IE10 is prefixed
	hasPointer: window.PointerEvent || window.MSPointerEvent,
	hasTransition: prefixStyle('transition') in elementStyle
});

_.style = {};

_.extend(_.style, {
	transform: transform,
	transitionTimingFunction: prefixStyle('transitionTimingFunction'),
	transitionDuration: prefixStyle('transitionDuration'),
	transitionDelay: prefixStyle('transitionDelay'),
	transformOrigin: prefixStyle('transformOrigin'),
	transitionEnd: prefixStyle('transitionEnd')
});

_.eventType = {};

_.extend(_.eventType, {
	touchstart: TOUCH_EVENT,
	touchmove: TOUCH_EVENT,
	touchend: TOUCH_EVENT,

	mousedown: MOUSE_EVENT,
	mousemove: MOUSE_EVENT,
	mouseup: MOUSE_EVENT,

	pointerdown: POINTER_EVENT,
	pointermove: POINTER_EVENT,
	pointerup: POINTER_EVENT,

	MSPointerDown: POINTER_EVENT,
	MSPointerMove: POINTER_EVENT,
	MSPointerUp: POINTER_EVENT
});

_.ease = {};

_.extend(_.ease, {
	//easeOutQuint
	swipe: {
		style: 'cubic-bezier(0.23, 1, 0.32, 1)',
		fn: function (t) {
			return 1 + ( --t * t * t * t * t);
		}
	},
	//easeOutQuard
	swipeBounce: {
		style: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)',
		fn: function (t) {
			return t * (2 - t);
		}
	},
	//easeOutQuart
	bounce: {
		style: 'cubic-bezier(0.165, 0.84, 0.44, 1)',
		fn: function (t) {
			return 1 - ( --t * t * t * t);
		}
	}
});
<|endoftext|>


<commit_before>/* ======= Global Utilities ======= */

/**
* Converts attributes into key-value pairs
* @param {Node} node
* @return {Object} Key-Value pairs of Attributes
*/
var extractAttrs = function(node) {
  var attrs = {};
  if(!node.attributes) return attrs;
  var rawAttrs = node.attributes;
  for(var i = 0; i < rawAttrs.length; i++) {
    attrs[rawAttrs[i].name] = rawAttrs[i].value
  }

  return attrs;
}

/**
* Compiles a template with given data
* @param {String} template
* @param {Object} data
* @return {String} Template with data rendered
*/
var compileTemplate = function(template, data) {
  var code = template,
      re = /{{([A-Za-z0-9_.()\[\]]+)}}/gi;
  code.replace(re, function(match, p) {
    code = code.replace(match, "` + data." + p + " + `");
  });
  var compile = new Function("data", "var out = `" + code + "`; return out");
  var output = compile(data);
  return output;
}

/**
* Gets Root Element
* @param {String} html
* @return {Node} Root Element
*/
var getRootElement = function(html) {
  var dummy = document.createElement('div');
  dummy.innerHTML = html;
  return dummy.firstChild;
}

/**
* Merges two Objects
* @param {Object} obj
* @param {Object} obj2
* @return {Object} Merged Objects
*/
function merge(obj, obj2) {
  for (var key in obj2) {
    if (obj2.hasOwnProperty(key)) obj[key] = obj2[key];
  }
  return obj;
}

/**
* Creates an object to be used in a Virtual DOM
* @param {String} type
* @param {Array} children
* @param {String} val
* @param {Object} props
* @param {Node} node
* @return {Object} Object usable in Virtual DOM
*/
var createElement = function(type, children, val, props, node) {
  return {type: type, children: children, val: val, props: props, node: node};
}

/**
* Create Elements Recursively For all Children
* @param {Array} children
* @return {Array} Array of elements usable in Virtual DOM
*/
var recursiveChildren = function(children) {
  var recursiveChildrenArr = [];
  for(var i = 0; i < children.length; i++) {
    var child = children[i];
    recursiveChildrenArr.push(createElement(child.nodeName, recursiveChildren(child.childNodes), child.textContent, extractAttrs(child), child));
  }
  return recursiveChildrenArr;
}

/**
* Creates Virtual DOM
* @param {Node} node
* @return {Object} Virtual DOM
*/
var createVirtualDOM = function(node) {
  var vdom = createElement(node.nodeName, recursiveChildren(node.childNodes), node.textContent, extractAttrs(node), node);
  return vdom;
}

/**
 * Compiles JSX to HTML
 * @param {String} tag
 * @param {Object} attrs
 * @param {Array} children
 * @return {String} HTML compiled from JSX
 */
var h = function(tag, attrs, children) {
	return "<" + tag + Object.keys(attrs||{}).reduce(function(total, current) {return (total||" ") + current + "='" + attrs[current] + "'"}, "") + ">" + children + "<" + tag + "/>";
};

var setInitialElementValue = function(el, value) {

}
/**
 * Does No Operation
 */
var noop = function() {

}
<commit_msg>initial element value wrapper<commit_after>/* ======= Global Utilities ======= */

/**
* Converts attributes into key-value pairs
* @param {Node} node
* @return {Object} Key-Value pairs of Attributes
*/
var extractAttrs = function(node) {
  var attrs = {};
  if(!node.attributes) return attrs;
  var rawAttrs = node.attributes;
  for(var i = 0; i < rawAttrs.length; i++) {
    attrs[rawAttrs[i].name] = rawAttrs[i].value
  }

  return attrs;
}

/**
* Compiles a template with given data
* @param {String} template
* @param {Object} data
* @return {String} Template with data rendered
*/
var compileTemplate = function(template, data) {
  var code = template,
      re = /{{([A-Za-z0-9_.()\[\]]+)}}/gi;
  code.replace(re, function(match, p) {
    code = code.replace(match, "` + data." + p + " + `");
  });
  var compile = new Function("data", "var out = `" + code + "`; return out");
  var output = compile(data);
  return output;
}

/**
* Gets Root Element
* @param {String} html
* @return {Node} Root Element
*/
var getRootElement = function(html) {
  var dummy = document.createElement('div');
  dummy.innerHTML = html;
  return dummy.firstChild;
}

/**
* Merges two Objects
* @param {Object} obj
* @param {Object} obj2
* @return {Object} Merged Objects
*/
function merge(obj, obj2) {
  for (var key in obj2) {
    if (obj2.hasOwnProperty(key)) obj[key] = obj2[key];
  }
  return obj;
}

/**
* Creates an object to be used in a Virtual DOM
* @param {String} type
* @param {Array} children
* @param {String} val
* @param {Object} props
* @param {Node} node
* @return {Object} Object usable in Virtual DOM
*/
var createElement = function(type, children, val, props, node) {
  return {type: type, children: children, val: val, props: props, node: node};
}

/**
* Create Elements Recursively For all Children
* @param {Array} children
* @return {Array} Array of elements usable in Virtual DOM
*/
var recursiveChildren = function(children) {
  var recursiveChildrenArr = [];
  for(var i = 0; i < children.length; i++) {
    var child = children[i];
    recursiveChildrenArr.push(createElement(child.nodeName, recursiveChildren(child.childNodes), child.textContent, extractAttrs(child), child));
  }
  return recursiveChildrenArr;
}

/**
* Creates Virtual DOM
* @param {Node} node
* @return {Object} Virtual DOM
*/
var createVirtualDOM = function(node) {
  var vdom = createElement(node.nodeName, recursiveChildren(node.childNodes), node.textContent, extractAttrs(node), node);
  return vdom;
}

/**
 * Compiles JSX to HTML
 * @param {String} tag
 * @param {Object} attrs
 * @param {Array} children
 * @return {String} HTML compiled from JSX
 */
var h = function(tag, attrs, children) {
	return "<" + tag + Object.keys(attrs||{}).reduce(function(total, current) {return (total||" ") + current + "='" + attrs[current] + "'"}, "") + ">" + children + "<" + tag + "/>";
};

/**
 * Sets the Elements Initial Value
 * @param {Node} el
 * @param {String} value
 */
var setInitialElementValue = function(el, value) {

}

/**
 * Does No Operation
 */
var noop = function() {

}
<|endoftext|>


<commit_before>/* ======= Global Utilities ======= */

/**
 * Logs a Message
 * @param {String} msg
 */
var log = function(msg) {
  if(!Moon.config.silent) console.log(msg);
}

/**
 * Throws an Error
 * @param {String} msg
 */
var error = function(msg) {
  console.error("[Moon] ERR: " + msg);
}

/**
 * Converts attributes into key-value pairs
 * @param {Node} node
 * @return {Object} Key-Value pairs of Attributes
 */
var extractAttrs = function(node) {
  var attrs = {};
  for(var rawAttrs = node.attributes, i = rawAttrs.length; i--;) {
    attrs[rawAttrs[i].name] = rawAttrs[i].value;
  }
  node.__moon__attrs__ = attrs;
  return attrs;
}

/**
 * Gives Default Metadata for a VNode
 * @return {Object} metadata
 */
var defaultMetadata = function() {
  return {
    shouldRender: true,
    component: false,
    eventListeners: {}
  }
}

/**
 * Escapes a String
 * @param {String} str
 */
var escapeString = function(str) {
	var NEWLINE_RE = /\n/g;
	var DOUBLE_QUOTE_RE = /"/g;
  return str.replace(NEWLINE_RE, "\\n").replace(DOUBLE_QUOTE_RE, "\\\"");
}

/**
 * Compiles a Template
 * @param {String} template
 * @param {Boolean} isString
 * @return {String} compiled template
 */
var compileTemplate = function(template, isString, customCode) {
  var TEMPLATE_RE = /{{([A-Za-z0-9_]+)([A-Za-z0-9_.()\[\]]+)?}}/gi;
  var compiled = template;
  template.replace(TEMPLATE_RE, function(match, key, modifiers) {
    if(!modifiers) {
      modifiers = '';
    }
    if(customCode) {
      compiled = customCode(compiled, match, key, modifiers);
    } else if(isString) {
      compiled = compiled.replace(match, `" + instance.get("${key}")${modifiers} + "`);
    } else {
      compiled = compiled.replace(match, `instance.get("${key}")${modifiers}`);
    }
  });
  return compiled;
}

/**
 * Creates a Virtual DOM Node
 * @param {String} type
 * @param {String} val
 * @param {Object} props
 * @param {Array} children
 * @param {Object} meta
 * @return {Object} Virtual DOM Node
 */
var createElement = function(type, val, props, children, meta) {
  return {
    type: type,
    val: val,
    props: props,
    children: children,
    meta: meta || defaultMetadata()
  };
}

/**
 * Normalizes Children
 * @param {*} children
 * @return {Object} Normalized Child
 */
 var normalizeChildren = function(children) {
   var normalizedChildren = [];
   for(var i = 0; i < children.length; i++) {
     var child = children[i];
     if(Array.isArray(child)) {
       normalizedChildren = normalizedChildren.concat(normalizeChildren(child));
     } else if(typeof child === "string" || child === null) {
       normalizedChildren.push(createElement("#text", child || "", {}, [], defaultMetadata()));
     } else {
       normalizedChildren.push(child);
     }
   }
   return normalizedChildren;
 }

/**
 * Compiles Arguments to a VNode
 * @param {String} tag
 * @param {Object} attrs
 * @param {Object} meta
 * @param {Array} children
 * @return {String} Object usable in Virtual DOM (VNode)
 */
var h = function() {
  var args = Array.prototype.slice.call(arguments);
  var tag = args.shift();
  var attrs = args.shift() || {};
  var meta = args.shift();
  var children = normalizeChildren(args);
  return createElement(tag, children.join(""), attrs, children, meta);
};

/**
 * Adds metadata Event Listeners to an Element
 * @param {Object} node
 * @param {Object} vnode
 * @param {Object} instance
 */
var addEventListeners = function(node, vnode, instance) {
  var eventListeners = vnode.meta.eventListeners;
  for(var type in eventListeners) {
    for(var i = 0; i < eventListeners[type].length; i++) {
      var method = eventListeners[type][i];
      if(instance.$events[type]) {
        instance.on(type, method);
      } else {
        node.addEventListener(type, method);
      }
    }
  }
}

/**
 * Creates DOM Node from VNode
 * @param {Object} vnode
 * @param {Object} instance
 * @return {Object} DOM Node
 */
var createNodeFromVNode = function(vnode, instance) {
  var el;

  if(vnode.type === "#text") {
    el = document.createTextNode(vnode.val);
  } else {
    el = document.createElement(vnode.type);
    for(var i = 0; i < vnode.children.length; i++) {
      el.appendChild(createNodeFromVNode(vnode.children[i], instance, true));
    }
    addEventListeners(el, vnode, instance);
  }
  diffProps(el, {}, vnode.props, vnode);
  return el;
}

/**
 * Diffs Props of Node and a VNode, and apply Changes
 * @param {Object} node
 * @param {Object} nodeProps
 * @param {Object} vnodeProps
 * @param {Object} vnode
 */
var diffProps = function(node, nodeProps, vnodeProps, vnode) {
  // Get object of all properties being compared
  var allProps = merge(nodeProps, vnodeProps);

  for(var propName in allProps) {
    // If not in VNode or is a Directive, remove it
    if(!vnodeProps[propName] || directives[propName] || specialDirectives[propName]) {
      // If it is a directive, run the directive
      if(directives[propName]) {
        directives[propName](node, allProps[propName], vnode);
      }
      node.removeAttribute(propName);
    } else if(!nodeProps[propName] || nodeProps[propName] !== vnodeProps[propName]) {
      // It has changed or is not in the node in the first place
      node.setAttribute(propName, vnodeProps[propName]);
    }
  }
}

/**
 * Diffs Node and a VNode, and applies Changes
 * @param {Object} node
 * @param {Object} vnode
 * @param {Object} parent
 * @param {Object} instance
 * @return {Object} adjusted node
 */
var diff = function(node, vnode, parent, instance) {
  var nodeName;

  if(node) {
    nodeName = node.nodeName.toLowerCase();
  }

  if((vnode && vnode.meta.shouldRender) || (!vnode)) {
    if(!node) {
      // No node, add it
      parent.appendChild(createNodeFromVNode(vnode, instance));
    } else if(!vnode) {
      // No VNode, remove the node
      parent.removeChild(node);
    } else if(nodeName !== vnode.type) {
      // Different types of Nodes, replace the node
      parent.replaceChild(createNodeFromVNode(vnode, instance), node);
    } else if(nodeName === "#text" && vnode.type === "#text") {
      // Both are text, set the text
      node.textContent = vnode.val;
    } else if(vnode.children.length === 0 && !node.firstChild.nextSibling && node.firstChild.nodeName === "#text" && vnode.children[0].type === "#text") {
      // Optimization:
      //  If the node and vnode contain a single text node, update it here
      node.firstChild.textContent = vnode.children[0].val;
    } else if(vnode.type) {
      // Diff properties
      var nodeProps = node.__moon__attrs__ || extractAttrs(node);
      diffProps(node, nodeProps, vnode.props, vnode);

      if(instance.$initialRender) {
        addEventListeners(node, vnode, instance);
      }

      // Diff children
      var currentChildNode = node.firstChild;
      for(var i = 0; i < vnode.children.length || currentChildNode; i++) {
        diff(currentChildNode, vnode.children[i], node, instance);
        currentChildNode = (currentChildNode ? currentChildNode.nextSibling : null);
      }
    }
  } else if(vnode && !vnode.meta.shouldRender && vnode.props[Moon.config.prefix + "pre"]) {
    // Not Rendering as a result of the "Pre" Directive, remove it
    node.removeAttribute(Moon.config.prefix + "pre");
  }
}

/**
 * Extends an Object with another Object's properties
 * @param {Object} parent
 * @param {Object} child
 * @return {Object} Extended Parent
 */
var extend = function(parent, child) {
  for (var key in child) {
    parent[key] = child[key];
  }
  return parent;
}

/**
 * Merges Two Objects Together
 * @param {Object} parent
 * @param {Object} child
 * @return {Object} Merged Object
 */
var merge = function(parent, child) {
  var merged = {};
  for(var key in parent) {
    merged[key] = parent[key];
  }
  for (var key in child) {
    merged[key] = child[key];
  }
  return merged;
}

/**
 * Calls a Hook
 * @param {Object} instance
 * @param {String} name
 */
var callHook = function(instance, name) {
  var hook = instance.$hooks[name];
  if(hook) {
    hook();
  }
}

/**
 * Does No Operation
 */
var noop = function() {

}
<commit_msg>don't recursively do true<commit_after>/* ======= Global Utilities ======= */

/**
 * Logs a Message
 * @param {String} msg
 */
var log = function(msg) {
  if(!Moon.config.silent) console.log(msg);
}

/**
 * Throws an Error
 * @param {String} msg
 */
var error = function(msg) {
  console.error("[Moon] ERR: " + msg);
}

/**
 * Converts attributes into key-value pairs
 * @param {Node} node
 * @return {Object} Key-Value pairs of Attributes
 */
var extractAttrs = function(node) {
  var attrs = {};
  for(var rawAttrs = node.attributes, i = rawAttrs.length; i--;) {
    attrs[rawAttrs[i].name] = rawAttrs[i].value;
  }
  node.__moon__attrs__ = attrs;
  return attrs;
}

/**
 * Gives Default Metadata for a VNode
 * @return {Object} metadata
 */
var defaultMetadata = function() {
  return {
    shouldRender: true,
    component: false,
    eventListeners: {}
  }
}

/**
 * Escapes a String
 * @param {String} str
 */
var escapeString = function(str) {
	var NEWLINE_RE = /\n/g;
	var DOUBLE_QUOTE_RE = /"/g;
  return str.replace(NEWLINE_RE, "\\n").replace(DOUBLE_QUOTE_RE, "\\\"");
}

/**
 * Compiles a Template
 * @param {String} template
 * @param {Boolean} isString
 * @return {String} compiled template
 */
var compileTemplate = function(template, isString, customCode) {
  var TEMPLATE_RE = /{{([A-Za-z0-9_]+)([A-Za-z0-9_.()\[\]]+)?}}/gi;
  var compiled = template;
  template.replace(TEMPLATE_RE, function(match, key, modifiers) {
    if(!modifiers) {
      modifiers = '';
    }
    if(customCode) {
      compiled = customCode(compiled, match, key, modifiers);
    } else if(isString) {
      compiled = compiled.replace(match, `" + instance.get("${key}")${modifiers} + "`);
    } else {
      compiled = compiled.replace(match, `instance.get("${key}")${modifiers}`);
    }
  });
  return compiled;
}

/**
 * Creates a Virtual DOM Node
 * @param {String} type
 * @param {String} val
 * @param {Object} props
 * @param {Array} children
 * @param {Object} meta
 * @return {Object} Virtual DOM Node
 */
var createElement = function(type, val, props, children, meta) {
  return {
    type: type,
    val: val,
    props: props,
    children: children,
    meta: meta || defaultMetadata()
  };
}

/**
 * Normalizes Children
 * @param {*} children
 * @return {Object} Normalized Child
 */
 var normalizeChildren = function(children) {
   var normalizedChildren = [];
   for(var i = 0; i < children.length; i++) {
     var child = children[i];
     if(Array.isArray(child)) {
       normalizedChildren = normalizedChildren.concat(normalizeChildren(child));
     } else if(typeof child === "string" || child === null) {
       normalizedChildren.push(createElement("#text", child || "", {}, [], defaultMetadata()));
     } else {
       normalizedChildren.push(child);
     }
   }
   return normalizedChildren;
 }

/**
 * Compiles Arguments to a VNode
 * @param {String} tag
 * @param {Object} attrs
 * @param {Object} meta
 * @param {Array} children
 * @return {String} Object usable in Virtual DOM (VNode)
 */
var h = function() {
  var args = Array.prototype.slice.call(arguments);
  var tag = args.shift();
  var attrs = args.shift() || {};
  var meta = args.shift();
  var children = normalizeChildren(args);
  return createElement(tag, children.join(""), attrs, children, meta);
};

/**
 * Adds metadata Event Listeners to an Element
 * @param {Object} node
 * @param {Object} vnode
 * @param {Object} instance
 */
var addEventListeners = function(node, vnode, instance) {
  var eventListeners = vnode.meta.eventListeners;
  for(var type in eventListeners) {
    for(var i = 0; i < eventListeners[type].length; i++) {
      var method = eventListeners[type][i];
      if(instance.$events[type]) {
        instance.on(type, method);
      } else {
        node.addEventListener(type, method);
      }
    }
  }
}

/**
 * Creates DOM Node from VNode
 * @param {Object} vnode
 * @param {Object} instance
 * @return {Object} DOM Node
 */
var createNodeFromVNode = function(vnode, instance) {
  var el;

  if(vnode.type === "#text") {
    el = document.createTextNode(vnode.val);
  } else {
    el = document.createElement(vnode.type);
    for(var i = 0; i < vnode.children.length; i++) {
      el.appendChild(createNodeFromVNode(vnode.children[i], instance));
    }
    addEventListeners(el, vnode, instance);
  }
  diffProps(el, {}, vnode.props, vnode);
  return el;
}

/**
 * Diffs Props of Node and a VNode, and apply Changes
 * @param {Object} node
 * @param {Object} nodeProps
 * @param {Object} vnodeProps
 * @param {Object} vnode
 */
var diffProps = function(node, nodeProps, vnodeProps, vnode) {
  // Get object of all properties being compared
  var allProps = merge(nodeProps, vnodeProps);

  for(var propName in allProps) {
    // If not in VNode or is a Directive, remove it
    if(!vnodeProps[propName] || directives[propName] || specialDirectives[propName]) {
      // If it is a directive, run the directive
      if(directives[propName]) {
        directives[propName](node, allProps[propName], vnode);
      }
      node.removeAttribute(propName);
    } else if(!nodeProps[propName] || nodeProps[propName] !== vnodeProps[propName]) {
      // It has changed or is not in the node in the first place
      node.setAttribute(propName, vnodeProps[propName]);
    }
  }
}

/**
 * Diffs Node and a VNode, and applies Changes
 * @param {Object} node
 * @param {Object} vnode
 * @param {Object} parent
 * @param {Object} instance
 * @return {Object} adjusted node
 */
var diff = function(node, vnode, parent, instance) {
  var nodeName;

  if(node) {
    nodeName = node.nodeName.toLowerCase();
  }

  if((vnode && vnode.meta.shouldRender) || (!vnode)) {
    if(!node) {
      // No node, add it
      parent.appendChild(createNodeFromVNode(vnode, instance));
    } else if(!vnode) {
      // No VNode, remove the node
      parent.removeChild(node);
    } else if(nodeName !== vnode.type) {
      // Different types of Nodes, replace the node
      parent.replaceChild(createNodeFromVNode(vnode, instance), node);
    } else if(nodeName === "#text" && vnode.type === "#text") {
      // Both are text, set the text
      node.textContent = vnode.val;
    } else if(vnode.children.length === 0 && !node.firstChild.nextSibling && node.firstChild.nodeName === "#text" && vnode.children[0].type === "#text") {
      // Optimization:
      //  If the node and vnode contain a single text node, update it here
      node.firstChild.textContent = vnode.children[0].val;
    } else if(vnode.type) {
      // Diff properties
      var nodeProps = node.__moon__attrs__ || extractAttrs(node);
      diffProps(node, nodeProps, vnode.props, vnode);

      if(instance.$initialRender) {
        addEventListeners(node, vnode, instance);
      }

      // Diff children
      var currentChildNode = node.firstChild;
      for(var i = 0; i < vnode.children.length || currentChildNode; i++) {
        diff(currentChildNode, vnode.children[i], node, instance);
        currentChildNode = (currentChildNode ? currentChildNode.nextSibling : null);
      }
    }
  } else if(vnode && !vnode.meta.shouldRender && vnode.props[Moon.config.prefix + "pre"]) {
    // Not Rendering as a result of the "Pre" Directive, remove it
    node.removeAttribute(Moon.config.prefix + "pre");
  }
}

/**
 * Extends an Object with another Object's properties
 * @param {Object} parent
 * @param {Object} child
 * @return {Object} Extended Parent
 */
var extend = function(parent, child) {
  for (var key in child) {
    parent[key] = child[key];
  }
  return parent;
}

/**
 * Merges Two Objects Together
 * @param {Object} parent
 * @param {Object} child
 * @return {Object} Merged Object
 */
var merge = function(parent, child) {
  var merged = {};
  for(var key in parent) {
    merged[key] = parent[key];
  }
  for (var key in child) {
    merged[key] = child[key];
  }
  return merged;
}

/**
 * Calls a Hook
 * @param {Object} instance
 * @param {String} name
 */
var callHook = function(instance, name) {
  var hook = instance.$hooks[name];
  if(hook) {
    hook();
  }
}

/**
 * Does No Operation
 */
var noop = function() {

}
<|endoftext|>


<commit_before>$(function($){
	$('#server').change(function(e) {
		_change_server();
  	});

	$('#redis_db').change(function(e) {
		_change_server();
	 });

	var _change_server = function() {
		var server = $('#server').val();
		var db = $('#redis_db').val();
		var request = getRequest();
		request['server_id'] = server;
		request['db'] = db;

		var url = 'http://' + location.host + location.pathname + '?';
		for(var i in request) {

			url += i + ( (typeof request[i] == 'undefined' || request[i] == 'undefined') ? '' : '=' + request[i] );
			url += '&';
		}

		url = url.substr(0, url.length - 1);
		location.href = url;
	}

	if (history.replaceState) {
		var params = getRequest();
		params['m'] = params['c'];
		params['c'] = 'index';
		var href = location.protocol + '\/\/' + location.host + location.pathname;
		var separator = '?';
		for(var key in params) {
			href += separator + key + '=' + params[key];
			separator = '&';
		}

	    window.parent.history.replaceState({}, '', href);
	}
})

var getRequest = function() {
	var url = location.search; //获取url中"?"符后的字串
	var theRequest = new Object();
	if (url.indexOf("?") != -1) {
	    var str = url.substr(1);
	    strs = str.split("&");
	    for(var i = 0; i < strs.length; i ++) {
	        theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
	    }
	}
	return theRequest;
}

var delTree = function(obj){
	if (confirm('确定要删除整个树及其所有的键吗？')) {
    		$.ajax({
				type: "POST",
				url: obj.href,
				data: {},
				timeout: 120000,
				success: function(url) {
					top.location.href = url;
				}
			});
	}
    return false;
}

var addDiyDom = function(treeId, treeNode) {
	if ( (typeof treeNode['isDir'] != 'undefined')
		&& ( treeNode['isDir'] )
	){
		var aObj = $("#" + treeNode.tId + '_a');
		var urlExport = _global.baseUrl + '?c=export&m=index&key=' + treeNode.id + ':*&' + _global.urlParams;
		var urlDelete = _global.baseUrl + '?c=delete&m=index&tree=' + treeNode.id + ':&' + _global.urlParams;
		var editStr = "";
		editStr += "";
		aObj.append(editStr);
	}
}

var redisAdmin = function(options){
	/*
		options = {
			//目标dom节点
			targetDom : string
			//基础URL
			baseUrl : string,
			//附加参数
			extraParams : string,
			//分割符
			seperator: ':'
		}
	 */
	this.treeNodeSetting = {
		pIdKey: 'pId',
		idKey: 'id',
		childKey: 'children',
		countKey: 'count'
	}

	this.formatedData = [];
	this.formatedDataForBuildTree = []
	this.options = options;

	this.keyList = [];

	this.existsNodeKey = {}
}

redisAdmin.prototype.transformTozTreeFormat = function(pageSize) {
	this.formatedData = [];
	var i,l,
	key = this.treeNodeSetting.idKey,
	parentKey = this.treeNodeSetting.pIdKey,
	childKey = this.treeNodeSetting.children;
	if (!key || key=="" || !sNodes) return [];

	var tmpMap = [];
	for (i=0, l=sNodes.length; i<l; i++) {
		tmpMap[sNodes[i][key]] = sNodes[i];
	}
	for (i=0, l=sNodes.length; i<l; i++) {
		if (tmpMap[sNodes[i][parentKey]] && sNodes[i][key] != sNodes[i][parentKey]) {
			if (!tmpMap[sNodes[i][parentKey]][childKey])
				tmpMap[sNodes[i][parentKey]][childKey] = [];
			tmpMap[sNodes[i][parentKey]][childKey].push(sNodes[i]);
		} else {
			this.formatedData.push(sNodes[i]);
		}
	}
	return this.formatedData;
}

redisAdmin.prototype.perpareTreeData = function() {

	function copyNode2(srcObj, dstObj, pageSize) {
		dstObj = {}
		dstObj.id = srcObj.id;
		dstObj.name = srcObj.name;
		dstObj.pId = srcObj.pId;
		dstObj.isDir = srcObj.isDir;
		dstObj.target = srcObj.target;
		dstObj.url = srcObj.url;
		if ( typeof srcObj[countKey] != 'undefined' ) {
			dstObj[countKey] = srcObj[countKey];
		}

	}

	function copyNode(r, srcObj, dstObj, pageSize) {
		var i;
		for (i = 0, l = srcObj.length; i < l; i++ ) {
			var dstObj = {}
			dstObj.id = srcObj.id;
			dstObj.name = srcObj.name;
			dstObj.pId = srcObj.pId;
			dstObj.isDir = srcObj.isDir;
			dstObj.target = srcObj.target;
			dstObj.url = srcObj.url;
			if ( typeof srcObj[countKey] != 'undefined' ) {
				dstObj[countKey] = srcObj[countKey];
				var cnt = 0;
				dstObj[childKey] = [];
			}
			r[i] = dstObj;

			if ( typeof srcObj[countKey] != 'undefined' ) {
				copyNode(r[i], this.formatedData[i], dstObj, 10)
			}
		}

		var d;
		dstObj = {}
		dstObj.id = srcObj.id;
		dstObj.name = srcObj.name;
		dstObj.pId = srcObj.pId;
		dstObj.isDir = srcObj.isDir;
		dstObj.target = srcObj.target;
		dstObj.url = srcObj.url;
		if ( typeof srcObj[countKey] != 'undefined' ) {
			dstObj[countKey] = srcObj[countKey];
		}
		var cnt = 0;
		var children = []
		if (typeof srcObj[childKey] != 'undefined') {
			dstObj[childKey] = [];
			for (var k in srcObj[childKey]) {
				copyNode(r, srcObj[childKey][k], dstObj, pageSize)
				cnt += 1;
				if ( cnt >= pageSize ) {
					break
				}
			}
		}

	}
	var r = [];
	var node;
	var tmpLen;
	var parentKey = this.treeNodeSetting.pIdKey;
	var childKey = this.treeNodeSetting.childKey;
	var countKey = this.treeNodeSetting.countKey;
	for (i = 0, l = this.formatedData.length; i < l; i++ ) {
		var dstObj = {}
		copyNode(r, this.formatedData[i], dstObj, 10)
	}
}

redisAdmin.prototype.buildTree = function() {

	return ;
	var $obj = $("#" + this.options.targetDom);
	$obj.html('');

	var setting = {
		data: {
			simpleData: {
				enable: true
			}
		},
		view: {
			addDiyDom: addDiyDom
		}
	};

	_global.ztreeObj = $.fn.zTree.init($obj, setting, this.keyList);
	_global.inited = true;
}

redisAdmin.prototype.loadData = function(prefix) {
	var that = this;

	var _buildParentNood = function(arr) {
		var id = arr.join(that.options.seperator);
		if ( typeof that.existsNodeKey[id] != 'undefined' ) {
			return
		}
		that.existsNodeKey[id] = 1;
		var name = arr.pop();
		var obj = {
			id: id,
			pId: arr.length > 0 ? arr.join(that.options.seperator) : -1,
			isDir: true,
			name: name
		}
		that.keyList.push(obj)
		if ( arr.length > 0 ) {
			_buildParentNood(arr);
		}
	}

	var _doLoadData = function(prefix, iterator) {
		$.ajax({
			type: "GET",
			url: that.options.baseUrl + "?c=key&key="+ prefix + '&' + that.options.extraParams,
			data: {"iterator": iterator},
			dataType: 'json',
			timeout: 10000,
			success: function(json) {
				if ( typeof json == 'object' ) {
					if (json.result == 0) {
						var data = json.data;
						var tempArr, name;
						for (var i in data['keys'] ) {
							tempArr = data['keys'][i].split(that.options.seperator)
							name = tempArr.pop();
							var obj = {
								id: data['keys'][i],
								pId: tempArr.length > 0 ? tempArr.join(that.options.seperator) : -1,
								name: name,
								isDir: false,
								target: "iframe",
								url: that.options.baseUrl + "?c=view&m=index&key="+ data['keys'][i] + '&' + that.options.extraParams
							}

							that.keyList.push(obj);
							if ( tempArr.length > 0 ) {
								_buildParentNood(tempArr);
							}
						}

						$("#current_loaded").html(that.keyList.length)

						if (( typeof data.iterator != 'undefined')
							&& ( data.iterator > 0 )
						){
							_doLoadData(prefix, data.iterator);
						} else {
							that.buildTree()
							//去锁
							_global.isLock = false;
						}
					} else {
						_global.isLock = false;
						alert('连接服务器时发生错误：' + json.msg);
					}
				} else {
					_global.isLock = false;
					alert('连接服务器出错。');
				}

			},
			error: function(){
				alert('连接服务器超时');
				_global.isLock = false;
			}
		});
	}

	if ( _global.isLock ) {
		return ;
	}
	_global.isLock = true;
	this.keyList = [{id: -1, pId: 0, name: "Keys"}];

	var iterator = -1;
	_doLoadData(prefix, iterator);
}
<commit_msg>删除多余文件<commit_after><|endoftext|>


<commit_before>import * as symbols from "./symbols.js";

/**
 * Miscellaneous utility functions for web components
 *
 * @module utilities
 */

const mousedownListenerKey = Symbol('mousedownListener');

 /**
 * Returns true if the first node contains the second, even if the second node
 * is in a shadow tree.
 *
 * The standard Node.contains() function does not account for Shadow DOM, and
 * returns false if the supplied target node is sitting inside a shadow tree
 * within the container.
 *
 * @param {Node} container - The container to search within.
 * @param {Node} target - The node that may be inside the container.
 * @returns {boolean} - True if the container contains the target node.
 */
export function deepContains(container, target) {
  /** @type {any} */
  let current = target;
  while (current) {
    const parent = current.assignedSlot || current.parentNode || current.host;
    if (parent === container) {
      return true;
    }
    current = parent;
  }
  return false;
}

/**
 * Determine which shadow or child element the indicated element would
 * like to treat as the default element to focus on.
 *
 * This proceeds by starting with the indicated element, seeing whether
 * it defines another element as the one which should receive the focus,
 * and repeating that process.
 *
 * [OverlayMixin](OverlayMixin) uses this utility to determine where the focus
 * should be put when an overlay is opened.
 *
 * @param {HTMLElement} element
 * @returns {HTMLElement}
 */
export function defaultFocus(element) {
  let result;
  // Keep asking if the indicated element specifies a default focus and,
  // if so, proceed there.
  for (
    result = element;
    result[symbols.defaultFocus];
    result = result[symbols.defaultFocus]
  ) {
    /* eslint-disable no-empty */
  }
  return result;
}

/**
 * Polyfill for shadowRoot.elementsFromPoint, which (as of 6 June 2018) is
 * not available in the webcomponents polyfill.
 * See https://github.com/webcomponents/shadydom/issues/141.
 *
 * @param {Element} element - element whose shadow root may contain elements
 * at the specified point
 * @param {number} x - x-coordinate of the indicated point
 * @param {number} y - y-coordinate of the indicated point
 * @returns {Element[]}
 */
export function elementsFromPoint(element, x, y) {
  if (element.shadowRoot && element.shadowRoot.elementsFromPoint) {
    return element.shadowRoot.elementsFromPoint(x, y);
  //@ts-ignore
  } else if (document.elementsFromPoint) {
    //@ts-ignore
    return document.elementsFromPoint(x, y);
  } else {
    // Microsoft Edge

    /** @type {any} */
    const cast = document;
    const elements = cast.msElementsFromPoint(x, y);
    return elements ?
      [...elements] :
      [];
  }
}

/**
 * TODO: Docs
 *
 * @param {HTMLElement} origin
 * @param {HTMLElement|null} target
 */
export function forwardFocus(origin, target) {
  if (origin[mousedownListenerKey]) {
    // Origin was previously forwarding focus, probably to a different target.
    // Remove the previous event listener.
    origin.removeEventListener('mousedown', origin[mousedownListenerKey]);
  }
  if (target) {
    // Using forward focus implies no tab stop.
    origin.setAttribute('tabindex', '-1');
    origin[mousedownListenerKey] = (event) => {
      // Only process events for the main (usually left) button.
      if (event.button !== 0) {
        return;
      }
      target.focus();
      event.preventDefault();
    };
    origin.addEventListener('mousedown', origin[mousedownListenerKey]);
  }
}

/**
 * Search a list element for the item that contains the specified target.
 *
 * When dealing with UI events (e.g., mouse clicks) that may occur in
 * subelements inside a list item, you can use this routine to obtain the
 * containing list item.
 *
 * @param {NodeList|Node[]} items - A list element containing a set of items
 * @param {Node} target - A target element that may or may not be an item in the
 * list.
 * @returns {number} - The index of the list child that is or contains the
 * indicated target node. Returns -1 if not found.
 */
export function indexOfItemContainingTarget(items, target) {
  return Array.prototype.findIndex.call(items, item =>
    item === target || deepContains(item, target)
  );
}

/**
 * Return true if the event came from within the node (or from the node itself);
 * false otherwise.
 *
 * @param {Node} node - The node to consider in relation to the event
 * @param {Event} event - The event which may have been raised within/by the
 * node
 * @returns {boolean} - True if the event was raised within or by the node
 */
export function ownEvent(node, event) {
  /** @type {any} */
  const cast = event;
  const eventSource = cast.composedPath()[0];
  return node === eventSource || deepContains(node, eventSource);
}
<commit_msg>Remove deprecated utilities.forwardFocus() in favor of ComposedFocusMixin.<commit_after>import * as symbols from "./symbols.js";

/**
 * Miscellaneous utility functions for web components
 *
 * @module utilities
 */

const mousedownListenerKey = Symbol('mousedownListener');

 /**
 * Returns true if the first node contains the second, even if the second node
 * is in a shadow tree.
 *
 * The standard Node.contains() function does not account for Shadow DOM, and
 * returns false if the supplied target node is sitting inside a shadow tree
 * within the container.
 *
 * @param {Node} container - The container to search within.
 * @param {Node} target - The node that may be inside the container.
 * @returns {boolean} - True if the container contains the target node.
 */
export function deepContains(container, target) {
  /** @type {any} */
  let current = target;
  while (current) {
    const parent = current.assignedSlot || current.parentNode || current.host;
    if (parent === container) {
      return true;
    }
    current = parent;
  }
  return false;
}

/**
 * Determine which shadow or child element the indicated element would
 * like to treat as the default element to focus on.
 *
 * This proceeds by starting with the indicated element, seeing whether
 * it defines another element as the one which should receive the focus,
 * and repeating that process.
 *
 * [OverlayMixin](OverlayMixin) uses this utility to determine where the focus
 * should be put when an overlay is opened.
 *
 * @param {HTMLElement} element
 * @returns {HTMLElement}
 */
export function defaultFocus(element) {
  let result;
  // Keep asking if the indicated element specifies a default focus and,
  // if so, proceed there.
  for (
    result = element;
    result[symbols.defaultFocus];
    result = result[symbols.defaultFocus]
  ) {
    /* eslint-disable no-empty */
  }
  return result;
}

/**
 * Polyfill for shadowRoot.elementsFromPoint, which (as of 6 June 2018) is
 * not available in the webcomponents polyfill.
 * See https://github.com/webcomponents/shadydom/issues/141.
 *
 * @param {Element} element - element whose shadow root may contain elements
 * at the specified point
 * @param {number} x - x-coordinate of the indicated point
 * @param {number} y - y-coordinate of the indicated point
 * @returns {Element[]}
 */
export function elementsFromPoint(element, x, y) {
  if (element.shadowRoot && element.shadowRoot.elementsFromPoint) {
    return element.shadowRoot.elementsFromPoint(x, y);
  //@ts-ignore
  } else if (document.elementsFromPoint) {
    //@ts-ignore
    return document.elementsFromPoint(x, y);
  } else {
    // Microsoft Edge

    /** @type {any} */
    const cast = document;
    const elements = cast.msElementsFromPoint(x, y);
    return elements ?
      [...elements] :
      [];
  }
}

/**
 * Search a list element for the item that contains the specified target.
 *
 * When dealing with UI events (e.g., mouse clicks) that may occur in
 * subelements inside a list item, you can use this routine to obtain the
 * containing list item.
 *
 * @param {NodeList|Node[]} items - A list element containing a set of items
 * @param {Node} target - A target element that may or may not be an item in the
 * list.
 * @returns {number} - The index of the list child that is or contains the
 * indicated target node. Returns -1 if not found.
 */
export function indexOfItemContainingTarget(items, target) {
  return Array.prototype.findIndex.call(items, item =>
    item === target || deepContains(item, target)
  );
}

/**
 * Return true if the event came from within the node (or from the node itself);
 * false otherwise.
 *
 * @param {Node} node - The node to consider in relation to the event
 * @param {Event} event - The event which may have been raised within/by the
 * node
 * @returns {boolean} - True if the event was raised within or by the node
 */
export function ownEvent(node, event) {
  /** @type {any} */
  const cast = event;
  const eventSource = cast.composedPath()[0];
  return node === eventSource || deepContains(node, eventSource);
}
<|endoftext|>


<commit_before>/* global TrelloPowerUp */

var WHITE_ICON = './images/icon-white.svg';
var GRAY_ICON = './images/icon-gray.svg';

var parkMap = {
  acad: 'Acadia National Park',
  arch: 'Arches National Park',
  badl: 'Badlands National Park',
  brca: 'Bryce Canyon National Park',
  crla: 'Crater Lake National Park',
  dena: 'Denali National Park',
  glac: 'Glacier National Park',
  grca: 'Grand Canyon National Park',
  grte: 'Grand Teton National Park',
  olym: 'Olympic National Park',
  yell: 'Yellowstone National Park',
  yose: 'Yosemite National Park',
  zion: 'Zion National Park'
};

var getBadges = function(t){
  return t.card('name')
  .get('name')
  .then(function(cardName){
    var badgeColor;
    var icon = GRAY_ICON;
    var lowercaseName = cardName.toLowerCase();
    if(lowercaseName.indexOf('green') > -1){
      badgeColor = 'green';
      icon = WHITE_ICON;
    } else if(lowercaseName.indexOf('yellow') > -1){
      badgeColor = 'yellow';
      icon = WHITE_ICON;
    } else if(lowercaseName.indexOf('red') > -1){
      badgeColor = 'red';
      icon = WHITE_ICON;
    }

    if(lowercaseName.indexOf('dynamic') > -1){
      // dynamic badges can have their function rerun after a set number
      // of seconds defined by refresh. Minimum of 10 seconds.
      return [{
        dynamic: function(){
          return {
            title: 'Detail Badge', // for detail badges only
            text: 'Dynamic ' + (Math.random() * 100).toFixed(0).toString(),
            icon: icon, // for card front badges only
            color: badgeColor,
            refresh: 10
          }
        }
      }]
    }

    if(lowercaseName.indexOf('static') > -1){
      // return an array of badge objects
      return [{
        title: 'Detail Badge', // for detail badges only
        text: 'Static',
        icon: icon, // for card front badges only
        color: badgeColor
      }];
    } else {
      return [];
    }
  })
};

var formatNPSUrl = function(t, url){
  if(!/^https?:\/\/www\.nps\.gov\/[a-z]{4}\//.test(url)){
    return null;
  }
  var parkShort = /^https?:\/\/www\.nps\.gov\/([a-z]{4})\//.exec(url)[1];
  if(parkShort && parkMap[parkShort]){
    return parkMap[parkShort];
  } else{
    return null;
  }
};

var boardButtonCallback = function(t){
  return t.popup({
    title: 'Popup List Example',
    items: [
      {
        text: 'Open Overlay',
        callback: function(t){
          return t.overlay({
            url: './overlay.html',
            args: { rand: (Math.random() * 100).toFixed(0) }
          })
          .then(function(){
            return t.closePopup();
          });
        }
      },
      {
        text: 'Open Board Bar',
        callback: function(t){
          return t.boardBar({
            url: './board-bar.html',
            height: 200
          })
          .then(function(){
            return t.closePopup();
          });
        }
      }
    ]
  });
};

var cardButtonCallback = function(t){
  var items = Object.keys(parkMap).map(function(parkCode){
    var urlForCode = 'http://www.nps.gov/' + parkCode + '/';
    return {
      text: parkMap[parkCode],
      url: urlForCode,
      callback: function(t){
        return t.attach({ url: urlForCode, name: parkMap[parkCode] })
        .then(function(){
          return t.closePopup();
        })
      }
    };
  });

  return t.popup({
    title: 'Popup Search Example',
    items: items,
    search: {
      count: 5,
      placeholder: 'Search National Parks',
      empty: 'No parks found'
    }
  });
};

TrelloPowerUp.initialize({
  'attachment-sections': function(t, options){
    // options.entries is a list of the attachments for this card
    // you can look through them and 'claim' any that you want to
    // include in your section.

    // we will just claim urls for Yellowstone
    var claimed = options.entries.filter(function(attachment){
      return attachment.url.indexOf('http://www.nps.gov/yell/') == 0;
    });

    // you can have more than one attachment section on a card
    // you can group items together into one section, have a section
    // per attachment, or anything in between.
    if(claimed && claimed.length > 0){
      // if the title for your section requires a network call or other
      // potentially length operation you can provide a function for the title
      // that returns the section title. If you do so, provide a unique id for
      // your section
      return [{
        id: 'Yellowstone', // optional if you aren't using a function for the title
        claimed: claimed,
        icon: GRAY_ICON,
        title: 'Example Attachment Section: Yellowstone',
        content: {
          type: 'iframe',
          url: t.signUrl('./section.html', { arg: 'you can pass your section args here' }),
          height: 230
        }
      }];
    } else {
      return [];
    }
  },
  'attachment-thumbnail': function(t, options){
    var parkName = formatNPSUrl(t, options.url);
    if(parkName){
      // return an object with some or all of these properties:
      // url, title, image, openText, modified (Date), created (Date), createdBy, modifiedBy
      return {
        url: options.url,
        title: parkName,
        image: {
          url: './images/nps.svg',
          logo: true // false if you are using a thumbnail of the content
        },
        openText: 'Open in NPS'
      };
    } else {
      throw t.NotHandled();
    }
  },
  'board-buttons': function(t, options){
    return [{
      icon: WHITE_ICON,
      text: 'Template',
      callback: boardButtonCallback
    }];
  },
  'card-badges': function(t, options){
    return getBadges(t);
  },
  'card-buttons': function(t, options) {
    return [{
      icon: GRAY_ICON,
      text: 'Template',
      callback: cardButtonCallback
    }];
  },
  'card-detail-badges': function(t, options) {
    return getBadges(t);
  },
  'card-from-url': function(t, options) {
    var parkName = formatNPSUrl(t, options.url);
    if(parkName){
      return {
        name: parkName,
        desc: 'An awesome park: ' + options.url
      };
    } else {
      throw t.NotHandled();
    }
  },
  'format-url': function(t, options) {
    var parkName = formatNPSUrl(t, options.url);
    if(parkName){
      return {
        icon: GRAY_ICON,
        text: parkName
      };
    } else {
      throw t.NotHandled();
    }
  },
  'show-settings': function(t, options){
    return t.popup({
      title: 'Settings',
      url: './settings.html',
      height: 184
    });
  }
});
<commit_msg>trello power app<commit_after>/* global TrelloPowerUp */
var GRAY_ICON = './images/icon-gray.svg';

var cardButtonCallback = function(t){
  var items = Object.keys(parkMap).map(function(parkCode){
    var urlForCode = 'http://www.nps.gov/' + parkCode + '/';
    return {
      text: parkMap[parkCode],
      url: urlForCode,
      callback: function(t){
        return t.attach({ url: urlForCode, name: parkMap[parkCode] })
        .then(function(){
          return t.closePopup();
        })
      }
    };
  });

  return t.popup({
    title: 'Popup Search Example',
    items: items,
    search: {
      count: 5,
      placeholder: 'Search National Parks',
      empty: 'No parks found'
    }
  });
};

TrelloPowerUp.initialize({
  'card-buttons': function(t, options) {
    return [{
      icon: GRAY_ICON,
      text: 'Start timer',
      callback: cardButtonCallback
    }];
  },
  'show-settings': function(t, options){
    return t.popup({
      title: 'Settings',
      url: './settings.html',
      height: 184
    });
  }
});
<|endoftext|>


<commit_before>var client = require('cheerio-httpcli');
var webPageParser = {};

webPageParser.load = function(args, next) {
  client.fetch(args.url, function (err, $, res) {
    var fetchText = $(args.target).text();
    next(false, [fetchText]);
  });
}
module.exports = webPageParser;
<commit_msg>parseWebPageプラグインに対して複数のURLを渡せる様にした<commit_after>var client = require('cheerio-httpcli');
var webPageParser = {};

webPageParser.load = function(args, next) {
  var targetPages = Array.isArray(args.url) ? args.url : [args.url];
  var targetDom = args.target;
  var fetchTexts = [];

  var fetchPage = function() {
    var url = targetPages.shift();

    client.fetch(url, function (err, $, res) {
      if (err) {
        fetchTexts.push("");
      } else {
        fetchTexts.push($(targetDom).text());
      }

      if (targetPages.length == 0) {
        next(false, fetchTexts);
      } else {
        fetchPage();
      }
    });
  };

  fetchPage();
}
module.exports = webPageParser;
<|endoftext|>


<commit_before>const fs = require('fs');
const glob = require('glob');
const path = require('path');
const plist = require('plist');
const xcode = require('xcode');

module.exports = {
	getClosestLikelyReactNativeProjectPath () {
		let currentPath = process.cwd();
		let nextPath;

		const pattern = 'ios/*.xcodeproj/project.pbxproj';
		let files = glob.sync(path.join(currentPath, pattern));

		while (files.length === 0) {
			nextPath = path.resolve(currentPath, '..');

			if (nextPath === currentPath) {
				// We're at the root of the filesystem and didn't find anything.
				return null;
			}

			currentPath = nextPath;

			files = glob.sync(path.join(currentPath, pattern));
		}

		return currentPath;
	},
	getFilesMatchingGlob (pattern, callback) {
        // Find all of the files we care about.
		const project = this.getClosestLikelyReactNativeProjectPath();
		if (!project) return callback(new Error('Unable to find project path.'));

		glob(path.join(project, pattern), (err, files) => {
			if (err) return callback(err);

            // Go through each project.
			for (const filePath of files) {
				callback(null, filePath);
			}
		});
	},
	updateProjectsMatchingGlob (pattern, callback) {
		this.getFilesMatchingGlob(pattern, (err, filePath) => {
			if (!filePath) return callback(new Error('Unable to find project path.'));
			if (filePath.endsWith(path.join('Pods.xcodeproj', 'project.pbxproj'))) {
				// The Pods.xcodeproj file isn't currently able to be parsed
				// by node-xcode:
				// https://github.com/alunny/node-xcode/issues/127
				//
				// We don't actually need to manipulate it so we'll go ahead and ignore.
				return;
			}

			const project = xcode.project(filePath);

			try {
				project.parseSync();
			} catch (error) {
				return callback(error);
			}

			// And fix it.
			if (callback(null, project)) {
				fs.writeFileSync(filePath, project.writeSync());
			}
		});
	},
	updatePlistsMatchingGlob (pattern, callback) {
		this.getFilesMatchingGlob(pattern, (err, filePath) => {
			if (!filePath) return callback(new Error('Unable to find plist path.'));

			const file = plist.parse(fs.readFileSync(filePath, 'utf8'));

			// And fix it.
			if (callback(null, file, filePath)) {
				fs.writeFileSync(filePath, plist.build(file));
			}
		});
	},
	getMappings () {
		const project = this.getClosestLikelyReactNativeProjectPath();
		const packageJson = require(path.join(project, 'package.json'));

		if (!packageJson.xcodeSchemes) {
			throw new Error('Please configure schemes on your project. For more information, see https://github.com/Thinkmill/react-native-schemes-manager/blob/master/README.md');
		}

		return packageJson.xcodeSchemes;
	},
	getBundledMappings () {
		const project = this.getClosestLikelyReactNativeProjectPath();
		const packageJson = require(path.join(project, 'package.json'));

		if (!packageJson.bundledDebugSchemes) {
			return [];
		}

		return packageJson.bundledDebugSchemes;
	},
};
<commit_msg>testing Utilities<commit_after>const fs = require('fs');
const glob = require('glob');
const path = require('path');
const plist = require('plist');
const xcode = require('xcode');

module.exports = {
	getClosestLikelyReactNativeProjectPath () {
		let currentPath = process.cwd();
		console.log('currentPath', currentPath)
		let nextPath;

		const pattern = 'ios/*.xcodeproj/project.pbxproj';
		let files = glob.sync(path.join(currentPath, pattern));

		while (files.length === 0) {
			nextPath = path.resolve(currentPath, '..');

			if (nextPath === currentPath) {
				// We're at the root of the filesystem and didn't find anything.
				return null;
			}

			currentPath = nextPath;
			console.log('currentPath', currentPath)

			files = glob.sync(path.join(currentPath, pattern));
			console.log('files', files)
		}

		return currentPath;
	},
	getFilesMatchingGlob (pattern, callback) {
        // Find all of the files we care about.
		const project = this.getClosestLikelyReactNativeProjectPath();
		if (!project) return callback(new Error('Unable to find project path.'));

		glob(path.join(project, pattern), (err, files) => {
			if (err) return callback(err);

            // Go through each project.
			for (const filePath of files) {
				callback(null, filePath);
			}
		});
	},
	updateProjectsMatchingGlob (pattern, callback) {
		this.getFilesMatchingGlob(pattern, (err, filePath) => {
			if (!filePath) return callback(new Error('Unable to find project path.'));
			if (filePath.endsWith(path.join('Pods.xcodeproj', 'project.pbxproj'))) {
				// The Pods.xcodeproj file isn't currently able to be parsed
				// by node-xcode:
				// https://github.com/alunny/node-xcode/issues/127
				//
				// We don't actually need to manipulate it so we'll go ahead and ignore.
				return;
			}

			const project = xcode.project(filePath);

			try {
				project.parseSync();
			} catch (error) {
				return callback(error);
			}

			// And fix it.
			if (callback(null, project)) {
				fs.writeFileSync(filePath, project.writeSync());
			}
		});
	},
	updatePlistsMatchingGlob (pattern, callback) {
		this.getFilesMatchingGlob(pattern, (err, filePath) => {
			if (!filePath) return callback(new Error('Unable to find plist path.'));

			const file = plist.parse(fs.readFileSync(filePath, 'utf8'));

			// And fix it.
			if (callback(null, file, filePath)) {
				fs.writeFileSync(filePath, plist.build(file));
			}
		});
	},
	getMappings () {
		const project = this.getClosestLikelyReactNativeProjectPath();
		const packageJson = require(path.join(project, 'package.json'));

		if (!packageJson.xcodeSchemes) {
			throw new Error('Please configure schemes on your project. For more information, see https://github.com/Thinkmill/react-native-schemes-manager/blob/master/README.md');
		}

		return packageJson.xcodeSchemes;
	},
	getBundledMappings () {
		const project = this.getClosestLikelyReactNativeProjectPath();
		const packageJson = require(path.join(project, 'package.json'));

		if (!packageJson.bundledDebugSchemes) {
			return [];
		}

		return packageJson.bundledDebugSchemes;
	},
};
<|endoftext|>