Repository: xunuoi/gulpman Branch: master Commit: d12eb0fa1c71 Files: 149 Total size: 2.3 MB Directory structure: gitextract_0od9uxhv/ ├── .gitignore ├── LICENSE ├── README.md ├── README_zh-CN.md ├── assets/ │ └── .babelrc ├── index.js ├── karma/ │ └── karma.conf.js ├── lib/ │ ├── assetsPathParser.js │ ├── base64.js │ ├── cdnProxy.js │ ├── gmutil.js │ ├── gulp-usemin/ │ │ ├── .npmignore │ │ ├── .travis.yml │ │ ├── LICENSE │ │ ├── README.md │ │ ├── gulpfile.js │ │ ├── index.js │ │ ├── lib/ │ │ │ ├── blocksBuilder.js │ │ │ ├── htmlBuilder.js │ │ │ └── pipeline.js │ │ ├── package.json │ │ └── test/ │ │ ├── expected/ │ │ │ ├── app.js │ │ │ ├── array-js-attributes.html │ │ │ ├── build-remove-no-trailing-whitespace.html │ │ │ ├── complex-path.html │ │ │ ├── complex.html │ │ │ ├── conditional-complex.html │ │ │ ├── conditional-css.html │ │ │ ├── conditional-inline-css.html │ │ │ ├── conditional-inline-js.html │ │ │ ├── conditional-js.html │ │ │ ├── data/ │ │ │ │ ├── css/ │ │ │ │ │ ├── min-style.css │ │ │ │ │ └── style.css │ │ │ │ └── js/ │ │ │ │ ├── app.js │ │ │ │ ├── app_min_concat.js │ │ │ │ └── min-app.js │ │ │ ├── glob-inline-css.html │ │ │ ├── glob-inline-js.html │ │ │ ├── many-blocks-removal.html │ │ │ ├── min-app.js │ │ │ ├── min-complex-path.html │ │ │ ├── min-complex.html │ │ │ ├── min-css-with-media-query.html │ │ │ ├── min-html-simple-css.html │ │ │ ├── min-html-simple-js.html │ │ │ ├── min-html-simple-removal.html │ │ │ ├── min-paths-with-querystring.html │ │ │ ├── min-simple-css-path.html │ │ │ ├── min-simple-css.html │ │ │ ├── min-simple-js-path.html │ │ │ ├── min-simple-js.html │ │ │ ├── min-style.css │ │ │ ├── multiple-alternative-paths.html │ │ │ ├── multiple-files.html │ │ │ ├── paths-with-querystring.html │ │ │ ├── simple-css-path.html │ │ │ ├── simple-css.html │ │ │ ├── simple-inline-css.html │ │ │ ├── simple-inline-js.html │ │ │ ├── simple-js-path.html │ │ │ ├── simple-js-removal.html │ │ │ ├── simple-js.html │ │ │ ├── single-quotes-css.html │ │ │ ├── single-quotes-inline-css.html │ │ │ ├── single-quotes-inline-js.html │ │ │ ├── single-quotes-js.html │ │ │ ├── style.css │ │ │ └── subfolder/ │ │ │ ├── app.js │ │ │ └── index.html │ │ ├── fixtures/ │ │ │ ├── alternative/ │ │ │ │ └── js/ │ │ │ │ └── util.js │ │ │ ├── array-js-attributes.html │ │ │ ├── async-less.html │ │ │ ├── build-remove-no-trailing-whitespace.html │ │ │ ├── comment-js.html │ │ │ ├── complex-path.html │ │ │ ├── complex.html │ │ │ ├── conditional-complex.html │ │ │ ├── conditional-css.html │ │ │ ├── conditional-inline-css.html │ │ │ ├── conditional-inline-js.html │ │ │ ├── conditional-js.html │ │ │ ├── css/ │ │ │ │ ├── clear.css │ │ │ │ └── main.css │ │ │ ├── css-with-media-query-error.html │ │ │ ├── css-with-media-query.html │ │ │ ├── glob-css.html │ │ │ ├── glob-inline-css.html │ │ │ ├── glob-inline-js.html │ │ │ ├── glob-js.html │ │ │ ├── js/ │ │ │ │ ├── lib.js │ │ │ │ └── main.js │ │ │ ├── js2/ │ │ │ │ ├── lib2.js │ │ │ │ └── main2.js │ │ │ ├── less/ │ │ │ │ ├── clear.less │ │ │ │ └── main.less │ │ │ ├── many-blocks-removal.html │ │ │ ├── many-blocks.html │ │ │ ├── min-html-simple-css.html │ │ │ ├── min-html-simple-js.html │ │ │ ├── min-html-simple-removal.html │ │ │ ├── multiple-alternative-paths-inline.html │ │ │ ├── multiple-alternative-paths.html │ │ │ ├── multiple-files.html │ │ │ ├── paths-with-querystring.html │ │ │ ├── simple-css-alternate-path.html │ │ │ ├── simple-css-path.html │ │ │ ├── simple-css.html │ │ │ ├── simple-inline-css.html │ │ │ ├── simple-inline-js.html │ │ │ ├── simple-js-alternate-path.html │ │ │ ├── simple-js-path.html │ │ │ ├── simple-js-removal.html │ │ │ ├── simple-js.html │ │ │ ├── single-quotes-css.html │ │ │ ├── single-quotes-inline-css.html │ │ │ ├── single-quotes-inline-js.html │ │ │ ├── single-quotes-js.html │ │ │ └── subfolder/ │ │ │ ├── index.html │ │ │ └── script.js │ │ └── main.js │ ├── htmlPathParser.js │ ├── iconFonter.js │ ├── inline.js │ ├── revReplace.js │ ├── spriter/ │ │ ├── README.md │ │ ├── index.js │ │ ├── lib/ │ │ │ ├── get-background-image-declarations.js │ │ │ ├── get-meta-info-for-declaration.js │ │ │ ├── map-over-styles-and-transform-background-image-declarations.js │ │ │ ├── spriter-util.js │ │ │ ├── transform-file-with-sprite-sheet-data.js │ │ │ └── transform-map.js │ │ └── package.json │ └── store.js ├── meta/ │ └── home/ │ ├── index.html │ ├── main.es6 │ └── main.scss ├── package.json ├── presetlib/ │ ├── jquery.js │ ├── react-0.14.6/ │ │ └── build/ │ │ ├── react-dom-server.js │ │ ├── react-dom.js │ │ ├── react-with-addons.js │ │ └── react.js │ └── react.js ├── scripts/ │ ├── gulp/ │ │ └── gulpfile.js │ ├── install.sh │ ├── package.json │ └── preinstall.sh └── test.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ node_modules .npm .bin ================================================ FILE: LICENSE ================================================ The MIT License (MIT) Copyright Lucas, Inc. and other contributors. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ [![Coverage Status](https://raw.githubusercontent.com/xunuoi/gulpman/master/assets/logo.png)](http://karat.cc/article/56a351c3e48d2d05682aa0ac/) ----- [![NPM version](https://img.shields.io/npm/v/gulpman.svg?style=flat-square)](http://badge.fury.io/js/gulpman) Build status # gulpman [浏览简体中文文档](https://github.com/xunuoi/gulpman/blob/master/README_zh-CN.md) - Create Modular Front-End Build System, organize the source by module, using relative path, `html/js/css/img/fonts/tpl` are in one same folder, like Baidu `FIS`. Good concept for FE source management / development. - Concept Introduction: [前端工程之模块化](http://fex.baidu.com/blog/2014/03/fis-module/) - Component Oriented Solution, based on `gulp`. More simple, flexible, expandable and stable. Everyone know gulp can do secondary development. - Support `base64` image in `html/CSS` - Support `JS/CSS` inlnied in html - Support `require('main.css')`, require css file in js - Intergrated with `spritesmith`, support auto sprite img - Intergrated with `icon-font`, support SVG 2 Iconfont. - Intergrated with `usemin`,support complex combo/package. - Supoort FE Tpl embed function, the `.tpl` file will packaged into js file,support async js loading. - Intergrated with `SCSS|ES6|ReactJS|Vuejs|Babel|Browserify|cssnano|uglify|imagmein` and other plugins,One-Stop Solution Service, very Simple and Strong - High scalability, compatiable with almost `gulp` plugins, you can use them in `gulpman`. For example, you can put `browser-sync` in your gulpman build system - Intergrated with `karma` framework,support `babel/es6` unit test and coverage result. ## Introduction - Support Mac、Linux - No full test under Windows. You can install `gulp`、`gulp-sass` manually - Required Node >= 4.0.0 ## Install - `npm install gulpman --save-dev` - Run `gulp gm:install` to finish the setup - *If in China, please use `cnpm` to install it: `cnpm install gulpman --save-dev` #### Note * If `gulp-sass` install failed, please run `cnpm install gulp-sass gulp-imagemin` by manual to fix that. * If error happened in npm install,such as `/usr/local/lib/node_modules` permission error, fix this by `sudo chown -R "$(whoami)"`+`Path` * `sudo npm install` is not recommended * The imagemin-pngquant module need`libpng-devel`,if in Linux, please run `yum install libpng-devel` at first * If install failed, check the `npm-debug.log` to see if there are some `ENOMEM`errors ## Config ### 0. Support Auto Mode, no Config * You can skip `Config`, and directly jump to `Usage` ### 1. Config gulpfile.js: - require the `gulpman` in your gulpfile.js,then it will load `gm:publish`, `gm:develop` into gulp tasks. - `gulp gm:publish` or `gulp gm:develop` in terminal then it will work ```Javascript /** * Gulpfile.js */ var gulp = require('gulp'), gman = require('gulpman') // your other tasks ... // xxx ... /** * config gulpman ====================== * Use config API * assets path, CDN, URL prefix */ gman.config({ // whether use absolute path, default `true` 'is_absolute': true, // cdn prefix support[string|array|function]arguments 'cdn_prefix': '', // url prefix, defautl `/static`. This involves the server config ,such as the static path of nginx 'url_prefix': '/static', /** use spritesmith for css-img sprite * Based on Spritesmith: https://github.com/Ensighten/spritesmith * Automatecially generate Sprite Image & CSS **/ //'spritesmith': { }, /** usemin config **/ // 'usemin': {} // The COMPONENTS directory 'components': 'components', // For development assets and templates folder, related to Server Config 'runtime_views': 'views', 'dist_views': 'views_dist', // For production assets and templates folder, related to Server Config 'runtime_assets': 'assets', 'dist_assets': 'assets_dist', // The js library dir, set as a global module. Also you can set as `bower_components` 'lib': 'lib', // You can add one customer global directory, so you can require module name directly, like: `require ('xxx')`. The xxx is in this directory 'global': 'common' }) ``` ### 2. How to config CDN better * `cdn_prefix` support String, Array, Function * if argument is array, the CDN will be an random value * if argument is function,it would input one argument, `mediaFile` ```Javascript 'cdn_prefix': function (fileName) { console.log(fileName) var c_list = [ 'http://s0.com', 'http://s1.com', 'http://s2.com', 'http://s3.com', 'http://s4.com' ] // You can customized your strategy if(hostFile.match(/\.html$/gm)){ return c_list[0] }else { return c_list[1] } }, ``` ### 3. About `is_absolute` * `is_absolute` is the dist path of source in html. default true. the dist path is like `/static/home/main.js` * [*]Need consistent config with Server, like nginx, apache * If no local server, you can set is_absolute as false, use relative path. Like `../../assets/static/home/main.js` ### 4. gulpman directory * Use gulpman to arrange your directory as component,The root component dir can be`./components`(default). If you have one component named foo, then `./components/foo`,all related assets such as `html|js|css|fonts|image` should be put in `foo` folder. * This solution for assets can be high efficiency and easy to maintain. * `gm:develop` to start `develop` mode, the `views` dir and `assets` dir can be generated automatically * `gm:publish` to publish assets in production env. The `views_dist` and `assets_dist` can generated. ### 5. What is global directory - For `Browserify` packing, the js module in `global dir` can be directly `require` or `import` in es6/js code - In `gulpman.config`, the `lib`和`global` are global directory. Take an example: * In `components/lib` directory, you have one module `foo.js`,then it is `components/lib/foo.js`. So when you use foo in your es6 file, you can use it like: `import foo from 'foo'`, no need write as `import foo from '../lib/foo'` - similarly, `global` option can set your dir as global module dir. You can set `bower` dir as your `lib` dir. - Please make no conficts in your global dir ### 6. Support for complex and multi level directory in config * Such as: ```Javascript gulpman.config({ 'is_absolute': false, 'components': 'components/cc', 'runtime_views': 'runtime_views/rv', 'dist_views': 'dist_views/dv/dv', 'dist_assets': 'dist_assets/da', 'runtime_assets': 'runtime_assets/ra/ra', }) ``` ## Usage ### 1. CLI run Task: ```Shell # Create components directory and add one demo # init components dir and a html demo gulp gm:init # develop and watch mode,watchings files changes and update files gulp gm:develop # Build and Watch one special component, other files are not compiled gulp gm:develop -c component_name1,component_name2,component_name3... # publish assets in production env gulp gm:publish # publish command support `-a`和`-v` parameters to set output assets/views path. gulp gm:publish -v your_views_dist -a your_assets_dist # clean dist files gulp gm:clean # clean dist files, including subfolders gulp gm:clean-deep # Generate one developing assets/views files, but not in watching mode # compile for develop, not watch gulp gm:compile ``` ### 2. Watch one special component in development * When the project become huge, if we watch all components assets, it will be slow and low efficiency, so we can only watch special component to get better performance * Fox example, if we want watch the `home` component: ```Shell # this will only build and watch `components/home` components gulp gm:develop -c home ``` ### 3. Use `React` in gulpman * Install React: `npm install react react-dom` * Use React in ES6: ```Javascript import React from 'react'; import ReactDOM from 'react-dom'; // xxx ``` ### 4. Use `tpl` file in js|es6|jsx * Support `.tpl` file, it will be packaged in dist js files. * Usage: `import dialogTpl from './dialog.tpl'` or `var dialogTpl = require('./dialog.tpl')` ### 5. Usge base64 img in HTML/CSS * Just add `?_gm_inline` in assets src path in html/css * The `base64` code will be inlined in html/css ##### html ```html

Karat 克拉

``` ##### CSS/SCSS ```css .test { background: url(./img/testb64.png?_gm_inline) no-repeat; } ``` ### 6. Use inlined CSS/JS in html by querystring * Like base64, just add `?_gm_inline` in url path ```html ``` * The inlined sources will be auto updated when source files changed. ### 7. Use Sprite img in css * Enable Sprite by `gulpman.config({ enableCSSSprite: true })`, the default is false. * Based on spritesmith, you can transport usemin opts in gulpman.config. * More detail about Spritesmith: [https://github.com/Ensighten/spritesmith](https://github.com/Ensighten/spritesmith) * Usage: In scss file, just add `?_gm_sprite` to img url ```css .demo { background: url(./img/abc.png?_gm_sprite) no-repeat; /* other style you can set ...*/ width: 50px; height: 50px; } ``` ### 8. Use Usemin * You can tranport usemin opts in gulpman.config * More detail about usemin: [https://github.com/zont/gulp-usemin](https://github.com/zont/gulp-usemin) * Uage: just add usemin build comments in html. Support `js`|`css`|`inlinejs`|`inlinecss` syntax * Note: Just write relative path in usemin build comment. Then gulpman can calculate absolute path for assets. * If you don't write output path, the gulpman will combo one new ouput file name automatically. ```html ``` ### 9. Use js tpl template * Put the `.tpl` files in your component, and use `require` or `import` in ES6, then the tpl files will be packaged in js files. * All tpl will be convertd to text string into js files. * Base64 img and CSS/JS Embed are supported in Tpl - import tpl in es6 ```js import dialogTpl from './dialog.tpl' ``` - require ```js var dialogTpl = require('./dialog.tpl') ``` ### 10. import css files into js/html - Just import the css, then the gulpman will attach it on page automatically. ```js import from './style.css'; ``` ```js require('./style.css'); ``` ### 11. Use iconfont convert svg to fontface * Convert SVG to icon-font, use `@font-face` in css * Run `gulp gm:iconfont:install` before first running * Put the svg files in `components/iconfonts/source` directory, then run `gulp gm:iconfont` to begin start convert * The icon-font and css will generated in `iconfonts/gmicon` folder ### 12. Support LAB.js to load async js * Add LAB.js in your project * Use LAB API to load js, use `relative path` * Example: `$LAB.script("../testload/test.js").wait(()=>{console.log('test loaded')})` ### 13. Require CSS in JS * Require css files in your es6/js files * The CSS contents will be packaged into js files, and automatically injected to html when page opend. Using style tag * Should keep the .css extname * Example: `require('./style.css')` or `import style from './style.css'` ### 14. Use karma for Unit Test * Run `gulp gm:karma:install` before first running, it will install dependencies and generate `karma.conf.js`. * In your one component folder, create one folder named `spec`, then put your spec es6 files in the `spec` folder, the file extname must be `.es6` * Run `gulp gm:karma:start` in CLI to start Karma Unit Test, you can view the coverage result in `coverage` foloder * Set one special spec folder、browsers and other karma options, you can set them in `karma.conf.js` ### Tutorial [Tutorial Link](http://karat.cc/article/56a351c3e48d2d05682aa0ac "karat.cc") ### License MIT ================================================ FILE: README_zh-CN.md ================================================ [![Coverage Status](https://raw.githubusercontent.com/xunuoi/gulpman/master/assets/logo.png)](http://karat.cc/article/56a351c3e48d2d05682aa0ac/) ----- [![NPM version](https://img.shields.io/npm/v/gulpman.svg?style=flat-square)](http://badge.fury.io/js/gulpman) Build status # gulpman [English Document](https://github.com/xunuoi/gulpman/blob/master/README.md) - 支持资源模块化组织方式,通过相对路径运算,像百度的FIS一样,可以将`js/css/img/fonts/tpl`按照功能单位组织到同一个目录中,不再分散维护。Gulpman运行时会自动分发各种资源到正确目录。 - 概念介绍: [前端工程之模块化](http://fex.baidu.com/blog/2014/03/fis-module/) - 基于`gulp`的前端组件化、模块化解决方案,更简单、灵活、可控性高,会gulp就会定制自己的方案 - 支持图片`base64`方式嵌入到`html/CSS` - 支持`JS/CSS`内联方式嵌入html文件 - 整合`spritesmith`,简单生成sprite雪碧图 - 整合`icon-font`转换,支持svg转换 - 整合`usemin`,构建合并更加灵活强大 - 支持前端js模板嵌入,`tpl`格式的直接构建打包到最终js文件,支持异步加载js - 集成`SCSS|ES6|ReactJS|Babel|Browserify|cssnano|uglify|imagmein`等常用组件,做到一站式自动化解决方案,同时清晰、可控,定制、修改简单 - 扩展性高,`gulp`现有的插件都可以拼装、加入到`gulpman`中使用,你可以自己根据实际情况组合、修改,比如可以轻松整合`browser-sync`到构建系统中。 - 整合`karma`单元测试框架,适配`babel和es6`的代码单元测试和`coverage` ## 说明 - 支持Mac、Linux环境下安装、使用 - Windows环境未做完整安装测试,由于安装脚本使用到shell,windows不支持shell,执行完`npm install gulpman --save-dev`后,可能需要手动安装`gulp`、`gulp-sass`模块 - 如果手动安装`gulp-sass`,建议使用淘宝的`cnpm`来完成,避免国内网络导致`npm`安装失败 - Node版本需要不低于4.0.0 ## 安装 - `npm install gulpman --save-dev` - 如果在中国,请使用cnpm安装:`cnpm install gulpman --save-dev` - 完成后请运行 `gulp gm:install` 来完成安装 #### 注: * 如果安装过程中提示 `gulp-sass` 安装失败, 运行 `cnpm install gulp-sass gulp-imagemin` 来修复。 * 安装中若npm报出目录权限导致的error,比如涉及到`/usr/local/lib/node_modules`权限的报错,请请检查其权限是否正常并用chown来修复,将拥有者修改为当前登录用户即可。 * 可以使用 `sudo chown -R "$(whoami)"`+`路径`来修复 * 不要使用`sudo npm install`来手工安装因为权限问题而失败的模块。请修改权限后,再用`npm install`来安装即可 * 如果你本地node和npm的安装和权限正常,那gulpman的安装过程应该都是顺利和成功的。 * 图片压缩模块imagemin-pngquant需要依赖`libpng-devel`,如果是Linux环境,建议先运行`yum install libpng-devel`来确保安装 * 安装过程中无故退出,请查看`npm-debug.log`,检查是否是内存不足`ENOMEM`导致。 ## 配置 ### 0. 支持自动默认模式,无需配置即使用 * 可直接跳过`Config 配置`处的说明,直接去看后面的`Usage 使用`内容 ### 1. 配置 gulpfile.js: - 只需要require gulpman模块,就会自动加载`gm:publish`, `gm:develop`(开发监视模式)等task到环境中 - 使用时在命令行中直接输入`gulp gm:publish`即可执行gulpman预置的任务 ```Javascript /** * Gulpfile.js */ var gulp = require('gulp'), gman = require('gulpman') // your other tasks ...你的其他task // xxx ... /** * 配置gulpman ====================== * Use config API * 设置路径、CDN、资源URL前缀等,API简单 */ gman.config({ // 是否使用绝对路径,默认值true, 推荐使用,方便服务器配置。比如`/static/home/main.js`这种风格。 // 如果无服务端情况下,本地调试,可以设置is_absolute为false, 那么会是类似`../../assets/static/home/main.js`这种风格 'is_absolute': true, // cdn prefix 配置CDN, 支持[字符串|数组|函数] 3中传参方式 'cdn_prefix': '', // 配置资源URL前缀,建议类似 /static这种 // usually set as /static, this involves the server config ,such as the static path of nginx 'url_prefix': '/static', /** use spritesmith for css-img sprite * 基于spritesmith实现, 详细参见https://github.com/Ensighten/spritesmith * 传递自动生成雪碧图的spritesmit的options **/ //'spritesmith': { },保持默认即可 /** usemin config 配置usemin,保持默认即可 **/ // 'usemin': {} // 模块COMPONENTS目录,同一个模块的html和资源文件在一起。默认 'components'即可 'components': 'components', // develop和publish下的views目录,跟服务端框架的views目录配置一致,比如express 'runtime_views': 'views', 'dist_views': 'views_dist', // develop和publish下的assets静态目录,跟服务器配置有关,比如nginx的static目录指向,请保持与服务器设定一致。支持多级路径设定,比如assets/public 'runtime_assets': 'assets', 'dist_assets': 'assets_dist', // 第三方JS类库、模块的目录,推荐设置为`lib`或`bower_components`(这样bower可以直接安装到这个目录) // 这个目录默认打包时为全局模块目录,可以直接`import xxx from 'xxx'`,而不用加相对路径 // the js library dir, set as a global module. Also you can set as bower_components 'lib': 'lib', // 可以添加一个自定的全局模块目录,该目录下的js模块,也作为全局模块来require,不需要相对路径。 // the global module dir 'global': 'common' }) ``` ### 2. 如何更好的配置CDN * `cdn_prefix`支持 字符串、数组、函数 * 如果传入数组,那么按照随机来分配 * 如果传入函数,函数会获1个参数,`mediaFile`, 就是当前被css或html中引用到的资源文件名,可以根据文件名做cdn分配 ```Javascript 'cdn_prefix': function (fileName) { console.log(fileName) var c_list = [ 'http://s0.com', 'http://s1.com', 'http://s2.com', 'http://s3.com', 'http://s4.com' ] // 你自可以自实现分配策略 if(hostFile.match(/\.html$/gm)){ return c_list[0] }else { return c_list[1] } }, ``` ### 3. 对于`is_absolute`的说明 * `is_absolute`是指输出的html文件中的资源src/url,否使用绝对路径,默认值true,即启用绝对目录。 * [常用]当使用服务器配置静态目录的情况下,推荐使用绝对目录。比如配合nginx,指定某个目录为静态资源目录。类似`/static/home/main.js`这种风格。 * 如果无服务端情况下,有需要本地调试,推荐设置is_absolute为false, 即启用相对路径。类似`../../assets/static/home/main.js`这种风格。 * 当is_absolute为false(启用相对路径)的情况下,直接打开输出的views目录下的html文件,就可以正常浏览、运行、调试 ### 4. gulpman目录说明 * 使用gulpman按照模块划分后,模块根目录可以是`./components`(默认,可配置),如果你有个模块是foo,那么应该有如下目录:`./components/foo`,然后跟foo模块相关的`html|js|css|fonts|image`等资源文件都放到`foo`下,这个结构下,做开发时非常清晰、高效,便于模块组织、资源定位等。 * 通过`gm:develop`命令进入`develop`开发模式后,会自动生成模板`views`目录,和静态资源`assets`目录。 * 通过`gm:publish`命令来构建发布资源,会自动生成生产环境下的模板目录`views_dist`,和静态资源目录`assets_dist`。 ### 5. 什么是全局模块目录: - 对应`Browserify`的打包功能,`全局目录`是指可以直接`require`或者`import`其下的js模块的目录 - `gulpman.config`的配置中,`lib`和`global`都是JS的全局模块目录。举个例子说明: * 你的`components/lib`目录下有一个模块 `foo.js`,就是: `components/lib/foo.js`,那么你在你的es6文件中,就可以这样使用:`import foo from 'foo'`,不需要写成 `import foo from '../lib/foo'` - 同理`global`那个配置也是这样的,推荐将lib目录设置成跟`bower`一致的,全部来存放第三方类库,而`global`设置的目录,比如叫`common`,可以存放自己的`公用模块`。这样开发会更加灵活、方便。 - 注意全局模块不要有同名冲突。 ### 6. 支持复杂目录和多级目录设定 * 比如下面这种复杂路径: ```Javascript gulpman.config({ 'is_absolute': false, 'components': 'components/cc', 'runtime_views': 'runtime_views/rv', 'dist_views': 'dist_views/dv/dv', 'dist_assets': 'dist_assets/da', 'runtime_assets': 'runtime_assets/ra/ra', }) ``` ## Usage 使用 ### 1. CLI 执行Task: ```Shell # 初始化目录,建立components目录并添加一份html的demo文件 # init components dir and a html demo gulp gm:init # develop and watch 开发模式,监视相关文件变动,增量更新 gulp gm:develop # 指定编译和监视某个component, 提高性能和效率(其他文件不编译输出) gulp gm:develop -c component_name1,component_name2,component_name3... # publish 发布资源,包括合并、压缩资源、rev产生MD5等 gulp gm:publish # publish命令支持`-a`和`-v`参数指定输出资源/模板目录(可选) gulp gm:publish -v your_views_dist -a your_assets_dist # clean 清理构建输出的目录和文件 gulp gm:clean # clean 清理构建输出的目录和文件,包括自文件夹/目录 gulp gm:clean-deep # 编译输出一份运行时资源文件,但是不进入监视状态 # compile for develop, not watch gulp gm:compile ``` ### 2. 开发中只监视某个component目录 * 随着项目变大,开发中如果全局监视所有component资源,效率将会降低,因此可使用gulpman提供的监视子component的方式来开发,提高性能 * 比如说,只监视components目录下的home模块: ```Shell # this will only watch `components/home` components gulp gm:develop -c home ``` ### 3. 如何在gulpman下使用React * 安装React: `npm install react react-dom` * 在ES6文件中使用 ```Javascript import React from 'react'; import ReactDOM from 'react-dom'; // xxx ``` ### 4. 如何在js|es6|jsx中使用tpl模板 * 目前支持.tpl扩展名的模板文件,直接打包到最终的js文件中 * 用法:`import dialogTpl from './dialog.tpl'` 或者 `var dialogTpl = require('./dialog.tpl')` ### 5. 如何在HTML/CSS中嵌入base64编码的图片 * 只需要图片资源后面添加`?_gm_inline`即可 * 打包时候会将图片生成`base64`编码替换到到html中 ##### html ```html

Karat 克拉

``` ##### CSS/SCSS ```css .test { background: url(./img/testb64.png?_gm_inline) no-repeat; } ``` ### 6. 如何在HTML中嵌入内联CSS/JS * 类似图片base64,只需要资源后面添加`?_gm_inline`即可 ```html ``` * 注:所有内嵌嵌入的资源,包括图片/JS/CSS,在develop(监视)模式下,都已自动关联更新。即如果a.html文件中,内联嵌入了一个b.css,如果b.css发生了修改,那么a.html会自动编译更新。 ### 7. 如何使用Sprite雪碧图 * 通过配置启用CSS Sprite `gulpman.config({ enableCSSSprite: true })` 默认false不启用 * 基于spritesmith实现,在gulpman.config 中可传入spritesmith配置opts * 关于spritesmith详细参见:[https://github.com/Ensighten/spritesmith](https://github.com/Ensighten/spritesmith) * 只需要在scss文件中的图片url资源后面添加`?_gm_sprite`即可 ```css .demo { background: url(./img/abc.png?_gm_sprite) no-repeat; /* other style you can set ...*/ width: 50px; height: 50px; } ``` ### 8. 如何使用Usemin * 整合usemin,在gulpman.config 中可传入usemin的配置opts * 关于usemin详细参见:[https://github.com/zont/gulp-usemin](https://github.com/zont/gulp-usemin) * 只需要在html文件中添加usemin的build注释即可。支持`js`|`css`|`inlinejs`|`inlinecss`等语法 * 注意build注释中配置的输出路径写相对路径即可,跟script、link等标签类似,gulpman会自动转换成最终输出路径 ```html ``` ### 9. 如何使用前端js模板 * 支持tpl扩展名,放到components相关目录下即可,js 可以直接require或者import * 最终会作为字符串格式打包进js * tpl中仍然支持资源嵌入和图片base64等,如参照前面_gm_inline等语法即可 - import到es6中 ```js import dialogTpl from './dialog.tpl' ``` - 或者使用require语法 ```js var dialogTpl = require('./dialog.tpl') ``` ### 10. 引入css文件到js/html - 直接import即可,gulpman会自动加载到html页面中. ```js import from './style.css'; ``` ```js require('./style.css'); ``` ### 11. 使用iconfont转换 * 可以将svg转换成icon-font,用`@font-face`方式引用 * 初次使用先安装,运行`gulp gm:iconfont:install` * 将svg文件放到`components/iconfonts/source`目录下,运行`gulp gm:iconfont`即可 * 自动生成的icon-font和css文件将会在`iconfonts/gmicon`目录下 ### 12. 支持LAB.js来完成异步加载js * 引入LAB.js到项目中 * 使用LAB的api来加载即可,使用相对路径 * 代码用例: `$LAB.script("../testload/test.js").wait(()=>{console.log('test loaded')})` ### 13. Require CSS in js * 直接在js中require你的css文件(源文件时scss文件) * The CSS contents will be packaged into js files, and automatically injected to html when page opend. Using style tag * 使用时要确保添加 .css 扩展名 * 举例: `require('./style.css')` or `import style from './style.css'` ### 14. 如何启用karma单元测试 * 初次使用先安装,运行`gulp gm:karma:install`,会安装依赖和生成`karma.conf.js`文件 * 在您的components中的对应模块目录下,建立一个spec文件夹,将对应的spec文件放在里面,文件拓展名是.es6 * 运行 `gulp gm:karma:start` 来启动单元测试(watch模式),将会运行各spec文件,完成后可在生成的coverage文件夹中查看覆盖率结果 * 指定spec目录、browsers等karma的选项,可以在`karma.conf.js`中设置、定制等 ### 教程 [浏览教程链接](http://karat.cc/article/56a351c3e48d2d05682aa0ac "karat.cc") ### License MIT ================================================ FILE: assets/.babelrc ================================================ { "presets": ["es2015", "react", "stage-3"] } ================================================ FILE: index.js ================================================ /** * Gulpman * FOR MODULAR FRONT-END SOURCE COMPILE SYSTEM */ // ======================================= 'use strict' // system module let path = require('path'), j = path.join, sh = require("shelljs") // gulp module let gulp = require('gulp'), p = require('gulp-load-plugins')(), // modules pngquant = require('imagemin-pngquant'), browserify = require('browserify'), stringify = require('stringify'), buffer = require('vinyl-buffer'), source = require('vinyl-source-stream'), es = require('event-stream'), globby = require('globby'), through = require('through2'), // gulpman utils gmutil = require('./lib/gmutil'), base64 = require('./lib/base64'), store = require('./lib/store'), htmlInline = require('./lib/inline'), revReplace = require('./lib/revReplace'), gulpUsemin = require('./lib/gulp-usemin'), assetsPathParser = require('./lib/assetsPathParser'), htmlPathParser = require('./lib/htmlPathParser.js'), // css spriter spriter = require('./lib/spriter'), // fix prefix for revAll and revReplace cdnProxy = require('./lib/cdnProxy'), specificComponents = []; // define base vars ======================================== let isDevelop = true, isWatching = false // get the cwd const _cwd = process.cwd() const _echo_off = ' >/dev/null 2>&1' let _opts = { // is enable the absolute prefix url 'is_absolute': true, // source url prefix 'cdn_prefix': '', 'url_prefix': '/static', // define babel optionals 'babel': { 'presets': ['es2015', 'react', 'stage-3'], 'sourceMaps': 'inline' }, // library path and global module path 'lib': 'lib', 'global': 'global', // whether browserify `lib` directory 'compileLibFiles': false, // enable css-sprite; 'enableCSSSprite': false, // the components source dir 'components': './components', 'runtime_views': './views', 'dist_views': './views_dist', 'runtime_assets': './assets', 'dist_assets': './assets_dist', // for sprite // 'spritesmith': {} // for usemin. No need rev here, by global rev. 'usemin': { // css: [ p.rev ], // html: [ function () {return minifyHtml({ empty: true });} ], // js: [ p.uglify, p.rev ], inlinejs: [ p.uglify ] // inlinecss: [ p.cssnano ] }, 'iconfont': {}, 'cssnano': { discardUnused: { fontFace: false } } } // define raw source type =================================== const base_source_type = 'js,css', img_source_type = 'png,PNG,jpg,JPG,gif,GIF,jpeg,JPEG,webp,WEBP,bmp,BMP', img_source_reg = img_source_type.split(',').join('|'), jstpl_source_type = 'tpl', font_source_type = 'svg,SVG,tiff,ttf,woff,woff2,eot', other_source_type = 'txt,mp3,mp4,ogg,webm,mpg,wav,wmv,mov,ico', // the pure raw souce means the source do not need gulp deal at all! pure_source_type = [font_source_type, other_source_type ].join(), // all raw source all_raw_source_type = [base_source_type, img_source_type, font_source_type, jstpl_source_type, other_source_type].join(), all_raw_source_reg = all_raw_source_type.split(',').join('|') // uncompiled source ===================================== let sass_source, es6_source, all_raw_source, html_source, // For publish source js_source, lib_source, except_lib_source, dist_lib_path, dist_except_lib_path, css_source, // js templates file tpl_source, img_source, pure_source, dist_html_source, dist_css_source, dist_js_source, dist_tpl_source, dist_all_raw_source // init vars function initVars(){ _opts['usemin']['url_prefix'] = _opts['url_prefix'] _opts['dist_static'] = j(_opts['dist_assets'] /*, _opts['url_prefix']*/ ) _opts['runtime_static'] = j(_opts['runtime_assets'] /*, _opts['url_prefix']*/ ) _opts['runtime_static_tmp'] = j(_opts['runtime_assets'], '.tmp_raw_static') // components sources sass_source = j(_opts['components'], '**/*.{scss,sass}') es6_source = j(_opts['components'], '**/*.{es6,jsx}') all_raw_source = j(_opts['components'], '**/*.{'+all_raw_source_type+'}') html_source = [j(_opts['components'],'**/*.html'), '!'+j(_opts['components'], _opts['lib'], '**/*.html')] // to-be-published source ================================ js_source = j(_opts['runtime_static'], '**/*.js') lib_source = j(_opts['runtime_static'], _opts['lib'], '**/*.*') except_lib_source = '!' + lib_source dist_lib_path = j(_opts['dist_static'], _opts['lib']) dist_except_lib_path = '!' + dist_lib_path css_source = j(_opts['runtime_static'], '**/*.css'), //js tpl tpl_source = j(_opts['runtime_static'], '**/*.tpl'), img_source = j(_opts['runtime_static'],'**/*.{'+img_source_type+'}') pure_source = j(_opts['runtime_static'], '**/*.{'+pure_source_type+'}') // dist source path dist_html_source = j(_opts['dist_views'], '**/*.html') dist_css_source = j(_opts['dist_static'], '**/*.css') dist_js_source = j(_opts['dist_static'], '**/*.js') dist_tpl_source = j(_opts['dist_static'], '**/*.tpl') dist_all_raw_source = j(_opts['dist_assets'], '**/*.{'+all_raw_source_type+'}') // fix cdn prefix useage by proxy _opts = cdnProxy.proxyPrefix(_opts) } // init vars before gulpman tasks initVars() // COMMON UTILS FN ======================================== function OSInform(title, _message, err){ let message = _message || title try { // call the os inform sh.exec("osascript -e 'display notification \""+message+"\" with title \""+title+"\"'"+_echo_off) }catch(err){ gmutil.warn('*Call System Inform Failed!') } if(err){ var errDesc = err['codeFrame'] || '' // print the err messsage err && err.message && gmutil.error('\n*'+err.plugin+': '+err.name+'\n' + err.message+'\n'+errDesc+'\n') } return { then (cb){ cb && cb() } } } function OSInformError(title, err, errDesc){ let filePath = getRelativePathOfComponents(err.fileName) var einfo = errDesc || filePath if(einfo === undefined){ einfo = 'Interal Error Occured' } return OSInform(title, einfo, err) } function getB64ImgReg(){ return new RegExp('(?=[\'"]?)([\\w\\.\\-\\?\\-\\/]+?(\\.('+img_source_reg+')))(\\?_gm_inline)(?=[\'"]?)', 'gm') } // browserify function browserified(fpath, sourceDir){ let _bOpts = { entries: fpath, debug: true, extensions: ['.es6', '.jsx', '.js'], //global modular paths: [ j(sourceDir, _opts['lib']), j(sourceDir, _opts['global']) ], transform: [ stringify(['.tpl', '.txt']), ['browserify-css', { global: true, autoInject: true, onFlush: function(options, done) { // @debug // here can do a function for calculate path let fRelativeName = path.relative(_opts['runtime_static_tmp'], options.href) let tmpSourceFilePath = path.join(_cwd, _opts['components'], fRelativeName) let sourceFilePath = gmutil.convertSource(tmpSourceFilePath, 'css') let tmpJSRelativePath = path.relative(_opts['runtime_static_tmp'], fpath) let jsSoucefilePath = path.join(_opts['components'], tmpJSRelativePath) // @debug the fpath is not real source path, but ignore this path becuase no use now. store.save(sourceFilePath, jsSoucefilePath, 'requiredCSS') done(); } // for path src in css /*processRelativeUrl: function(relativeUrl) { if (_.contains(['.jpg','.png','.gif'], path.extname(relativeUrl))) { // Embed image data with data URI var DataUri = require('datauri'); var dUri = new DataUri(relativeUrl); return dUri.content; } return relativeUrl; }*/ }] ] } // use wathcify to browserify // var watchifybOpts = Object.assign(_bOpts, watchify.args) // return watchify(browserify(watchifybOpts)).bundle() return browserify(_bOpts) .bundle() .on('error', function(err){ err.plugin = 'Browserify' OSInformError('Browserify Error', err, err['message']) console.log(err) // browserify的流特殊,需要emti才能停止,否则会挂掉 this.emit('end') }) .pipe(source(fpath)) .pipe(buffer()) } function getDirFromTmpStaticToRuntimeStatic(p){ var diffDir = path.relative(_opts['runtime_static_tmp'], p.dirname), newDirname = j(_opts['runtime_static'], diffDir) return newDirname } // 根据代码的require等,打包js文件 function doBrowserify(){ // 这里不做增量打包,因为js有自身依赖机制,并非单一依赖,需要重新整体打包 // 此处如果是tpl发生变化,也会导致重新打包 // 此处取tmp目录,确保源文件干净没有被browserify过 let filesGlob = ''; if (specificComponents.length > 0) { const browserifyComponentsList = [_opts['global']].concat(specificComponents); // if enable compile `lib` files, then push it to browserify path; if (_opts['compileLibFiles']) { browserifyComponentsList.unshift(_opts['lib']); } filesGlob = '{' + browserifyComponentsList.join() + '}/'; } var files = globby.sync(j(_opts['runtime_static_tmp'], filesGlob + '**/*.es6')), tasks = files.map((entry)=>{ // 注意,此处dest目录必须和src目录不一致,否则dest打包后会把输出结果直接输出到src, 那么会影响后续打包的文件,后续打包的文件的require的文件已经不是srcw文件,而是被dest后的文件,因此会有require、define那块额外添加的代码的冗余 return browserified(entry, _opts['runtime_static_tmp']) .pipe(p.rename(p=>{ /** * 此处作用是,将.tmp_raw_static目录, * 作为未打包备份目录,不被打包后文件覆盖 * 这样.tmp_raw_static目录可以被watch中触发的打包服务 */ p.dirname = getDirFromTmpStaticToRuntimeStatic(p) p.extname = '.js' })) .pipe(gulp.dest('./')) }) return es.merge.apply(null, tasks) } function getComponentsPath(){ return j(_cwd, _opts['components']) } // get handler for relevancy update function getRelevancyHandler() { return { // only the scss files in raw folder implemented increasement updates 'scss': compile_sass, 'html': function (rawHtmlFile){ // The html has implemented increaement updates for Base64 gmutil.tip('*Relevancy HTML: '+rawHtmlFile) let basepath = getComponentsPath() parseRawHTML(gulp.src(rawHtmlFile), basepath, true) }, 'requiredCSS': function(filePath, event) { // here the filePath is related ES6 js file, not scss file // the `event` comes from watcher fireUpdate('es6', { 'type': 'changed', 'path': filePath, }) }, 'sprite': function (filePath, event) { /** * if the img is in sprite-relevancy, then fire the scss event to re-compile-css */ // the `event` comes from raw files watcher fireUpdate('sprite', { 'type': 'changed', 'path': filePath, }) }, 'tpl': function(filePath){ // the current was changed scss file which is relevancy with the tpl file var event = getUpdateEvent() updateTplFile(filePath) event['path'] = filePath fireUpdate('tpl', event) } } } function updateTplFile(tmpFile){ // /Users/cloud/work/karat/k3/assets/.tmp_raw_static/home/dialog.tpl var absTmpStatic = j(_cwd, _opts['runtime_static_tmp']), tplRelPath = path.relative(absTmpStatic, tmpFile), tplRelPathOfComponents = j(_opts['components'], tplRelPath) sh.cp('-rf', tplRelPathOfComponents, tmpFile) gmutil.warn('*Relink Tpl: '+tplRelPathOfComponents) } // for sprite function spriteCSS(entry) { // gmutil.alert('Sprite Entry: '+entry) // 注意之前的问题: 检测到有sprite参数的css文件才会被push到下一个流,如果都没有,处理完这个流就是空的了。已经fix return gulp.src(entry) .pipe(spriter({ 'cwd': _cwd, // 'includeMode': 'explicit', // The path and file name of where we will save the sprite sheet 'dist_root': _opts['runtime_static'], // 'spriteSheet': j(_opts['dist_static'],'sprite_sheet.png'), // Because we don't know where you will end up saving the CSS file at this point in the pipe, // we need a litle help identifying where it will be. // 'pathToSpriteSheetFromCSS': '../sprite_sheet.png' // check if the spriter-img existed 'shouldVerifyImagesExist': true, // throw error when occured 'silent': false, 'spritesmithOptions': _opts['spritesmith'] })) .on('error', function(err){ OSInformError('CSS Spriter Error', err, err['message']) this.end() }) //这里用通用的traversal解决了 .pipe(gulp.dest('./')) } // wrap the store check fn function storeCheck(filepath, dbType, handlerType, evtObj){ // check if the file is in relevancy data return store.check( filepath, getRelevancyHandler(), dbType, handlerType, evtObj ) } // Main Tasks ===================================== function safeClean(path) { if (!path.replace(/[.\/]+/g, '')) { return '' } else { return path } } gulp.task('gm:clean', ()=>{ sh.rm('-rf', [ safeClean(_opts['runtime_views']), safeClean(_opts['dist_views']), safeClean(_opts['runtime_static']), safeClean(_opts['dist_static']), safeClean(_opts['runtime_static_tmp']), safeClean(_opts['runtime_assets']), safeClean(_opts['dist_assets']), ]) }) // clean dir includes components gulp.task('gm:clean-deep', ['gm:clean'],()=>{ var pSep = '/' //path.sep var runtime_assetsRoot = path.normalize(_opts['runtime_assets']).split(pSep)[0] var dist_assetsRoot = path.normalize(_opts['dist_assets']).split(pSep)[0] var runtime_viewsRoot = path.normalize(_opts['runtime_views']).split(pSep)[0] var dist_viewsRoot = path.normalize(_opts['dist_views']).split(pSep)[0] sh.rm('-rf', [ runtime_assetsRoot, dist_assetsRoot, runtime_viewsRoot, dist_viewsRoot ]) }) // clean dir includes components gulp.task('gm:clean-all', ['gm:clean'],()=>{ sh.rm('-rf', [ _opts['components'], ]) }) gulp.task('gm:compile-copy', ()=>{ return gulp.src(all_raw_source) .pipe(gulp.dest(_opts['runtime_static'])) // 复制一份 非编译到static备份目录 .pipe(gulp.dest(_opts['runtime_static_tmp'])) }) function compile_sass(singleFile){ // 此处增量编译scss, 当处于监视状态,只编译修改了的scss文件 // 此处还没有关联到sass的增量,只关联了raw source中的css // @todo let _sass_source = singleFile || sass_source // gmutil.tip('*Compile SCSS: '+_sass_source) return gulp.src(_sass_source) .pipe(p.sourcemaps.init()) .pipe(p.sass()) .on('error', function(err){ OSInformError('SCSS Compile Error', err, 'Compile Error') this.emit('end') }) .pipe(p.sourcemaps.write()) .pipe(base64({ 'is_absolute': _opts['is_absolute'], 'baseDir': _opts['runtime_static'], 'url_prefix': _opts['url_prefix'], 'components': _opts['components'], 'isDevelop': isDevelop, // the current files type 'type': 'css', 'rule': getB64ImgReg() })) .on('error', function(err){ OSInformError('CSS Img-Base64 Error', err, err['message']) this.end() }) .pipe(gulp.dest(_opts['runtime_static'])) // 这里没有复制到static的.tmp_raw_static备份目录 } gulp.task('gm:compile-sass', ()=>{ return compile_sass() }) // generate sprite if exist gulp.task('gm:compile-css-sprite', ()=>{ if (!_opts['enableCSSSprite']) { return; } // here generate sprite into css // now sprite all css in runtime_static let files = globby.sync([css_source, /*except_lib_source*/]), // 每个css的sprite图路径可能是不一样的,所以要遍历的去sprite,每次动态修改sprite的config的输出sprite图的路径 tasks = files.map(entry=>spriteCSS(entry)) // @debug // 现在问题是,spriteCSS还没运行完,下面就执行了,parsseHTML,所以导致html内容是spriteCSS之前的 return es.merge.apply(null, tasks) // here can do optimization , continue use this pipe to do traversal }) gulp.task('gm:compile-css-traversal', ()=>{ return gulp.src([css_source]) .pipe(assetsPathParser.absolutizePath({ // replace relative path to absolute path 'cwd': _cwd, // add for tpl parse '_opts': _opts, // 跟资源最终url前缀有关 '_isRuntimeDir': false, 'all_raw_source_reg': all_raw_source_reg, // end for tpl parse 'is_absolute': _opts['is_absolute'], 'static_dir': _opts['runtime_static'], 'cdn_prefix': _opts['cdn_prefix'], 'url_prefix': _opts['url_prefix'], 'components': _opts['components'] })) .pipe(gulp.dest('./')) // for css require in js .pipe(p.rename(fpath=>{ let fRelativeDir = path.relative(_opts['runtime_static'], fpath.dirname) let fTmpStaticDir = path.join(_opts['runtime_static_tmp'], fRelativeDir) fpath.dirname = fTmpStaticDir })) .pipe(gulp.dest('./')) }) gulp.task('gm:compile-css', cb=>{ return p.sequence( 'gm:compile-sass', 'gm:compile-css-sprite', 'gm:compile-css-traversal' )(cb) }) gulp.task('gm:compile-media-check', ['gm:compile-css'], function(){ // 此刻检查关联性,sprite那块还未处理,所有html更新的inline的css中,只有处理了base64,应该在sprite处理完css后,再检查 if(isWatching){ // store for relevancy scss var curEvent = getUpdateEvent() if(curEvent){ var epath = curEvent.path, // solution是fireUpdate添加的,fire类型 solution = curEvent['solution'] if(solution == 'sprite' ) { // 对于sprite引起改变的css var tarFilePath = epath }else { // 其余的按照编译型资源处理 // 计算源文件(来自components的资源,计算出输出后的资源) var tarPath = getAbsPathOfTarget(epath, _opts['runtime_static']) var tarFilePath = translatePathExtname('css', tarPath) } gmutil.tip('*Modified File: '+epath) gmutil.tip('*Target File: '+tarFilePath) storeCheck(tarFilePath) // check if it is requiredCSS storeCheck(epath, 'requiredCSS', 'requiredCSS', curEvent) // @debug 如果不remove,会有重复触发 removeUpdateEvent() }else { gmutil.warn('*Unhandled Event: '+JSON.stringify(curEvent)) } } }) /** * THIS WILL TRIGGER `Trunk filled` Problem */ // for sass and sprite and inline(base64) // gulp.task('gm:xxx', p.sequence('ttt','yyy')) gulp.task('gm:compile-es6', ()=>{ return gulp.src(es6_source) .pipe(p.babel(_opts['babel'])) .on('error', function(err) { OSInformError('Babel Error', err) this.end() throw Error('*Compile Stopped for the Babel Error') }) .pipe(p.rename(path=>{ // 这里有一部分是从es6转成的.js,也有一部分是jsx转成的.js // 此处都统一扩展名设置为.es6,方便后面browserify打包 path.extname = '.es6' })) .pipe(assetsPathParser.absolutizePath({ // replace relative path to absolute path 'cwd': _cwd, // add for tpl parse '_opts': _opts, // related to final url '_isRuntimeDir': false, 'all_raw_source_reg': all_raw_source_reg, // end for tpl parse 'is_absolute': _opts['is_absolute'], 'static_dir': _opts['runtime_static'], 'cdn_prefix': _opts['cdn_prefix'], 'url_prefix': _opts['url_prefix'], 'components': _opts['components'] })) // 输出到tmp目录,是为了browserify文件时,源文件时干净的,避免被打包过的又打包一次 .pipe(gulp.dest(_opts['runtime_static_tmp'])) // 这个是输出目录 .pipe(gulp.dest(_opts['runtime_static'])) }) // 处理tpl, gulp.task('gm:compile-tpl', cb=>{ // 这儿最好根据打包目录来拆分,这样publish后,打包和开发目录都是正常的 var _isRuntimeDir = isDevelop var tb = gulp.src(j(_opts['runtime_static_tmp'], '**/*.tpl')) .pipe(assetsPathParser.absolutizePath({ // replace relative path to absolute path 'cwd': _cwd, // add for tpl parse '_opts': _opts, // 跟资源最终url前缀有关 '_isRuntimeDir': false, 'all_raw_source_reg': all_raw_source_reg, // end for tpl parse 'is_absolute': _opts['is_absolute'], 'static_dir': _opts['runtime_static'], 'cdn_prefix': _opts['cdn_prefix'], 'url_prefix': _opts['url_prefix'], 'components': _opts['components'] })) /** * @debug * 这里需要输出到tmp_runtime_static目录一份,提供干净打包 * 这样也导致一个问题,update-tpl的时候,源文件也是来自于tmp_runtime_static, * 这样这块文件在develop的时候是脏的,可能跟components中的tpl不一致,需要修复 * * 修复方法1,如果不再往tmp_static写入htmlParseFlow的tpl,tmp_static 就始终一个源tpl,从raw_watcher那儿监听,如果源tpl 修改了,tmp_static 中的tpl才会更新。这样有问题,因为browserify es6的时候,是从tmp_static 中取文件的(为了保持干净),那么嵌入到js中的tpl就是源文件内容,没有处理过的,嵌入资源也没有 * 修复方式2 每次打包前从raw的components目录中复制一份tpl到tmp_static,这样来更新(htmlParseFlow后又回覆盖这个tpl文件) * */ var rsB = htmlParseFlow(tb, _isRuntimeDir) .pipe(gulp.dest('./'))// 不能根据修复1取消,有错误,用修复2 .pipe(p.rename(p=>{ // 输出到正式runtime_static p.dirname = getDirFromTmpStaticToRuntimeStatic(p) })) // 输出到正式目录供使用 .pipe(gulp.dest('./')) if(isDevelop){ return rsB }else { // 再输出到dist_static中做备用比如js中可能异步加载? return rsB.pipe(p.rename(p=>{ // 输出到正式runtime_static var diffDir = path.relative(_opts['runtime_static'], p.dirname), newDirname = j(_opts['dist_static'], diffDir) p.dirname = newDirname })) .pipe(gulp.dest('./')) } }) gulp.task('gm:compile-browserify', ['gm:compile-tpl', 'gm:compile-es6'], ()=>{ return doBrowserify() }) gulp.task('gm:compile-html', cb=>{ return parseRawHTML(gulp.src(html_source), null, true) }) // only used for publish gulp.task('gm:publish-html', cb=>{ // the `null` is basepath // the `false` is isRuntimeDir return parseRawHTML(gulp.src(html_source), null, false) }) gulp.task('gm:publish-usemin', ()=>{ let html_src = j(_opts['dist_views'], '**/*.html') if(_opts['is_absolute']){ _opts['usemin']['path'] = _opts['dist_assets'] var diffPath = path.relative(_opts['dist_views'], _opts['dist_assets']) _opts['usemin']['outputRelativePath'] = diffPath } return gulp.src(html_src) .pipe(gulpUsemin(_opts['usemin'])) .pipe(gulp.dest(_opts['dist_views'])) }) gulp.task('gm:compile', cb => { updateSpecificComponentsSource(); return p.sequence( 'gm:clean', 'gm:compile-copy', 'gm:compile-css', // 由于tpl 中可能需要嵌入css,因此将compile-css和compile-browserify 变成串行 'gm:compile-browserify', 'gm:compile-html' )(cb) }); /** * FOR DEVELOP WATCHT ================================ */ /** * 因为task不能传参,这里用全局变量来实现, * 后续考虑优化 * @type {[type]} */ let _g_update_evt = { '_current_event': null, 'scss': { 'event': null, 'task': 'gm:compile-media-check' }, 'sprite': { 'event': null, 'task': 'gm:compile-media-check' }, 'es6': { 'event': null, 'task': 'gm:update-js' }, // need browserify 'tpl': { 'event': null, 'task': 'gm:update-tpl' } } function fireUpdate(type, event){ event['solution'] = type _g_update_evt['_current_event'] = _g_update_evt[type]['event'] = event let _task = _g_update_evt[type]['task'] _task && gulp.start(_task) } function getUpdateEvent(type){ if(type){ return _g_update_evt[type]['event'] }else { return _g_update_evt['_current_event'] } } function removeUpdateEvent(type){ if(type){ _g_update_evt[type] && (_g_update_evt[type]['event'] = null) }else { _g_update_evt['_current_event'] = null } } function htmlParseFlow(b, _isRuntimeDir){ return b.pipe(base64({// 第二步,替换生成html原本内容本身中的base64图片路径, 比如img标签中有?_gm_inline则被替换为base64 'is_absolute': _opts['is_absolute'], 'baseDir': _opts['runtime_assets'], 'url_prefix': _opts['url_prefix'], 'views': _isRuntimeDir ? _opts['runtime_views'] : _opts['dist_views'], 'dist_assets': _opts['dist_assets'], 'isDevelop': isDevelop, 'type': 'html', 'rule': getB64ImgReg() })) .on('error', function(err){ OSInformError('HTML Img-Base64 Error', err, err['message']) this.end() }) .pipe(htmlInline({// 第三步,向html中替换插入行内标记的内容 'is_runtime': _isRuntimeDir, 'absoluteRoot': _opts['is_absolute'] ? (_isRuntimeDir ? _opts['runtime_assets'] : _opts['dist_assets']) : false, queryKey: '_gm_inline', // 选择是否压缩css minifyCss: _isRuntimeDir ? false : true, // 选择是否压缩js, minifyJs: _isRuntimeDir ? false : true, 'dist_dir': _opts['dist_assets'], 'runtime_dir': _opts['runtime_assets'], 'url_prefix': _opts['url_prefix'], 'root': _cwd })) .on('error', function(err){ OSInformError('htmlInline Error', err) this.end() }) } // 解析html文件中的资源路径和做处理 function parseRawHTML(b, basepath, _isRuntimeDir) { /** * @debug 未完成inline后的路径转换 * * 1. 这里inline后需要一个路径转换,比如css中./a.png 当inline到html中,可能变成了 ../../assets/static/home/a.png,不转换将可能404。 * 2. 如果将行内内容或者components中全部内容中(可能主要是css的资源引用,js现在没有做资源嵌入)的资源引用都做成绝对路径,那么没有这个问题了。也可以考虑在做inline的时候,转换路径,也就是1。 */ // 第一步先计算并替换html的相关路径 var tb = b.pipe(htmlPathParser({ '_opts': _opts, 'basepath': basepath, '_isRuntimeDir': _isRuntimeDir, 'all_raw_source_reg': all_raw_source_reg })) .on('error', function(err) { OSInformError('ParseHtml Error', err) this.end() }) return htmlParseFlow(tb, _isRuntimeDir) .pipe(gulp.dest(_isRuntimeDir ? _opts['runtime_views'] : _opts['dist_views'])) } function getRelativePathOfComponents(epath) { if(epath === undefined) return; let comsPath = getComponentsPath() return path.relative(comsPath, epath) } function translatePathExtname(type, _path){ var d = { 'js': function(){ return _path.replace(/\.(es6|jsx)$/gm, '.js') }, 'css': function(){ return _path.replace(/\.(scss|sass)$/gm, '.css') } } return d[type]() } function delChangedFile(epath, delOutDir, type){ let relPath = getRelativePathOfComponents(epath) // 这里可以用path的api来处理后重新生成,用正则不准确可能 // 删除文件,首先判断类型,来处理拓展名 if(type == 'js'){ // relPath = relPath.replace(/\.(es6|jsx)$/gm, '.js') relPath = translatePathExtname('js', relPath) }else if(type == 'css'){ // relPath = relPath.replace(/\.(scss|sass|css)$/gm, '.css') relPath = translatePathExtname('css', relPath) }else { // relPath is relPath,keep the extname } let delFilePath = j(delOutDir, relPath) gmutil.tip('Delete File: '+ delFilePath) // 删除输出的文件 sh.rm('-rf', delFilePath) } function getRelativePathOfTarget(epath, tarBaseDir){ let relPath = getRelativePathOfComponents(epath), tarPath = j(tarBaseDir, relPath), dirPath = path.dirname(tarPath) return { 'tarPath': tarPath, 'dirPath': dirPath } } function getAbsPathOfTarget(epath, tarBaseDir){ return j(_cwd, getRelativePathOfTarget(epath, tarBaseDir)['tarPath']) } // check file dep function _checkRelevancy(filePath, event){ // check for raw sources storeCheck(filePath) storeCheck(filePath, 'sprite', 'sprite', event) } function getSpecificComponentsList() { if (process.argv[4]) { return process.argv[4].split(','); } return []; } function updateSpecificComponentsSource() { const componentsList = getSpecificComponentsList(); if (componentsList.length > 0) { // should filter the `lib` html files; const htmlList = componentsList.concat(_opts['global']); specificComponents = [].concat(componentsList); ; const sourceComponents = [_opts['lib'], _opts['global']].concat(componentsList).join(); all_raw_source = j(_opts['components'], '{' + sourceComponents + '}/**/*.{'+all_raw_source_type+'}'); html_source = [j(_opts['components'],'{' + htmlList.join() + '}/**/*.html'), '!'+j(_opts['components'], _opts['lib'], '**/*.html')]; gmutil.warn('\n'); gmutil.warn('Components Source: \n -> '+ componentsList.join(', ')); gmutil.warn('\n'); } } // tasks gulp.task('gm:update-es6', ()=>{ //这里用增量更新处理了已经,只babel转换有变动的es6 var _evt = getUpdateEvent('es6') let epath = _evt.path, etype = _evt.type return gulp.src(epath) .pipe(p.babel(_opts['babel'])) .on('error', function(err){ OSInformError('Babel Error', err) this.end() }) .pipe(p.rename(path=>{ // 这里算法可能需要优化简化一下 let relPath = getRelativePathOfComponents(epath) let namePt = new RegExp(`${path.basename}\.(es6|jsx)$`, 'gm') relPath = relPath.replace(namePt, '') /** * 输出到 未打包备份目录中, * 而不是输出到已经打包的目录, * 否则会覆盖正式的static目录中打包后的js文件) */ path.dirname = j(_opts['runtime_static_tmp'], relPath) path.extname = '.es6' gmutil.tip('*ES6 File Changed: ' + epath) })) .pipe(gulp.dest('./')) }) gulp.task('gm:update-js', ['gm:update-es6'], ()=>{ return doBrowserify() }) // for browserify and tpl refresh gulp.task('gm:update-tpl', ['gm:compile-tpl'], ()=>{ return doBrowserify() }) gulp.task('gm:develop', ['gm:compile'], ()=>{ let _cmdBase = { 'component': { '-c': true, '-component': true } } let _how = process.argv[3]; let _watch_es6_source = es6_source, _watch_css_source = sass_source, _watch_html_source = html_source, _watch_all_raw_source = all_raw_source; const _specificList = getSpecificComponentsList(); const _whatList = [_opts['lib'], _opts['global']].concat(_specificList); const _what = '{' + _whatList.join() + '}'; if(_how in _cmdBase['component'] && _specificList.length > 0){ gmutil.warn('\n*Watch Component: ' + _what) _watch_es6_source = j(_opts['components'], _what, '**/*.{es6,jsx}') _watch_css_source = j(_opts['components'], _what, '**/*.{scss,sass}') _watch_html_source = [j(_opts['components'], _what, '**/*.html'), '!'+j(_opts['components'], _opts['lib'], '**/*.html')] _watch_all_raw_source = j(_opts['components'], _what, '**/*.{'+all_raw_source_type+'}') } gmutil.warn('\n*Source Compiled Succeed. \n*Loading source. Waiting ...\n') // watch es6\js ---------------------------------- let js_watcher = gulp.watch(_watch_es6_source) js_watcher.on('change', event=>{ switch(event.type){ case 'deleted': delChangedFile(event.path, _opts['runtime_static'], 'js') delChangedFile(event.path, _opts['runtime_static_tmp'], 'js') break // for added changed default: fireUpdate('es6', event) } }) // watch scss ---------------------------------- let css_watcher = gulp.watch(_watch_css_source) // 目前watch scss并没有做成增量,因为sass有自身模块依赖机制 css_watcher.on('change', event=>{ let epath = event.path, etype = event.type switch(event.type){ case 'deleted': delChangedFile(epath, _opts['runtime_static'], 'css') break default: fireUpdate('scss', event) } return false }) // watch html -------------------------------------- let html_watcher = gulp.watch(_watch_html_source) html_watcher.on('change', event=>{ let epath = event.path, etype = event.type, f = getRelativePathOfTarget(epath, _opts['runtime_views']) if(etype == 'changed' || etype == 'added'){ let relPath = getRelativePathOfComponents(epath) let htmlFilePathOfCwd = j(_opts['components'], relPath) let basepath = getComponentsPath() parseRawHTML(gulp.src(htmlFilePathOfCwd), basepath, true) }else if(etype == 'deleted'){ delChangedFile(epath, _opts['runtime_views']) }else if(etype == 'renamed'){ let oldPath = event.old, oldf = getRelativePathOfTarget(oldPath, _opts['runtime_views']) sh.cp('-rf', epath, f.dirPath) sh.rm('-rf', oldf.tarPath) gmutil.tip('Rename HTML File: '+oldf.tarPath) }else { // ddd } }) // raw source ------------------------------------- let raw_watcher = gulp.watch(_watch_all_raw_source) raw_watcher.on('change', function(event) { let epath = event.path, file_extname = path.extname(epath), f = getRelativePathOfTarget(epath, _opts['runtime_static']), tmp_f = getRelativePathOfTarget(epath, _opts['runtime_static_tmp']) let runtimeFile = gmutil.pathInAssets(_cwd, epath, _opts['components'], _opts['runtime_static']) if(event.type == 'added' || event.type == 'changed'){ sh.cp('-rf', epath, f.dirPath) gmutil.tip('*Copy Raw File To: '+f.tarPath) // 复制js和tpl模板文件 if(file_extname == '.js' || file_extname == '.tpl') { // for the reason of browserify-pack, so need copy to tmp_static sh.cp('-rf', epath, tmp_f.dirPath) gmutil.tip('*Copy Raw File To: '+tmp_f.tarPath) if(file_extname == '.tpl'){ // the tpl need re-browserify fireUpdate('tpl', event) } } }else if(event.type == 'deleted'){ sh.rm('-rf', f.tarPath) gmutil.tip('*Delete Raw File: '+f.tarPath) if(file_extname == '.js') { sh.rm('-rf', tmp_f.tarPath) gmutil.tip('*Delete Raw File: '+f.tarPath) } }else if(event.type == 'renamed'){ let oldPath = event.old, oldf = getRelativePathOfTarget(oldPath, _opts['runtime_static']), old_tmpf = getRelativePathOfTarget(oldPath, _opts['runtime_static_tmp']) gmutil.tip('*Rename Raw File: '+oldf.tarPath) sh.cp('-rf', epath, f.dirPath) sh.rm('-rf', oldf.tarPath) if(file_extname == '.js') { sh.cp('-rf', epath, tmp_f.dirPath) sh.rm('-rf', old_tmpf.tarPath) gmutil.tip('*Delete Raw File: '+f.tarPath) } }else { gmutil.warn('Other Event: \n' + event) } // check dep _checkRelevancy(runtimeFile, event) }) .on('error', function(err){ gmutil.error('Error: ', err['message']) console.log(err) this.end() }) // ready for watch -------------------------------- isWatching = true gmutil.tip('\n*Now Watching For Development:\n') OSInform('Ready For Development', 'Start') }) /** * FOR PUBLISH SOURCE ================================ */ // utils function setRevReplace(){ let manifest = gulp.src(j(_opts['dist_assets'],'rev-manifest.json')) return revReplace({ 'manifest': manifest, // 如果is_absolute为false, 那么不启用cdn_prefix 'prefix': _opts['is_absolute'] ? _opts['cdn_prefix'] : '', 'url_prefix': _opts['url_prefix'] }) } // tasks gulp.task('gm:cssmin', ()=>{ // 除去lib return gulp.src([css_source, except_lib_source]) .pipe(p.cssnano(_opts['cssnano'])) .pipe(gulp.dest(_opts['dist_static'])) }) gulp.task('gm:imagemin', ()=>{ // 除去lib return gulp.src([img_source, except_lib_source]) .pipe(p.imagemin({ progressive: true, debug: true, svgoPlugins: [{ 'removeViewBox': false }], use: [pngquant()] })) .pipe(gulp.dest(_opts['dist_static'])) }) gulp.task('gm:jsmin', ()=>{ // 除去lib return gulp.src([js_source, except_lib_source]) .pipe(p.uglify()) .on('error', function (err){ gmutil.error('*Warning \n*Jsmin Error: \n') console.log(err); gmutil.warn('*Failed ...') this.end(); }) .pipe(gulp.dest(_opts['dist_static'])) }) gulp.task('gm:rev-js', ()=>{ return gulp.src(dist_js_source) .pipe(setRevReplace()) .pipe(gulp.dest(_opts['dist_static'])) }) /** * Rev Generate MD5 for Source and File name * ================================= */ gulp.task('gm:rev', p.sequence( 'gm:rev-lib-pre', // for usemin 'gm:publish-usemin', 'gm:rev-source', ['gm:rev-html', 'gm:rev-css', 'gm:rev-js']) ) /** * 由于lib属于第三方模块的特殊性,在处理uglify js的时候会导致错误等, * 因此特殊处理,只压缩css */ // for the lib prepare gulp.task('gm:rev-lib-pre', p.sequence('gm:rev-copy-lib', ['gm:lib-mincss', 'gm:lib-uglify'])) // copy lib source to dist lib dir gulp.task('gm:rev-copy-lib', ()=>{ return gulp.src(lib_source) .pipe(gulp.dest(dist_lib_path)) }) // minify the lib css gulp.task('gm:lib-mincss', ()=>{ return gulp.src(j(dist_lib_path, '**/*.css')) .pipe(p.cssnano(_opts['cssnano'])) .pipe(gulp.dest(dist_lib_path)) }) // minify the lib js gulp.task('gm:lib-uglify', ()=>{ return gulp.src(j(dist_lib_path, '**/*.js')) // uglify libjs常会导致错误,某些第三方类库uglify导致的 // .pipe(p.uglify()) .pipe(gulp.dest(dist_lib_path)) }) /** * 将dist目录的所有编译后资源,包括css,js,img,font等,做md5 */ gulp.task('gm:rev-source', ()=>{ const revOpts = { // 禁止参与重命名的文件 'dontRenameFile': ['.html', /^\/favicon.ico$/], // 无需关联处理文件 'dontGlobal': [ /^\/favicon.ico$/, '.txt' /*'.tpl'*/], // 该项配置只影响当前src的静态资源中 绝对路径的资源引用地址 'prefix': _opts['transformPath'] ? '' : (_opts['is_absolute'] ? _opts['cdn_prefix'] : ''), // 如果prefix传入的是函数,那么将在rev-all中执行transformPath 'transformPath': _opts['transformPath'] }; return gulp.src(dist_all_raw_source) .pipe(p.revAll.revision(revOpts)) /** * 这里因为assets_url的缘故, * dist_all_raw_source的路径要不带static, * 否则最终发布的html,assets_url会跑到_opts['cdn_prefix']前面。 */ .pipe(gulp.dest(_opts['dist_assets'])) // 输出manifest文件 .pipe(p.revAll.manifestFile()) .pipe(gulp.dest(_opts['dist_assets'])) }) gulp.task('gm:rev-html', ()=>{ return gulp.src(dist_html_source) .pipe(setRevReplace()) .pipe(gulp.dest(_opts['dist_views'])) }) gulp.task('gm:rev-css', ()=>{ /** * debug * 这个rev插件有个bug,对于css中,以emma-wat-012.jpg这种中划线格式的图片,md5后,css中资源未被替换... */ return gulp.src(dist_css_source) .pipe(setRevReplace()) .pipe(gulp.dest(_opts['dist_static'])) }) // create ../assets_dist gulp.task('gm:create-assets-dist-dir', ()=>{ // 目前由于browserify可能已经不需要了(这一步之前已经生成了) sh.exec('mkdir ' + _opts['dist_assets']+ _echo_off) }) gulp.task('gm:copy-pure-source', ()=>{ return gulp.src([pure_source, except_lib_source]) .pipe(gulp.dest(_opts['dist_static'])) }) // for compile publish gulp.task('gm:copy', [ 'gm:create-assets-dist-dir', 'gm:copy-pure-source', 'gm:publish-html' ],()=>{ // 从 runtime的views目录内容,拷贝到dist的views目录 // return gulp.src(j(_opts['runtime_views'], '**/*.*')) // .pipe(gulp.dest(_opts['dist_views'])) }) //set Mode in Publish gulp.task('gm:publish-mode', ()=>{ let args = process.argv.slice(3), r = {} // 如果在CLI指定了输出目录 if(args.length){ args.forEach((v,i)=>i%2 == 0 && (r[v] = args[i+1])) let _dist_views = r['-v'] || r['-views'] let _dist_assets = r['-a'] || r['-assets'] gmutil.warn('*Dist Path Config\n*dist_assets: '+(_dist_assets || '@config')+'\n*dist_views: '+(_dist_views || '@config')); (_dist_assets || _dist_views) && updateConf(gmutil.validateObj({ 'dist_assets': _dist_assets, 'dist_views': _dist_views })) } isDevelop = false }) gulp.task('gm:osinform', ()=>{ OSInform('Publish Succeed', 'Completed') }) // publish source ,based on the runtime source gulp.task('gm:publish', p.sequence( 'gm:publish-mode', 'gm:compile', 'gm:copy', ['gm:jsmin', 'gm:cssmin', 'gm:imagemin'], 'gm:rev', 'gm:osinform' )) // For init demo and constructure =============== // init dir and create some meta files gulp.task('gm:generate-config', ()=>{ let conf_path = j(__dirname ,'./assets/.babelrc') return gulp.src(conf_path) .pipe(gulp.dest('./')) }) // create componetns dir gulp.task('gm:generate-components', ()=>{ // May invalid for windows sh.exec('mkdir '+_opts['components']+_echo_off) }) // init dir and create some meta files gulp.task('gm:generate-lib', ()=>{ let prelib_path = j(__dirname ,'./presetlib/**/*.*') return gulp.src(prelib_path) .pipe(gulp.dest(j(_opts['components'], _opts['lib']))) }) // init dir and create some meta files gulp.task('gm:generate-meta', ()=>{ let meta_path = j(__dirname ,'./meta/**/*.*') return gulp.src(meta_path) .pipe(gulp.dest(_opts['components'])) }) // open demo html file gulp.task('gm:open-demo', ()=>{ sh.exec('open '+j(_opts['runtime_views'], 'home/index.html')+_echo_off) OSInform('Init Succeed', 'Completed') }) // init the proj gulp.task('gm:init', p.sequence( 'gm:clean', 'gm:generate-components', ['gm:generate-meta', 'gm:generate-lib'], // 'gm:generate-config', 'gm:compile', 'gm:open-demo' )) // init the proj gulp.task('gm:install', () => { sh.exec('cd node_modules/gulpman && npm install gulp-sass --save'); sh.exec('npm install babel-preset-es2015 babel-preset-react babel-preset-stage-3 browserify-css --save-dev'); }) /** * FOR karma ut test and coverage ===== */ gulp.task('gm:karma:install', ()=>{ sh.exec('npm install karma karma-browserify karma-coverage karma-jasmine karma-chrome-launcher browserify-istanbul babel-preset-es2015 babel-preset-react babel-preset-stage-3 babelify babel-istanbul watchify stringify --save-dev') sh.cp('./node_modules/gulpman/karma/karma.conf.js', './') }) gulp.task('gm:karma:start', ()=>{ sh.exec('./node_modules/karma/bin/karma start') }); /** * For plugins tasks */ gulp.task('gm:iconfont:install', ()=>{ sh.exec('npm install gulp-iconfont gulp-iconfont-css --save-dev') }) require('./lib/iconFonter').registerTask(gulp, _opts) // API ================================ // config the dir function updateConf(opts){ Object.assign(_opts, opts) initVars() return _opts } exports['config'] = updateConf // return the _opts exports['getConfig'] = function(){ return _opts } exports['util'] = gmutil ================================================ FILE: karma/karma.conf.js ================================================ var stringify = require('stringify'); var ignore_files = '**/lib/**', spec_files = '**/spec/**', tpl_files = '**/*.tpl', node_modules_files = '**/node_modules/**'; var babelOpts = { presets: ['es2015', 'react'], // sourceMap: 'inline', ignore: [node_modules_files, ignore_files, tpl_files] } module.exports = function(config) { config.set({ basePath: '', frameworks: [ 'browserify', 'jasmine' ], files: [ "./components/**/*.es6", ], browsers: ['Chrome'], preprocessors: { "./components/**/*.es6": ['browserify'] }, browserify: { debug: true, paths: ['./components/lib'], transform: [ stringify(['.tpl', '.txt']), ["babelify", babelOpts], ['browserify-istanbul', { instrumenter: require('babel-istanbul'), instrumenterConfig: { // embedSource: true, babel: babelOpts, }, ignore: [ spec_files, tpl_files, node_modules_files, ignore_files ], }] ], extensions: ['.es6', '.jsx', '.js'] }, // logLevel: config.LOG_DEBUG, reporters: ['progress', 'coverage'], coverageReporter: { type : 'html', dir : './coverage' }, // if true, Karma captures browsers, runs the tests and exits singleRun: false }); }; ================================================ FILE: lib/assetsPathParser.js ================================================ /** * For path replace into abs path */ 'use strict' var through = require('through2'), path = require('path'), j = path.join, gmutil = require('./gmutil') /* var ct = ';saasdfasf url()\n\r background: url ( "./img/1.png?_gm_inline&sd=32" ) no-repeat; \n\t; .d{ background-image: url(sss.png?_gm_sprite ) }'*/ var cssUrlReg = /url\s*\(\s*['"]?(.+?)['"]?\s*\)/gm var opts = {} function parseCSS(content, file){ var tList = content.match(cssUrlReg) if(tList){ tList.forEach(t=>{ var url = t.replace(/[\n\r\b\t\s'"]+/gm, '').replace(/^url\(/gm, '').replace(/\)$/gm, '') // 如果是相对路径,那么替换 if(gmutil.isUrl('relative', url) ){ var baseDir = j(opts['cwd'], opts['static_dir']) // gmutil.alert('Base: '+baseDir) var fileRelativeDirOfComponents = path.relative(baseDir, file.path) // var hostFileAbsPath = j() var relativeDir = path.dirname(fileRelativeDirOfComponents) // gmutil.alert('relativeDir: '+relativeDir) var mediaRelPath = j(relativeDir, url) // gmutil.alert('mediaRelPath: '+mediaRelPath) var absUrl = j(opts['url_prefix'], mediaRelPath) // gmutil.alert('absUrl: '+absUrl) var tarStr = 'url('+absUrl+')' content = content.replace(t, tarStr) } }) } return content } function parseTpl(conf, contents, file){ let _opts = conf['_opts'], basepath = conf['basepath'], _isRuntimeDir = conf['_isRuntimeDir'], all_raw_source_reg = conf['all_raw_source_reg'], fdirname = path.dirname(file.relative), _urlPrefix // set assets url prefix if(_opts['is_absolute']) { _urlPrefix = _opts['url_prefix'] }else { // 判断打包资源中的url路径前缀 let _fPath = j(_isRuntimeDir ? _opts['runtime_views'] : _opts['dist_views'], fdirname) let _staticPath = _isRuntimeDir ? _opts['runtime_static'] : _opts['dist_static'] _urlPrefix = path.relative(_fPath, _staticPath) } // 所有格式都要处理 let srcQuoteReg = new RegExp('(?=[\'"]?)([\\w\\.\\-\\?\\-\\/\\:]+?(\\.('+all_raw_source_reg+')))(?=\\?_gm_inline)?(?=[\'"]?)', 'gm') // httpReg = /^http(s)?\:/ let tmp_rs_list = [], rs_list = [] // 提取单标签和双标签 tmp_rs_list = tmp_rs_list .concat(contents.match(gmutil.reg['tagMedia'])) .concat(contents.match(gmutil.reg['closeTagMedia'])) // 首先提取标签,然后从标签中提取href或者src tmp_rs_list.length && ( rs_list = tmp_rs_list .filter(r=>(r && r.match(srcQuoteReg))) .map(v=>v.match(srcQuoteReg)[0]) .filter(r=>{ // remove the http:xxx.com/xx and base64 data url // 只处理相对路径 // 不处理绝对路径、http、dataURL return gmutil.isUrl('relative', r) }) .filter(r=>!r.match(/^(['"]\/)/gm)) ) // 这里利用set做去重 let rs_set = new Set(rs_list), srcPrefix = j(_urlPrefix, fdirname) // 替换url的的path和前缀 rs_set.size && rs_set.forEach(epath=>{ // 对于base64的参数标识要保留,不能清理掉,因为后续要嵌入base64 let innerReg = new RegExp('(?=[\'"]?)('+epath+')(\\?_gm_inline)*(?=[\'"]?)', 'gm') contents = contents.replace(innerReg, j(srcPrefix, epath)+'$2') }) // dealing with usemin build mark syntax // when in publish, not runtime-dir if(!_isRuntimeDir) { // 这里处理usemin 的build的注释内容 contents = gmutil.replaceBuildBlock(contents, srcPrefix) } return contents } function parseJS(conf, contents, file){ let _opts = conf['_opts'], basepath = conf['basepath'], _isRuntimeDir = conf['_isRuntimeDir'], all_raw_source_reg = conf['all_raw_source_reg'], fdirname = path.dirname(file.relative), _urlPrefix // set assets url prefix if(_opts['is_absolute']) { _urlPrefix = _opts['url_prefix'] }else { // 判断打包资源中的url路径前缀 let _fPath = j(_isRuntimeDir ? _opts['runtime_views'] : _opts['dist_views'], fdirname) let _staticPath = _isRuntimeDir ? _opts['runtime_static'] : _opts['dist_static'] _urlPrefix = path.relative(_fPath, _staticPath) } // for all src "xxx.yy" format path let srcQuoteReg = new RegExp('(?=[\'"]?)([\\w\\.\\-\\?\\-\\/\\:]+?(\\.('+all_raw_source_reg+')))(?=\\?_gm_inline)?(?=[\'"]?)', 'gm') // httpReg = /^http(s)?\:/ let tmp_rs_list = [], rs_list = [] // 提取单标签和双标签 tmp_rs_list = tmp_rs_list .concat(contents.match(gmutil.reg['requireAsync'])) .concat(contents.match(gmutil.reg['jsAsyncLoad'])) // 首先提取标签,然后从标签中提取href或者src tmp_rs_list.length && ( rs_list = tmp_rs_list .filter(r=>(r && r.match(srcQuoteReg))) .map(v=>v.match(srcQuoteReg)[0]) .filter(r=>{ // remove the http:xxx.com/xx and base64 data url // 只处理相对路径 // 不处理绝对路径、http、dataURL return gmutil.isUrl('relative', r) }) .filter(r=>!r.match(/^(['"]\/)/gm)) ) // 这里利用set做去重 let rs_set = new Set(rs_list), srcPrefix = j(_urlPrefix, fdirname) // 替换url的的path和前缀 rs_set.size && rs_set.forEach(epath=>{ // 对于base64的参数标识要保留,不能清理掉,因为后续要嵌入base64 let innerReg = new RegExp('(?=[\'"]?)('+epath+')(\\?_gm_inline)*(?=[\'"]?)', 'gm') contents = contents.replace(innerReg, j(srcPrefix, epath)+'$2') }) // dealing with usemin build mark syntax // when in publish, not runtime-dir if(!_isRuntimeDir) { // 这里处理usemin 的build的注释内容 contents = gmutil.replaceBuildBlock(contents, srcPrefix) } return contents } function _absolutizePath(_opts){ opts = Object.assign(opts, _opts) return through.obj(function(file, enc, cb){ if (file.isNull()) { this.push(file); return cb() } if (file.isStream()) { gmutil.error('*PathParser Error: Streaming not supported') return cb() } var fileType = path.extname(file.path).slice(1) if(opts['is_absolute']){ var content = file.contents.toString() if(fileType == 'css'){ var rc = parseCSS(content, file) }else if(fileType == 'tpl'){ var rc = parseTpl(opts, content, file) }else if(fileType == 'js' || fileType == 'es6'){ var rc = parseJS(opts, content, file) }else{ throw Error("Unknown Type: "+fileType) } file.contents = new Buffer(rc) } // gmutil.error(file.base) // gmutil.error(file.relative) // this will dest in right path if(fileType != 'js' && fileType != 'es6') { file.base = opts['cwd'] } this.push(file) return cb() }) } exports.absolutizePath = _absolutizePath ================================================ FILE: lib/base64.js ================================================ /** * FOR BASE 64 UTILS */ var path = require('path'), j = path.join, fs = require('fs'), gutil = require('gulp-util'), through = require('through2') var store = require('./store'), gmutil = require('./gmutil') var bError = null var opts const PLUGIN_NAME = 'Base64' function purifyUrlPrefix(str){ return str.replace(opts['url_prefix'], ''); } function purify(str){ return str.split('?')[0] // return str.replace(/\?_gm_inline/gm, '') } function parseSource(images, file, refType, content, baseDir){ var fileDir = path.dirname(file.relative) var status = true // gmutil.alert('debug: '+fileDir) images.forEach(function(item) { // remove url() in css var imageURL = item .replace(/\(|\)|\'/g, '') .replace(/^url/g, '') // 这里路经计算,需要后续优化 // 现在相对路径计算繁琐了 var pureFilePath; // console.log('item:', item) // // 如果url是相对路径,那么解析 // if(!gmutil.isUrl('relative', imageURL)){ // // imageURL = imageURL.replace(opts['url_prefix'], '') // } if(refType == 'css'){ if(opts['isDevelop']){ file.base = opts['components'] fileDir = path.dirname(file.relative) } pureFilePath = j( file.cwd, baseDir, fileDir, imageURL ) // html or other source }else { var srcPath = purify(j(file.cwd, opts['views'], fileDir, imageURL)) // 输出资源在HMTL是相对路径情况下 if(opts['is_absolute'] === false){ // develop模式下 if(opts['isDevelop']){ pureFilePath = srcPath }else { // publish 模式下 var dist_assets_path = j(file.cwd, opts['dist_assets']), runtime_assets_path = j(file.cwd, baseDir) pureFilePath = srcPath.replace(dist_assets_path, runtime_assets_path) } // 绝对路径情况下,比如/static/home/main.css }else { pureFilePath = j(baseDir, imageURL) } // remove url_prefix pureFilePath = purifyUrlPrefix(pureFilePath) } // 如果url是绝对路径,那么解析 // }else { // } // remove base64 params pureFilePath = purify(pureFilePath) // gmutil.warn('pureFilePath: \n\n\n'+pureFilePath+'\n\n') // check if exist try { var filepath = fs.realpathSync(pureFilePath); }catch(err){ bError = err gmutil.error(err['message']) gmutil.error('\n*Check Your Component: '+fileDir) status = false return false } var extname = purify(path.extname(imageURL).slice(1)) var imageContent = new Buffer(fs.readFileSync(filepath)).toString('base64') content = content.replace( item, 'data:image/' + extname.toLowerCase() + ';base64,' + imageContent ) // generate json file of relevance store.save(filepath, gmutil.convertSource(file.path, refType)) gmutil.log('*Convert to Base64: ' + filepath, 'green') }) if(status) { return content }else { return false } } function toBase64(_opts) { opts = _opts || {} var rule = opts.rule || /url\([^\)]+\)/g var refType = opts.type || 'css', baseDir = opts.baseDir || './' opts['dist_assets'] || (opts['dist_assets'] = '') return through.obj(function (file, enc, cb) { if (file.isNull()) { this.push(file) return cb() } if (file.isStream()) { this.emit('error', new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported')) return cb() } var content = file.contents.toString() var images = content.match(rule) if(images){ content = parseSource(images, file, refType, content, baseDir, this) // 如果出现错误返回了false if(content === false){ var errMes = 'File Not Exist' if(bError){ errMes = bError['message'] } this.emit('error', new gutil.PluginError(PLUGIN_NAME, errMes)) }else { file.contents = new Buffer(content) } } this.push(file) cb() }) } module.exports = toBase64; ================================================ FILE: lib/cdnProxy.js ================================================ /** * FOR CDN PREFIX CONFIG * * FIX gulp-rev-all and revReplace about `prefix` */ /** * Another Proxy code in revReplace.js, * include random url of list and function */ var gmutil = require('./gmutil') function proxyPrefix(obj){ // fix prefix options for gulp-rev-all // 注意: 这了可能会干预到rev-replace里的变量 obj['cdn_prefix'] = obj['cdn_prefix'] || '' obj['_prefix'] = obj['cdn_prefix'] // fix array if(obj['cdn_prefix'] instanceof Array){ // console.log('Array: \n', obj['cdn_prefix']) function _getRandPrefixFromList(){ return obj['_prefix'][gmutil.randomNum(0, obj['_prefix'].length-1)] } // rewrite replace of array obj['cdn_prefix'].replace = function(a, b){ var p = _getRandPrefixFromList().replace(a, b) return p } // rewrite toString of array obj['cdn_prefix'].toString = function(){ return _getRandPrefixFromList() } }else if(obj['cdn_prefix'] instanceof Function){ // !! only for gulp-rev-all obj['transformPath'] = function (rev, source, file) { return obj['_prefix'](source, rev, file)+rev // on the remote server, image files are served from `/images` // return rev.replace('/img', '/images') } }else if(typeof obj['cdn_prefix'] == 'string'){ // no handle // obj['_all_prefix'].add(obj['cdn_prefix']) }else { throw Error('Unknown Type: '+ (typeof obj['cdn_prefix'])) } return obj } exports.proxyPrefix = proxyPrefix ================================================ FILE: lib/gmutil.js ================================================ /** * FOR UTILS */ 'use strict' var colors = require('colors'), path = require('path'), j = path.join function _log (str, color) { str += '' var color = color || 'blue' console.log(str[color]) } function _error (str){ return _log(str, 'red') } function _alert(str) { return _log(str, 'red') } function _tip (str){ return _log(str, 'green') } function _warn (str){ return _log(str, 'yellow') } /** * Returns a random number between min (inclusive) and max (exclusive) */ function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; } /** * Returns a random integer between min (inclusive) and max (inclusive) * Using Math.round() will give you a non-uniform distribution! */ function randomNum(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function byLongestUnreved(a, b) { return b.unreved.length - a.unreved.length; } function pathInAssets(_cwd, fpath, componentsDir, runStaticDir){ var componentsAbsPath = j(_cwd, componentsDir), imgRelPath = fpath.replace(componentsAbsPath, ''), imgAbsPath = j(_cwd, runStaticDir, imgRelPath) return imgAbsPath } function validateObj(obj){ var a for(a in obj){ if(obj.hasOwnProperty(a) && obj[a] === undefined) { delete obj[a] } } return obj } function isArray(o) { return Object.prototype.toString.call(o) === '[object Array]'; } function convertSource(rawSource, refType){ let tarType if(refType == 'css'){ tarType = 'scss' } var repReg = new RegExp('\\.'+refType+'$', 'g'), rsList = [] if(!rawSource.match(repReg)) { return rawSource } if(typeof tarType == 'string'){ return rawSource.replace(repReg, '.'+tarType) }else { return rawSource } } function isUrl(urlType, str){ var _d = { 'absolute': /^\//g, 'http': /^http(s)?\:/g, 'dataURL': /^data\:/g, } var t = _d[urlType] if(urlType == 'relative'){ return !isUrl('absolute', str) && !isUrl('http', str) && !isUrl('dataURL', str) } if(!t){ throw Error('Unknow Type: '+t) } return str.match(_d[urlType]) } function joinUrl (a, b){ if(!b.match(/\/$/g)) { b = b + '/' } if(!a.match(/\/$/g) && !b.match(/^\//g)) { return a + '/' + b; }else if(a.match(/\/$/g) && b.match(/^\//g)){ return a.replace(/\/$/g, '') + b; }else{ return a + b; } } function replaceBuildBlock(content, srcPrefix) { var startReg = //gim; var endReg = //gim; var sections = content.split(endReg) sections.forEach((e, i)=>{ var block if( (block = e.match(startReg)) && (block = block[0])){ var section = e.split(startReg) // var block = e.match(startReg)[0] var outputPathParam = section[4]; if(!outputPathParam) { // not set output path in usemin, build:js/css var srcStr = section[5] var doExec = true var comboNameList = [] var comboExtFileName while(doExec) { let oneFile = _reg['sourceUrl'].exec(srcStr) let ofname if(oneFile && (ofname = oneFile[2])){ let oneFileName = path.basename(ofname); let extFileName = path.extname(ofname) if(!comboExtFileName) { comboExtFileName = extFileName } comboNameList.push(oneFileName.replace(extFileName, '')) }else { doExec = false } } if(!comboExtFileName) { comboExtFileName = '.unknown' _warn('*Found Unknown Extname, check your assets files!') } // add 80 as max combo name length var comboNameStr = comboNameList.join('_').slice(0, 80) + comboExtFileName var outputPathParam = comboNameStr.split('?')[0] _warn('*Not set build file name, use combo name: ' + outputPathParam) // _error(outputPathParam) } var newOutPath = j(srcPrefix, outputPathParam) // _alert('Usemin Build: '+newOutPath) // section[2]: alternative search path // section[3]: nameInHTML: section[3] // section[4]: relative out path content = content.replace(block, '') } }) return content } // source reg var _reg = { link: new RegExp('[\\s\\S]*?<*\\/*>*', 'gi'), img: new RegExp('[\\s\\S]*?<*\\/*>*', 'gi'), href: new RegExp('\\s*(href)=["\']+([\\s\\S]*?)["\']'), style:new RegExp('[\\s\\S]*?<\\/style>', 'gi'), script: new RegExp('[\\s\\S]*?<\\/script>', 'gi'), src: new RegExp('\\s*(src)=["\']+([\\s\\S]*?)["\']'), sourceUrl: new RegExp('\\s*(src|href)=["\']+([\\s\\S]*?)["\']', 'gi'), jsAsyncLoad: new RegExp('\\s*(\\.script\\()["\']+([\\s\\S]*?)["\']\\)', 'gi'), requireAsync: new RegExp('\\s*(require\\.async\\()["\']+([\\s\\S]*?)["\']\\)', 'gi'), tagMedia: new RegExp('<(img|link|source|input)\\s+[\\s\\S]*?>[\\s\\S]*?<*\\/*>*', 'gi'), closeTagMedia: new RegExp('<(script|iframe|frame|audio|video|object)\\s*[\\s\\S]*?>[\\s\\S]*?<\\/(script|iframe|frame|audio|video|object)>', 'gi'), useminBuild: new RegExp('<\\!\\-\\-\\s+build\\:\\w+\\s+([\\w\\.\\/\\-\\?\\=&]+)\\s+\\-\\->', 'gm') } // log exports.log = _log exports.error = _error exports.alert = _alert exports.tip = _tip exports.warn = _warn exports.reg = _reg // for rev replace exports.byLongestUnreved = byLongestUnreved exports.joinUrl = joinUrl // utils exports.randomNum = randomNum exports.isArray = isArray exports.pathInAssets = pathInAssets exports.validateObj = validateObj exports.convertSource = convertSource // for usemin build exports.replaceBuildBlock = replaceBuildBlock exports.isUrl = isUrl ================================================ FILE: lib/gulp-usemin/.npmignore ================================================ /node_modules /*.log .idea/ *~ ================================================ FILE: lib/gulp-usemin/.travis.yml ================================================ language: node_js node_js: - "4.0" before_script: - npm install ================================================ FILE: lib/gulp-usemin/LICENSE ================================================ The MIT License (MIT) Copyright (c) 2014 Alexander Zonov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: lib/gulp-usemin/README.md ================================================ [![Build Status](https://travis-ci.org/zont/gulp-usemin.svg?branch=master)](https://travis-ci.org/zont/gulp-usemin) # gulp-usemin > Replaces references to non-optimized scripts or stylesheets into a set of HTML files (or any templates/views). This task is designed for gulp >= 3 and node >= 4.0. > Attention: v0.3.0 options is not compatible with v0.2.0. ## Usage First, install `gulp-usemin` as a development dependency: ```shell npm install --save-dev gulp-usemin ``` Then, add it to your `gulpfile.js`: ```javascript var usemin = require('gulp-usemin'); var uglify = require('gulp-uglify'); var minifyHtml = require('gulp-minify-html'); var minifyCss = require('gulp-minify-css'); var rev = require('gulp-rev'); gulp.task('usemin', function() { return gulp.src('./*.html') .pipe(usemin({ css: [ rev() ], html: [ minifyHtml({ empty: true }) ], js: [ uglify(), rev() ], inlinejs: [ uglify() ], inlinecss: [ minifyCss(), 'concat' ] })) .pipe(gulp.dest('build/')); }); ``` If you need to call the same pipeline twice, you need to define each task as a function that returns the stream object that should be used. ```javascript gulp.task('usemin', function() { return gulp.src('./*.html') .pipe(usemin({ css: [ rev ], html: [ function () {return minifyHtml({ empty: true });} ], js: [ uglify, rev ], inlinejs: [ uglify ], inlinecss: [ minifyCss, 'concat' ] })) .pipe(gulp.dest('build/')); }); ``` ## API ### Blocks Blocks are expressed as: ```html ... HTML Markup, list of script / link tags. ``` - **pipelineId**: pipeline id for options or *remove* to remove a section - **alternate search path**: (optional) By default the input files are relative to the treated file. Alternate search path allows one to change that - **path**: the file path of the optimized file, the target output An example of this in completed form can be seen below: ```html ``` ### Options #### assetsDir Type: `String` Alternate root path for assets. New concated js and css files will be written to the path specified in the build block, relative to this path. Currently asset files are also returned in the stream. #### path Type: `String` Default alternate search path for files. Can be overridden by the alternate search path option for a given block. #### any pipelineId Type: `Array` If exist used for modify files. If does not contain string 'concat', then it added as first member of pipeline #### outputRelativePath Type: `String` Relative location to html file for new concatenated js and css. #### enableHtmlComment Type: `Boolean` Keep HTML comment when processing #### jsAttributes Type: `Object` Attach HTML attributes to the output js file. For Example : ```js gulp.task('usemin', function() { return gulp.src('./index.html') .pipe(usemin({ html: [], jsAttributes : { async : true, lorem : 'ipsum', seq : [1, 2, 1] }, js: [ ], js1:[ ], js2:[ ] })) .pipe(gulp.dest('./')); }); ``` Will give you : ```html ``` As your built script tag. ## Use case ``` | +- app | +- index.html | +- assets | +- js | +- foo.js | +- bar.js | +- css | +- clear.css | +- main.css +- dist ``` We want to optimize `foo.js` and `bar.js` into `optimized.js`, referenced using relative path. `index.html` should contain the following block: ``` ``` We want our files to be generated in the `dist` directory. `gulpfile.js` should contain the following block: ```javascript gulp.task('usemin', function () { return gulp.src('./app/index.html') .pipe(usemin({ js: [uglify()] // in this case css will be only concatenated (like css: ['concat']). })) .pipe(gulp.dest('dist/')); }); ``` This will generate the following output: ``` | +- app | +- index.html | +- assets | +- js | +- foo.js | +- bar.js +- dist | +- index.html | +- js | +- optimized.js | +- style.css ``` `index.html` output: ``` ``` ## Changelog #####0.3.23 - Added support array value for cssAttributes (by MillerRen) #####0.3.22 - Added html import support (by linfaxin) #####0.3.21 - Added support paths with querystring or hash (by Lanfei) #####0.3.20 - Added support array value for jsAttributes (by kuitos) #####0.3.18 - Fixed relative path for script in subfolder bug #####0.3.17 - Fixed block output when stream returns multiple files (by maksidom) #####0.3.16 - Added feature to assign attributes to js script tags (by sohamkamani) #####0.3.15 - Allow proper html output when blocks are empty (by ppowalowski) #####0.3.14 - fixed #91 #####0.3.13 - works fine only with gulp-foreach #####0.3.12 - fixed #121. Depending on the node >= 0.12. #####0.3.11 - fixed #88 #####0.3.10 - fixed uppercase Q bug (on case-sensetive file systems) #####0.3.9 - async tasks support #####0.3.8 - allow removal option (by tejohnso) - added support for single quotes (by adicirstei) #####0.3.7 - ouputRelativePath renamed outputRelativePath #####0.3.6 - ouputRelativePath option (by bhstahl) #####0.3.5 - Support for conditional comments inside build blocks (by simplydenis) #####0.3.4 - When a file does not exist an error containing the missing path is thrown #####0.3.3 - fixed dependencies - Add support for multiple alternative paths (by peleteiro) #####0.3.2 - fixed assetsDir option (by rovjuvano) #####0.3.1 - fixed fails to create source map files by uglify({outSourceMap: true}) #####0.3.0 - new version of options #####0.2.3 - fixed html minify bug #####0.2.2 - allow gulp-usemin to work with minified source HTML (by CWSpear) - fixed alternate path bug (by CWSpear) - add assetsDir option (by pursual) - add rev option (by pursual) #####0.2.1 - fixed subfolders bug #####0.2.0 - no minification by default. New options API #####0.1.4 - add alternate search path support #####0.1.3 - add support for absolute URLs (by vasa-chi) #####0.1.1 - fixed aggressive replace comments #####0.1.0 - fixed some bugs. Add tests. #####0.0.2 - add minification by default #####0.0.1 - initial release ================================================ FILE: lib/gulp-usemin/gulpfile.js ================================================ /* jshint node:true */ 'use strict'; var gulp = require('gulp'); var jshint = require('gulp-jshint'); var mocha = require('gulp-mocha'); gulp.task('lint', function() { return gulp.src('test/main.js') .pipe(jshint()) .pipe(jshint.reporter('default')) .pipe(mocha()); }); gulp.task('default', ['lint']); ================================================ FILE: lib/gulp-usemin/index.js ================================================ module.exports = function(options) { var through = require('through2'); var gutil = require('gulp-util'); var blocksBuilder = require('./lib/blocksBuilder.js'); var htmlBuilder = require('./lib/htmlBuilder.js'); return through.obj(function(file, enc, callback) { if (file.isStream()) { this.emit('error', new gutil.PluginError('gulp-usemin', 'Streams are not supported!')); callback(); } else if (file.isNull()) callback(null, file); // Do nothing if no contents else { try { var blocks = blocksBuilder(file, options); htmlBuilder(file, blocks, options, this.push.bind(this), callback); } catch(e) { this.emit('error', e); callback(); } } }); }; ================================================ FILE: lib/gulp-usemin/lib/blocksBuilder.js ================================================ var fs = require('fs'); var glob = require('globby'); var path = require('path'); var gutil = require('gulp-util'); module.exports = function(file, options) { options = options || {}; var startReg = //gim; var endReg = //gim; var jsReg = /<\s*script\s+.*?src\s*=\s*['"]?([^'"?# ]+).*?><\s*\/\s*script\s*>/gi; var cssReg = /<\s*link\s+.*?href\s*=\s*['"]?([^'"?# ]+).*?>/gi; var cssMediaReg = /<\s*link\s+.*?media\s*=\s*['"]?([^'" ]+).*?>/gi; var startCondReg = //gim; var basePath = file.base; var mainPath = path.dirname(file.path); var outputPath = options.outputRelativePath || ''; var content = String(file.contents); var sections = content.split(endReg); var blocks = []; var cssMediaQuery = null; function getFiles(content, reg, alternatePath) { var paths = []; var files = []; cssMediaQuery = null; content .replace(startCondReg, '') .replace(endCondReg, '') .replace(//gim, function (a) { return options.enableHtmlComment ? a : ''; }) .replace(reg, function (a, b) { var tmpfileRelPath = b.replace(/^'|^"/, '').replace(/'$/, '').replace(/"$/, ''); if(options['url_prefix']){ var fileRelativePath = path.relative(options['url_prefix'], tmpfileRelPath); }else { var fileRelativePath = tmpfileRelPath; } var filePath = path.resolve(path.join( alternatePath || options.path || mainPath, fileRelativePath )); if (options.assetsDir) filePath = path.resolve(path.join(options.assetsDir, path.relative(basePath, filePath))); paths.push(filePath); }); if (reg === cssReg) { content.replace(cssMediaReg, function(a, media) { media = media.replace(/^'|^"/, '').replace(/'$/, '').replace(/"$/, ''); if (!cssMediaQuery) { cssMediaQuery = media; } else { if (cssMediaQuery != media) throw new gutil.PluginError('gulp-usemin', 'incompatible css media query for ' + a + ' detected.'); } }); } for (var i = 0, l = paths.length; i < l; ++i) { var filepaths = glob.sync(paths[i]); if(filepaths[0] === undefined) { throw new gutil.PluginError('gulp-usemin', 'Path ' + paths[i] + ' not found!'); } filepaths.forEach(function (filepath) { files.push(new gutil.File({ path: filepath, contents: fs.readFileSync(filepath) })); }); } return files; } for (var i = 0, l = sections.length; i < l; ++i) { if (sections[i].match(startReg)) { var section = sections[i].split(startReg); blocks.push(section[0]); var startCondLine = section[5].match(startCondReg); var endCondLine = section[5].match(endCondReg); if (startCondLine && endCondLine) blocks.push(startCondLine[0]); if (section[1] !== 'remove') { if(section[1] === 'htmlimport'){ blocks.push({ type: 'htmlimport', nameInHTML: section[3], name: path.join(outputPath || path.relative(basePath, mainPath), section[4]), files: getFiles(section[5], cssReg, section[2]), tasks: options[section[1]] }); }else if (jsReg.test(section[5])) { if (section[1].indexOf('inline') !== -1) { blocks.push({ type: 'inlinejs', files: getFiles(section[5], jsReg, section[2]), tasks: options[section[1]] }); } else { blocks.push({ type: 'js', nameInHTML: section[3], name: path.join(outputPath || path.relative(basePath, mainPath), section[4]), files: getFiles(section[5], jsReg, section[2]), tasks: options[section[1]] }); } } else { if (section[1].indexOf('inline') !== -1) { blocks.push({ type: 'inlinecss', files: getFiles(section[5], cssReg, section[2]), tasks: options[section[1]], mediaQuery: cssMediaQuery }); } else { blocks.push({ type: 'css', nameInHTML: section[3], name: path.join(outputPath || path.relative(basePath, mainPath), section[4]), files: getFiles(section[5], cssReg, section[2]), tasks: options[section[1]], mediaQuery: cssMediaQuery }); } } } if (startCondLine && endCondLine) blocks.push(endCondLine[0]); } else blocks.push(sections[i]); } return blocks; }; ================================================ FILE: lib/gulp-usemin/lib/htmlBuilder.js ================================================ module.exports = function(file, blocks, options, push, callback) { var path = require('path'); var gutil = require('gulp-util'); var pipeline = require('./pipeline.js'); var basePath = file.base; var name = path.basename(file.path); var mainPath = path.dirname(file.path); function createFile(name, content) { var filePath = path.join(path.relative(basePath, mainPath), name); return new gutil.File({ path: filePath, contents: new Buffer(content) }) } function createHTMLAttributes(attributes, index){ if(!attributes){ return ''; } var attrArray = []; Object.keys(attributes).forEach(function (attribute) { var attributeValue = attributes[attribute]; if (attributeValue === true) { attrArray.push(attribute); return; } if (attributeValue === false) { return; } if (Array.isArray(attributeValue)) { attrArray.push(attribute + '="' + attributeValue[index] + '"'); } else { attrArray.push(attribute + '="' + attributeValue + '"'); } }); return ' ' + attrArray.join(' '); } // fix for revReplace url, if not fix then get: /http://s.cdn.com/public/a/b.js function _fixUrlForRevReplace(str){ return str; // return str ? str.replace(/^\//g, '') : str; } function _fixFilePath(name, file){ var realRelativeFilePath = '/' + path.relative(options['url_prefix'], name); file.path = file.path.replace(name, realRelativeFilePath); return file; } var html = []; var jsCounter = 0; var cssCounter = 0; var promises = blocks.map(function(block, i) { return new Promise(function(resolve) { html[i] = ''; if (typeof block == 'string') { html[i] = block; resolve(); } else if (block.files.length == 0){ resolve(); } else if (block.type == 'js') { pipeline(block.name, block.files, block.tasks, function(name, file) { _fixFilePath(name, file); push(file); var jsAttributes = options ? options.jsAttributes : null; if (path.extname(file.path) == '.js') html[i] += ''; resolve(); }.bind(this, block.nameInHTML)); } else if (block.type == 'css') { pipeline(block.name, block.files, block.tasks, function(name, file) { _fixFilePath(name, file); push(file); var cssAttributes = options ? options.cssAttributes : null; html[i] += ''; resolve(); }.bind(this, block.nameInHTML)); } else if (block.type == 'inlinejs') { pipeline(block.name, block.files, block.tasks, function(file) { html[i] = ''; resolve(); }.bind(this)); } else if (block.type == 'inlinecss') { pipeline(block.name, block.files, block.tasks, function(file) { html[i] = '' + String(file.contents) + ''; resolve(); }.bind(this)); } else if (block.type == 'htmlimport') { pipeline(block.name, block.files, block.tasks, function(name, file) { _fixFilePath(name, file); push(file); html[i] += ''; resolve(); }.bind(this, block.nameInHTML)); } }); }); Promise.all(promises).then(function() { var createdFile = createFile(name, html.join('')); pipeline(createdFile.path, [createdFile], options && options['html'], function(file) { callback(null, file); }); }); }; ================================================ FILE: lib/gulp-usemin/lib/pipeline.js ================================================ module.exports = function(name, files, tasks, push) { var through = require('through2'); var concat = require('gulp-concat')(name || 'filename.temp', {newLine: '\n'}); /* PREPARE TASKS */ tasks = (tasks || []).slice(); var concatIndex = tasks.indexOf('concat'); if (concatIndex == -1) tasks.unshift(concat); else tasks[concatIndex] = concat; tasks.push(through.obj(function(file, enc, streamCallback) { streamCallback(null, file); push(file); })); /* PREPARE TASKS END */ var stream = through.obj(function(file, enc, streamCallback) { streamCallback(null, file); }); var newStream = stream; tasks.forEach(function(task) { newStream = newStream.pipe(typeof(task) == 'function' ? task(): task); }); files.forEach(stream.write.bind(stream)); stream.end(); }; ================================================ FILE: lib/gulp-usemin/package.json ================================================ { "name": "gulp-usemin", "version": "0.3.23", "description": "Replaces references to non-optimized scripts or stylesheets into a set of HTML files (or any templates/views).", "main": "index.js", "dependencies": { "gulp-util": "~2.2.14", "through2": "~0.5.1", "glob": "~4.0.4", "gulp-concat": "~2.4.1" }, "devDependencies": { "event-stream": "~3.1.0", "vinyl-fs": "~2.3.1", "gulp": "~3.8.6", "gulp-jshint": "~1.7.0", "gulp-mocha": "~0.5.1", "gulp-uglify": "~0.3.1", "gulp-minify-html": "~0.1.1", "gulp-minify-css": "~0.3.0", "gulp-rev": "~0.4.2", "gulp-less": "2.0.1" }, "scripts": { "test": "gulp" }, "repository": { "type": "git", "url": "git://github.com/zont/gulp-usemin.git" }, "keywords": [ "gulpplugin", "usemin", "gulp-usemin" ], "author": { "name": "Alexander Zonov", "email": "zont@pochta.ru" }, "license": "MIT", "bugs": { "url": "https://github.com/zont/gulp-usemin/issues" }, "engines": { "node": ">=0.12" }, "gitHead": "81bff9fd6d46f9fbedea53e349001d0fa7bcb49c", "homepage": "https://github.com/zont/gulp-usemin#readme", "_id": "gulp-usemin@0.3.23", "_shasum": "9f451546e4ac53a00119c7343d36c42d6a5ce6f0", "_from": "gulp-usemin@>=0.3.21 <0.4.0", "_resolved": "https://registry.npm.taobao.org/gulp-usemin/download/gulp-usemin-0.3.23.tgz", "_npmVersion": "3.3.10", "_nodeVersion": "5.0.0", "_npmUser": { "name": "alexander.zonov", "email": "zont@pochta.ru" }, "dist": { "shasum": "9f451546e4ac53a00119c7343d36c42d6a5ce6f0", "size": 12939, "noattachment": false, "tarball": "http://registry.npm.taobao.org/gulp-usemin/download/gulp-usemin-0.3.23.tgz" }, "maintainers": [ { "name": "alexander.zonov", "email": "zont@pochta.ru" } ], "_npmOperationalInternal": { "host": "packages-16-east.internal.npmjs.com", "tmp": "tmp/gulp-usemin-0.3.23.tgz_1462364006265_0.13037881650961936" }, "directories": {}, "publish_time": 1462364007542, "_cnpm_publish_time": 1462364007542 } ================================================ FILE: lib/gulp-usemin/test/expected/app.js ================================================ var sample = 111; console.log(sample); ================================================ FILE: lib/gulp-usemin/test/expected/array-js-attributes.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/build-remove-no-trailing-whitespace.html ================================================
================================================ FILE: lib/gulp-usemin/test/expected/complex-path.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/complex.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/conditional-complex.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/conditional-css.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/conditional-inline-css.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/conditional-inline-js.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/conditional-js.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/data/css/min-style.css ================================================ *{margin:0;padding:0}body{margin:10px} ================================================ FILE: lib/gulp-usemin/test/expected/data/css/style.css ================================================ * { margin: 0; padding: 0; } body { margin: 10px; } ================================================ FILE: lib/gulp-usemin/test/expected/data/js/app.js ================================================ var sample = 111; console.log(sample); ================================================ FILE: lib/gulp-usemin/test/expected/data/js/app_min_concat.js ================================================ var sample=111; console.log(sample); ================================================ FILE: lib/gulp-usemin/test/expected/data/js/min-app.js ================================================ var sample=111;console.log(sample); ================================================ FILE: lib/gulp-usemin/test/expected/glob-inline-css.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/glob-inline-js.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/many-blocks-removal.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/min-app.js ================================================ var sample=111;console.log(sample); ================================================ FILE: lib/gulp-usemin/test/expected/min-complex-path.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/min-complex.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/min-css-with-media-query.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/min-html-simple-css.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/min-html-simple-js.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/min-html-simple-removal.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/min-paths-with-querystring.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/min-simple-css-path.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/min-simple-css.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/min-simple-js-path.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/min-simple-js.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/min-style.css ================================================ *{margin:0;padding:0}body{margin:10px} ================================================ FILE: lib/gulp-usemin/test/expected/multiple-alternative-paths.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/multiple-files.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/paths-with-querystring.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/simple-css-path.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/simple-css.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/simple-inline-css.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/simple-inline-js.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/simple-js-path.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/simple-js-removal.html ================================================
================================================ FILE: lib/gulp-usemin/test/expected/simple-js.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/single-quotes-css.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/single-quotes-inline-css.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/single-quotes-inline-js.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/single-quotes-js.html ================================================ ================================================ FILE: lib/gulp-usemin/test/expected/style.css ================================================ * { margin: 0; padding: 0; } body { margin: 10px; } ================================================ FILE: lib/gulp-usemin/test/expected/subfolder/app.js ================================================ console.log(sample); ================================================ FILE: lib/gulp-usemin/test/expected/subfolder/index.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/alternative/js/util.js ================================================ alert(1); ================================================ FILE: lib/gulp-usemin/test/fixtures/array-js-attributes.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/async-less.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/build-remove-no-trailing-whitespace.html ================================================

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

================================================ FILE: lib/gulp-usemin/test/fixtures/comment-js.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/complex-path.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/complex.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/conditional-complex.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/conditional-css.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/conditional-inline-css.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/conditional-inline-js.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/conditional-js.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/css/clear.css ================================================ * { margin: 0; padding: 0; } ================================================ FILE: lib/gulp-usemin/test/fixtures/css/main.css ================================================ body { margin: 10px; } ================================================ FILE: lib/gulp-usemin/test/fixtures/css-with-media-query-error.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/css-with-media-query.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/glob-css.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/glob-inline-css.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/glob-inline-js.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/glob-js.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/js/lib.js ================================================ var sample = 111; ================================================ FILE: lib/gulp-usemin/test/fixtures/js/main.js ================================================ console.log(sample); ================================================ FILE: lib/gulp-usemin/test/fixtures/js2/lib2.js ================================================ var sample = 111; ================================================ FILE: lib/gulp-usemin/test/fixtures/js2/main2.js ================================================ console.log(sample); ================================================ FILE: lib/gulp-usemin/test/fixtures/less/clear.less ================================================ @zero: 0; * { margin: @zero; padding: @zero; } ================================================ FILE: lib/gulp-usemin/test/fixtures/less/main.less ================================================ body { margin: 10px; } ================================================ FILE: lib/gulp-usemin/test/fixtures/many-blocks-removal.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/many-blocks.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/min-html-simple-css.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/min-html-simple-js.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/min-html-simple-removal.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/multiple-alternative-paths-inline.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/multiple-alternative-paths.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/multiple-files.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/paths-with-querystring.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/simple-css-alternate-path.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/simple-css-path.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/simple-css.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/simple-inline-css.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/simple-inline-js.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/simple-js-alternate-path.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/simple-js-path.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/simple-js-removal.html ================================================
================================================ FILE: lib/gulp-usemin/test/fixtures/simple-js.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/single-quotes-css.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/single-quotes-inline-css.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/single-quotes-inline-js.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/single-quotes-js.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/subfolder/index.html ================================================ ================================================ FILE: lib/gulp-usemin/test/fixtures/subfolder/script.js ================================================ console.log(sample); ================================================ FILE: lib/gulp-usemin/test/main.js ================================================ /* jshint node: true */ /* global describe, it */ 'use strict'; var assert = require('assert'); var fs = require('fs'); var gutil = require('gulp-util'); var PassThrough = require('stream').PassThrough; var path = require('path'); var usemin = require('../index'); var vfs = require('vinyl-fs'); function getFile(filePath) { return new gutil.File({ path: filePath, base: path.dirname(filePath), contents: fs.readFileSync(filePath) }); } function getFixture(filePath) { return getFile(path.join('test', 'fixtures', filePath)); } function getExpected(filePath) { return getFile(path.join('test', 'expected', filePath)); } describe('gulp-usemin', function() { describe('allow removal sections', function() { function compare(name, expectedName, done) { var htmlmin = require('gulp-minify-html'); var stream = usemin({html: [htmlmin({empty: true, quotes: true})]}); stream.on('data', function(newFile) { if (path.basename(newFile.path) === name) { assert.equal(String(getExpected(expectedName).contents), String(newFile.contents)); done(); } }); stream.write(getFixture(name)); } it('simple js block', function(done) { compare('simple-js-removal.html', 'simple-js-removal.html', done); }); it('minified js block', function(done) { compare('min-html-simple-removal.html', 'min-html-simple-removal.html', done); }); it('many blocks', function(done) { compare('many-blocks-removal.html', 'many-blocks-removal.html', done); }); it('robust pattern recognition (no whitespace after build:remove)', function(done) { compare('build-remove-no-trailing-whitespace.html', 'build-remove-no-trailing-whitespace.html', done); }); }); describe('negative test:', function() { it('shouldn\'t work in stream mode', function(done) { var stream = usemin(); var t; var fakeStream = new PassThrough(); var fakeFile = new gutil.File({ contents: fakeStream }); fakeStream.end(); stream.on('error', function() { clearTimeout(t); done(); }); t = setTimeout(function() { assert.fail('', '', 'Should throw error', ''); done(); }, 1000); stream.write(fakeFile); }); it('html without blocks', function(done) { var stream = usemin(); var content = '
content
'; var fakeFile = new gutil.File({ path: 'test.file', contents: new Buffer(content) }); stream.on('data', function(newFile) { assert.equal(content, String(newFile.contents)); done(); }); stream.write(fakeFile); }); }); describe('should work in buffer mode with', function() { describe('minified HTML:', function() { function compare(name, expectedName, done, fail) { var htmlmin = require('gulp-minify-html'); var stream = usemin({ html: [function() { return htmlmin({empty: true}); }] }); stream.on('data', function(newFile) { if (path.basename(newFile.path) === name) { assert.equal(String(getExpected(expectedName).contents), String(newFile.contents)); done(); } }); stream.on('error', function() { if (fail) fail(); }); stream.write(getFixture(name)); } it('simple js block', function(done) { compare('simple-js.html', 'min-simple-js.html', done); }); it('simple js block with path', function(done) { compare('simple-js-path.html', 'min-simple-js-path.html', done); }); it('simple css block', function(done) { compare('simple-css.html', 'min-simple-css.html', done); }); it('css block with media query', function(done) { compare('css-with-media-query.html', 'min-css-with-media-query.html', done); }); it('css block with mixed incompatible media queries should error', function(done) { compare('css-with-media-query-error.html', 'min-css-with-media-query.html', function() { assert.fail('', '', 'should error', ''); done(); }, done); }); it('simple css block with path', function(done) { compare('simple-css-path.html', 'min-simple-css-path.html', done); }); it('complex (css + js)', function(done) { compare('complex.html', 'min-complex.html', done); }); it('complex with path (css + js)', function(done) { compare('complex-path.html', 'min-complex-path.html', done); }); it('paths with querystring', function(done) { compare('paths-with-querystring.html', 'min-paths-with-querystring.html', done); }); }); describe('not minified HTML:', function() { function compare(name, expectedName, done) { var stream = usemin(); stream.on('data', function(newFile) { if (path.basename(newFile.path) === name) { assert.equal(String(getExpected(expectedName).contents), String(newFile.contents)); done(); } }); stream.write(getFixture(name)); } it('simple js block with single quotes', function (done) { compare('single-quotes-js.html', 'single-quotes-js.html', done); }); it('simple css block with single quotes', function (done) { compare('single-quotes-css.html', 'single-quotes-css.html', done); }); it('simple (js block)', function(done) { compare('simple-js.html', 'simple-js.html', done); }); it('simple (js block) (html minified)', function(done) { compare('min-html-simple-js.html', 'min-html-simple-js.html', done); }); it('simple with path (js block)', function(done) { compare('simple-js-path.html', 'simple-js-path.html', done); }); it('simple (css block)', function(done) { compare('simple-css.html', 'simple-css.html', done); }); it('simple (css block) (html minified)', function(done) { compare('min-html-simple-css.html', 'min-html-simple-css.html', done); }); it('simple with path (css block)', function(done) { compare('simple-css-path.html', 'simple-css-path.html', done); }); it('complex (css + js)', function(done) { compare('complex.html', 'complex.html', done); }); it('complex with path (css + js)', function(done) { compare('complex-path.html', 'complex-path.html', done); }); it('multiple alternative paths', function(done) { compare('multiple-alternative-paths.html', 'multiple-alternative-paths.html', done); }); it('paths with querystring', function(done) { compare('paths-with-querystring.html', 'paths-with-querystring.html', done); }); }); describe('minified CSS:', function() { function compare(fixtureName, name, expectedName, end) { var cssmin = require('gulp-minify-css'); var stream = usemin({css: ['concat', cssmin()]}); stream.on('data', function(newFile) { if (path.basename(newFile.path) === name) { assert.equal(String(getExpected(expectedName).contents), String(newFile.contents)); end(); } }); stream.write(getFixture(fixtureName)); } it('simple (css block)', function(done) { var name = 'style.css'; var expectedName = 'min-style.css'; compare('simple-css.html', name, expectedName, done); }); it('simple with path (css block)', function(done) { var name = 'style.css'; var expectedName = path.join('data', 'css', 'min-style.css'); compare('simple-css-path.html', name, expectedName, done); }); it('simple with alternate path (css block)', function(done) { var name = 'style.css'; var expectedName = path.join('data', 'css', 'min-style.css'); compare('simple-css-alternate-path.html', name, expectedName, done); }); }); describe('not minified CSS:', function() { function compare(fixtureName, expectedName, end) { var stream = usemin(); stream.on('data', function(newFile) { if (path.basename(newFile.path) === path.basename(expectedName)) { assert.equal(String(getExpected(expectedName).contents), String(newFile.contents)); end(); } }); stream.write(getFixture(fixtureName)); } it('simple (css block)', function(done) { compare('simple-css.html', 'style.css', done); }); it('simple (css block) (minified html)', function(done) { compare('min-html-simple-css.html', 'style.css', done); }); it('simple with path (css block)', function(done) { compare('simple-css-path.html', path.join('data', 'css', 'style.css'), done); }); it('simple with alternate path (css block)', function(done) { compare('simple-css-alternate-path.html', path.join('data', 'css', 'style.css'), done); }); }); describe('minified JS:', function() { function compare(fixtureName, name, expectedName, end) { var jsmin = require('gulp-uglify'); var stream = usemin({js: [jsmin()]}); stream.on('data', function(newFile) { if (path.basename(newFile.path) === path.basename(name)) { assert.equal(String(getExpected(expectedName).contents), String(newFile.contents)); end(); } }); stream.write(getFixture(fixtureName)); } it('simple (js block)', function(done) { compare('simple-js.html', 'app.js', 'min-app.js', done); }); it('simple with path (js block)', function(done) { var name = path.join('data', 'js', 'app.js'); var expectedName = path.join('data', 'js', 'min-app.js'); compare('simple-js-path.html', name, expectedName, done); }); it('simple with alternate path (js block)', function(done) { var name = path.join('data', 'js', 'app.js'); var expectedName = path.join('data', 'js', 'min-app.js'); compare('simple-js-alternate-path.html', name, expectedName, done); }); }); describe('not minified JS:', function() { function compare(fixtureName, expectedName, end) { var stream = usemin(); stream.on('data', function(newFile) { if (path.basename(newFile.path) === path.basename(expectedName)) { assert.equal(String(getExpected(expectedName).contents), String(newFile.contents)); end(); } }); stream.write(getFixture(fixtureName)); } it('simple (js block)', function(done) { compare('simple-js.html', 'app.js', done); }); it('simple (js block) (minified html)', function(done) { compare('min-html-simple-js.html', 'app.js', done); }); it('simple with path (js block)', function(done) { compare('simple-js-path.html', path.join('data', 'js', 'app.js'), done); }); it('simple with alternate path (js block)', function(done) { compare('simple-js-alternate-path.html', path.join('data', 'js', 'app.js'), done); }); }); it('many html files', function(done) { var cssmin = require('gulp-minify-css'); var jsmin = require('gulp-uglify'); var rev = require('gulp-rev'); var stream = usemin({ css: ['concat', cssmin], js: ['concat', jsmin] }); var nameCss = 'style.css'; var expectedNameCss = 'min-style.css'; var nameJs = 'app.js'; var expectedNameJs = 'min-app.js'; var cssExist = false; var jsExist = false; var htmlCount = 0; stream.on('data', function(newFile) { if (path.basename(newFile.path) === path.basename(nameCss)) { cssExist = true; assert.equal(String(getExpected(expectedNameCss).contents), String(newFile.contents)); } else if (path.basename(newFile.path) === path.basename(nameJs)) { jsExist = true; assert.equal(String(getExpected(expectedNameJs).contents), String(newFile.contents)); } else { htmlCount += 1; } }); stream.on('end', function() { assert.equal(htmlCount, 2); assert.ok(cssExist); assert.ok(jsExist); done(); }); stream.write(getFixture('simple-css.html')); stream.write(getFixture('simple-js.html')); stream.end(); }); it('many blocks', function(done) { var cssmin = require('gulp-minify-css'); var jsmin = require('gulp-uglify'); var rev = require('gulp-rev'); var stream = usemin({ css1: ['concat', cssmin], js1: [jsmin, 'concat', rev] }); var nameCss = path.join('data', 'css', 'style.css'); var expectedNameCss = path.join('data', 'css', 'min-style.css'); var nameJs = path.join('data', 'js', 'app.js'); var expectedNameJs = path.join('data', 'js', 'app.js'); var nameJs1 = 'app1'; var expectedNameJs1 = path.join('data', 'js', 'app_min_concat.js'); var nameJs2 = 'app2'; var expectedNameJs2 = path.join('data', 'js', 'app_min_concat.js'); var cssExist = false; var jsExist = false; var js1Exist = false; var js2Exist = false; stream.on('data', function(newFile) { if (path.basename(newFile.path) === path.basename(nameCss)) { cssExist = true; assert.equal(String(getExpected(expectedNameCss).contents), String(newFile.contents)); } else if (path.basename(newFile.path) === path.basename(nameJs)) { jsExist = true; assert.equal(String(getExpected(expectedNameJs).contents), String(newFile.contents)); } else if (newFile.path.indexOf(nameJs1) != -1) { js1Exist = true; assert.equal(String(getExpected(expectedNameJs1).contents), String(newFile.contents)); } else if (newFile.path.indexOf(nameJs2) != -1) { js2Exist = true; assert.equal(String(getExpected(expectedNameJs2).contents), String(newFile.contents)); } else { assert.ok(cssExist); assert.ok(jsExist); assert.ok(js1Exist); assert.ok(js2Exist); done(); } }); stream.write(getFixture('many-blocks.html')); }); describe('assetsDir option:', function() { function compare(assetsDir, done) { var stream = usemin({assetsDir: assetsDir}); var expectedName = 'style.css'; stream.on('data', function(newFile) { if (path.basename(newFile.path) === expectedName) { assert.equal(String(getExpected(expectedName).contents), String(newFile.contents)); done(); } }); stream.write(getFixture('simple-css.html')); } it('absolute path', function(done) { compare(path.join(process.cwd(), 'test', 'fixtures'), done); }); it('relative path', function(done) { compare(path.join('test', 'fixtures'), done); }); }); describe('conditional comments:', function() { function compare(name, expectedName, done) { var stream = usemin(); stream.on('data', function(newFile) { if (path.basename(newFile.path) === name) { assert.equal(String(getExpected(expectedName).contents), String(newFile.contents)); done(); } }); stream.write(getFixture(name)); } it('conditional (js block)', function(done) { compare('conditional-js.html', 'conditional-js.html', done); }); it('conditional (css block)', function(done) { compare('conditional-css.html', 'conditional-css.html', done); }); it('conditional (css + js)', function(done) { compare('conditional-complex.html', 'conditional-complex.html', done); }); it('conditional (inline js block)', function(done) { compare('conditional-inline-js.html', 'conditional-inline-js.html', done); }); it('conditional (inline css block)', function(done) { compare('conditional-inline-css.html', 'conditional-inline-css.html', done); }); }); describe('globbed files:', function() { function compare(fixtureName, name, end) { var stream = usemin(); stream.on('data', function(newFile) { if (path.basename(newFile.path) === name) { assert.equal(String(newFile.contents), String(getExpected(name).contents)); end(); } }); stream.write(getFixture(fixtureName)); } it('glob (js block)', function(done) { compare('glob-js.html', 'app.js', done); }); it('glob (css block)', function(done) { compare('glob-css.html', 'style.css', done); }); it('glob inline (js block)', function(done) { compare('glob-inline-js.html', 'glob-inline-js.html', done); }); it('glob inline (css block)', function(done) { compare('glob-inline-css.html', 'glob-inline-css.html', done); }); }); describe('comment files:', function() { function compare(name, callback) { var stream = usemin({enableHtmlComment: true}); stream.on('data', callback); stream.write(getFixture(name)); } it('comment (js block)', function(done) { var expectedName = 'app.js'; compare( 'comment-js.html', function(newFile) { if (path.basename(newFile.path) === expectedName) { assert.equal(String(newFile.contents), String(getExpected(expectedName).contents)); done(); } } ); }); }); describe('inline Sources:', function() { function compare(fixtureName, name, end) { var stream = usemin(); stream.on('data', function(newFile) { if (path.basename(newFile.path) === name) { assert.equal(String(newFile.contents), String(getExpected(name).contents)); end(); } }); stream.write(getFixture(fixtureName)); } it('simple inline js block', function (done) { compare('simple-inline-js.html', 'simple-inline-js.html', done); }); it('simple inline css block', function (done) { compare('simple-inline-css.html', 'simple-inline-css.html', done); }); it('simple inline js block width single quotes', function (done) { compare('single-quotes-inline-js.html', 'single-quotes-inline-js.html', done); }); it('simple inline css block with single quotes', function (done) { compare('single-quotes-inline-css.html', 'single-quotes-inline-css.html', done); }); }); describe('array jsAttributes:', function() { function compare(fixtureName, name, end) { var stream = usemin({ jsAttributes: { seq: [1, 2, 1, 3], color: ['blue', 'red', 'yellow', 'pink'] }, js: [], js1: [], js2: [], js3: [] }); stream.on('data', function(newFile) { if (path.basename(newFile.path) === name) { assert.equal(String(newFile.contents), String(getExpected(name).contents)); end(); } }); stream.write(getFixture(fixtureName)); } it('js attributes with array define', function (done) { compare('array-js-attributes.html', 'array-js-attributes.html', done); }); }); it('async task', function(done) { var less = require('gulp-less'); var cssmin = require('gulp-minify-css'); var stream = usemin({ less: [less(), 'concat', cssmin()] }); var name = 'style.css'; var expectedName = 'min-style.css'; stream.on('data', function(newFile) { if (path.basename(newFile.path) === path.basename(name)) { assert.equal(String(getExpected(expectedName).contents), String(newFile.contents)); done(); } }); stream.write(getFixture('async-less.html')); }); it('subfolders', function(done) { var stream = usemin(); var jsExist = false; var nameJs = path.join('subfolder', 'app.js'); stream.on('data', function(newFile) { if (path.basename(newFile.path) === path.basename(nameJs)) { jsExist = true; assert.equal(path.relative(newFile.base, newFile.path), nameJs); assert.equal(String(getExpected(nameJs).contents), String(newFile.contents)); } else { assert.ok(jsExist); done(); } }); vfs.src('test/fixtures/**/index.html') .pipe(stream); }); }); it('multiple files in stream', function(done) { var multipleFiles = function() { var through = require('through2'); var File = gutil.File; return through.obj(function(file) { var stream = this; stream.push(new File({ cwd: file.cwd, base: file.base, path: file.path, contents: new Buffer('test1') })); stream.push(new File({ cwd: file.cwd, base: file.base, path: file.path, contents: new Buffer('test2') })); }); }; var stream = usemin({ css: [multipleFiles], js: [multipleFiles] }); stream.on('data', function(newFile) { if (path.basename(newFile.path) === path.basename('multiple-files.html')) { assert.equal(String(getExpected('multiple-files.html').contents), String(newFile.contents)); done(); } }); stream.write(getFixture('multiple-files.html')); }); }); ================================================ FILE: lib/htmlPathParser.js ================================================ /** * FOR PARSE HTML REF PATH */ 'use strict' var through = require('through2'), path = require('path'), j = path.join, // gulpman utils gmutil = require('./gmutil') function _dealHTML(conf){ let _opts = conf['_opts'], basepath = conf['basepath'], _isRuntimeDir = conf['_isRuntimeDir'], all_raw_source_reg = conf['all_raw_source_reg'] return through.obj(function (file, enc, cb){ if (file.isNull()) { this.push(file); return cb() } if (file.isStream()) { gmutil.error('*ParseHtml Error: Streaming not supported') return cb() } let contents = file.contents.toString() // file.relative 是根据path.base自动生成的 if(basepath) file.base = basepath let fdirname = path.dirname(file.relative) // set assets url prefix let _urlPrefix if(_opts['is_absolute']) { _urlPrefix = _opts['url_prefix'] }else { // 判断打包资源中的url路径前缀 let _fPath = j(_isRuntimeDir ? _opts['runtime_views'] : _opts['dist_views'], fdirname) let _staticPath = _isRuntimeDir ? _opts['runtime_static'] : _opts['dist_static'] _urlPrefix = path.relative(_fPath, _staticPath) } // 所有格式都要处理 let srcQuoteReg = new RegExp('(?=[\'"]?)([\\w\\.\\-\\?\\-\\/\\:]+?(\\.('+all_raw_source_reg+')))(?=\\?_gm_inline)?(?=[\'"]?)', 'gm') // httpReg = /^http(s)?\:/ let tmp_rs_list = [], rs_list = [] // 提取单标签和双标签 tmp_rs_list = tmp_rs_list .concat(contents.match(gmutil.reg['tagMedia'])) .concat(contents.match(gmutil.reg['closeTagMedia'])) // 首先提取标签,然后从标签中提取href或者src tmp_rs_list.length && ( rs_list = tmp_rs_list .filter(r=>(r && r.match(srcQuoteReg))) .map(v=>v.match(srcQuoteReg)[0]) .filter(r=>{ // remove the http:xxx.com/xx and base64 data url // 只处理相对路径 // 不处理绝对路径、http、dataURL return gmutil.isUrl('relative', r) }) .filter(r=>!r.match(/^(['"]\/)/gm)) ) // 这里利用set做去重 let rs_set = new Set(rs_list), srcPrefix = j(_urlPrefix, fdirname) // 替换url的的path和前缀 rs_set.size && rs_set.forEach(epath=>{ // 对于base64的参数标识要保留,不能清理掉,因为后续要嵌入base64 let innerReg = new RegExp('(?=[\'"]?)('+epath+')(\\?_gm_inline)*(?=[\'"]?)', 'gm') contents = contents.replace(innerReg, j(srcPrefix, epath)+'$2') }) // dealing with usemin build mark syntax // when in publish, not runtime-dir if(!_isRuntimeDir) { // 这里处理usemin 的build的注释内容 contents = gmutil.replaceBuildBlock(contents, srcPrefix) } file.contents = new Buffer(contents) gmutil.tip('*Raw HTML File Parsed: '+file.relative) this.push(file) cb() }) } module.exports = _dealHTML ================================================ FILE: lib/iconFonter.js ================================================ // Copyright (c) 2015 App Annie Inc. All rights reserved. 'use strict'; var path = require('path'), j = path.join; var sh = require("shelljs") var fontName = 'gmicon'; function registerTask(gulp, opts) { var runTimestamp = Math.round(Date.now() / 1000); if(!opts['iconfont']) { opts['iconfont'] = { } } var _iconConf = opts['iconfont']; var svgSource = _iconConf['source'] || j(opts['components'], 'iconfonts/source') var iconPath = _iconConf['icon'] || j(opts['components'], 'iconfonts', fontName) // var iconCSSPath = _iconConf['css'] || j(opts['components'], 'iconfonts') var svgSource = j(svgSource, '/*.svg'); gulp.task('gm:iconfont', function() { var iconfont = require('gulp-iconfont'); var iconfontCss = require('gulp-iconfont-css'); return gulp.src(svgSource) .pipe(iconfontCss({ fontName: fontName, // path: 'app/assets/css/templates/_icons.scss', targetPath: 'gmicon.css', fontPath: './', cssClass: 'gmicon' })) .pipe(iconfont({ fontName: fontName, // required formats: ['svg', 'ttf', 'eot', 'woff', 'woff2'], normalize: true, fontHeight: 500, timestamp: runTimestamp // recommended to get consistent builds when watching files })) .pipe(gulp.dest(iconPath)) }); } exports.registerTask = registerTask; ================================================ FILE: lib/inline.js ================================================ /** * Created by Rodey on 2015/11/5. */ var fs = require('fs'), path = require('path'), through2 = require('through2'), uglifycss = require('uglifycss'), jsmin = require('jsmin2'), PluginError = require('gulp-util').PluginError, gmutil = require('./gmutil'), store = require('./store') var PLUGIN_NAME = 'gulp-html-inline'; var linkRegx = new RegExp('[\\s\\S]*?<*\\/*>*', 'gi'), hrefRegx = new RegExp('\\s*(href)="+([\\s\\S]*?)"'), styleRegx = new RegExp('[\\s\\S]*?<\\/style>', 'gi'), jsRegx = new RegExp('[\\s\\S]*?<\\/script>', 'gi'), scriptRegx = new RegExp('[\\s\\S]*?<\\/script>', 'gi'), srcRegx = new RegExp('\\s*(src)="+([\\s\\S]*?)"'); var joint = function(tag, content){ return '<'+ tag +'>' + content + ''; }; // add for gulpman var _file; /** * 获取get模式下url中的指定参数值 * @param name 参数名 * @param url 传入的url地址 * @returns {*} */ var getParams = function(name, url) { var reg = new RegExp('(^|&)' + name + '=?([^&]*)(&|$)', 'i'), search = ''; if(url && url !== ''){ search = (url.split('?')[1] || '').match(reg); }else{ search = window.location.search.substr(1).match(reg); } if(search && search[0].indexOf(name) !== -1) { return search[2] ? decodeURI(search[2]) : null; } }; //压缩内联css代码 | js脚本 var miniInline = function(content, type, options){ var isMinifyCss = options && !!options.minifyCss, isMinifyJs = options && !!options.minifyJs, ignore = options['ignore'] || 'ignore', basePath = options['basePath'] || '', queryKey = options['queryKey'] || '_gm_inline', queryRegx = new RegExp('&*'+ queryKey +'[=|&]?', 'i'), code = content, tags; tags = content.match(/<[\s\S]*?<*\/*[\s\S]*?>/gi); if(tags && tags[0] && tags[0].indexOf(ignore) !== -1) return content; if('css' === type){ if(!isMinifyCss) return content; code = uglifycss.processString(content, options); } else if('js' === type){ if(!isMinifyJs) return content; /** * FIX BUGS FOR replace */ // gmutil.alert('content: \n'+content) // gmutil.alert('opts: \n'+JSON.stringify(options)) var pt = /(?=['"]?)([\w\/\-\?\&\=]*?\.js)(?=['"]?)/gm, item // 如果没有标记inline,那么不处理 if((item = content.match(pt)) && (item = item[0])){ if(!item.match(queryRegx)) return content } // gmutil.alert(jsmin(content, options).code) code = jsmin(content, options).code.replace(/\n*\t*/gi, ''); } return code; }; //replace callback src | href var replaceCallback = function(sourceRegx, match, parentFile, type, options){ var ms = sourceRegx.exec(match), code = '', query, isMinifyCss = options && !!options.minifyCss, isMinifyJs = options && !!options.minifyJs, ignore = options['ignore'] || 'ignore', basePath = options['basePath'] || '', queryKey = options['queryKey'] || '_gm_inline', queryRegx = new RegExp('&*'+ queryKey +'[=|&]?', 'i'); if(!ms || !ms[2] || '' === ms[2]){ return miniInline(match, type, options); } var attr = ms[1] || '', href = ms[2] || ''; if(match.indexOf(ignore) !== -1) return match.replace(queryRegx, ''); //在url地址上加上 _gm_inline_字段就可以直接嵌入网页 query = getParams(queryKey, href); if(query === undefined){ return match.replace(queryRegx, ''); } // 如果使用绝对路径 if(options['absoluteRoot']){ var sourceFile = path.join(options['root'], options['absoluteRoot'], href.split('?')[0]) }else { var sourceFile = path.normalize(path.dirname(parentFile) + path.sep + basePath + href.split('?')[0]) } if(!options['is_runtime']){ var url_runtime_dir = path.join(options['root'], options['runtime_dir']), url_dist_dir = path.join(options['root'], options['dist_dir']), sourceFile = sourceFile.replace(url_dist_dir, url_runtime_dir) } // remove the url prefix for once // the url is abs url sourceFile = sourceFile.replace(options['url_prefix'], '') if(!fs.existsSync(sourceFile)){ gmutil.error('\n*Error: \n*Inline File Not Exist: '+sourceFile+'\n') return match; } content = getFileContent(sourceFile); // add for gulpman store save store.save(sourceFile, _file.path) if('css' === type){ if(!isMinifyCss) return joint('style', content); code = uglifycss.processString(content, options); code = joint('style', code); } else if('js' === type){ if(!isMinifyJs) return joint('script', content); code = jsmin(content, options).code.replace(/\n*\t*/gi, ''); code = joint('script', code); } return code; }; //根据标签类型获取内容并压缩 var execture = function(file, options){ var parentFile = path.normalize(file.path); var fileContents = file.contents.toString('utf8'); if(typeof fileContents === 'undefined'){ fileContents = getFileContent(file.path); } // get the single tag replace-content (mined) var content = fileContents .replace(linkRegx, function($1){ //like: return replaceCallback(hrefRegx, $1, parentFile, 'css', options); }).replace(jsRegx, function($1){ //like: return replaceCallback(srcRegx, $1, parentFile, 'js', options); }).replace(styleRegx, function($1){ //like: // //console.log($1); return miniInline($1, 'css', options); }).replace(scriptRegx, function($1){ //like: // /** * @debug for replace bug * this trigger the src with type joined together * lead into miniInline */ return miniInline($1, 'js', options); }); return content; }; //get the content of files var getFileContent = function(file){ if(!fs.existsSync(file)) throw new Error('File not find: ' + file); var fileContent = fs.readFileSync(file, { encoding: 'utf8' }); return fileContent; //file.contents = new Buffer(uglifycss.processString(fileContent, options)); }; //get the mined files content var getContent = function(file, options){ var content = execture(file, options); return content; }; //将压缩后的内容替换到html中 var inline = function(options){ var options = options || {}, basePath = options.basePath; //是否压缩css, 默认压缩 options.minifyCss = 'undefined' === typeof(options.minifyCss) ? true : options.minifyCss; //是否压缩js, 默认压缩 options.minifyJs = 'undefined' === typeof(options.minifyJs) ? true : options.minifyJs; return through2.obj(function(file, enc, next){ if (file.isStream()) { this.emit('error', new PluginError(PLUGIN_NAME, 'Stream content is not supported')); return next(null, file); } _file = file if (file.isBuffer()) { try { var content = getContent(file, options); file.contents = new Buffer(content); } catch (err) { this.emit('error', new PluginError(PLUGIN_NAME, err['message'])); } } this.push(file); return next(); }); }; module.exports = inline; ================================================ FILE: lib/revReplace.js ================================================ 'use strict'; var path = require('path'); var gutil = require('gulp-util'); var through = require('through2'); var gmutil = require('./gmutil'); function plugin(options) { var renames = []; var cache = []; options = options || {}; if (!options.canonicalUris) { options.canonicalUris = true; } options.replaceInExtensions = options.replaceInExtensions || ['.js', '.css', '.html', '.hbs']; // @debug add for gulpman options.prefix = options.prefix || ''; options['_prefix'] = options['prefix'] options['_all_prefix'] = new Set() var _url_prefix = options['url_prefix'] // @add prefix array and fn support // @Lucas if(typeof options.prefix == 'string'){ options['_all_prefix'].add(options.prefix) }else if(options.prefix instanceof Array){ // 虽然在gulpman/index中已经做了proxy,但是目前注释掉这块,会导致/http://xx的问题,需要处理下 Object.defineProperty(options, 'prefix',{ get: function () { var p = this['_prefix'][gmutil.randomNum(0, options['_prefix'].length-1)] options['_all_prefix'].add(p) return p }, set : function (val) { this['_prefix'] = val }, configurable : true }) // if the param is a function }else if(options.prefix instanceof Function){ Object.defineProperty(options, 'prefix',{ get: function () { var p = this['_prefix'](options['_tmpMediaFilePath'], options['_tmpMediaFilePath']) options['_all_prefix'].add(p) return p; }, set : function (val) { this['_prefix'] = val }, configurable : true }) }else { // default } return through.obj(function collectRevs(file, enc, cb) { if (file.isNull()) { this.push(file); return cb(); } if (file.isStream()) { this.emit('error', new gutil.PluginError('gulp-rev-replace', 'Streaming not supported')); return cb(); } // 此处file是宿主文件 options['_file'] = file // Collect renames from reved files. if (file.revOrigPath) { // @add for gulpman hooks options['_tmpHostFilePath'] = file.path var mediaFilePath = fmtPath(file.revOrigBase, file.revOrigPath) // media file ,js css,egg. options['_tmpMediaFilePath'] = mediaFilePath // 此处触发一次运行函数 var availablePrefix = options.prefix renames.push({ unreved: mediaFilePath, reved: availablePrefix + fmtPath(file.base, file.path) }); } if (options.replaceInExtensions.indexOf(path.extname(file.path)) > -1) { // file should be searched for replaces cache.push(file); } else { // nothing to do with this file this.push(file); } cb(); }, function replaceInFiles(cb) { var stream = this; if (options.manifest) { // Read manifest file for the list of renames. options.manifest.on('data', function (file) { var manifest = JSON.parse(file.contents.toString()); Object.keys(manifest).forEach(function (srcFile) { // @add for gulpman hooks var unrevedFilePath = canonicalizeUri(srcFile) //if want delete source file, can do delete here options['_tmpMediaFilePath'] = unrevedFilePath if(options['_file']){ options['_tmpHostFilePath'] = options['_file'].path } // 此处每次get prefix,都会运行一次产生函数,每次结果可能不同 var availablePrefix = options.prefix renames.push({ unreved: unrevedFilePath, reved: availablePrefix + canonicalizeUri(manifest[srcFile]) }); }); }); options.manifest.on('end', replaceContents); } else { replaceContents(); } function replaceContents() { renames = renames.sort(gmutil.byLongestUnreved); // Once we have a full list of renames, search/replace in the cached // files and push them through. cache.forEach(function replaceInFile(file) { var contents = file.contents.toString(); renames.forEach(function replaceOnce(rename) { var unreved = options.modifyUnreved ? options.modifyUnreved(rename.unreved) : rename.unreved; var reved = options.modifyReved ? options.modifyReved(rename.reved) : rename.reved; contents = contents.split(unreved).join(reved); options['_all_prefix'].size && options['_all_prefix'].forEach((availablePrefix)=>{ // add for gulpman hooks // 这块需要遍历所有prefix,每次prefix可能会变,导致替换失败 if (availablePrefix) { var _tmp_full_url_prefix = _url_prefix + '/'+ availablePrefix; var _full_url_prefix = gmutil.joinUrl(availablePrefix, _url_prefix); contents = contents.split(_tmp_full_url_prefix).join(_full_url_prefix) } }) }); file.contents = new Buffer(contents); stream.push(file); }); cb(); } }); function fmtPath(base, filePath) { var newPath = path.relative(base, filePath); return canonicalizeUri(newPath); } // 标准化url function canonicalizeUri(filePath) { if (path.sep !== '/' && options.canonicalUris) { filePath = filePath.split(path.sep).join('/'); } return filePath; } } /** * Export API * @type {[type]} */ module.exports = plugin; ================================================ FILE: lib/spriter/README.md ================================================ [![npm version](https://badge.fury.io/js/gulp-css-spriter.svg)](http://badge.fury.io/js/gulp-css-spriter) # gulp-css-spriter `gulp-css-spriter`, a [gulp](http://gulpjs.com/) plugin, looks through the CSS you pipe in and gathers all of the background images. It then creates a sprite sheet and updates the references in the CSS. You can easily exclude/include certain background image declarations using meta info in your styles([*see meta section below*](#meta-options)) and `includeMode` option([*see options section below*](#options)) depending on your use case. # Install ### Latest Version: 0.3.3 `npm install gulp-css-spriter` # About `gulp-css-spriter` uses [spritesmith](https://www.npmjs.com/package/spritesmith) behind the scenes for creating the sprite sheet. # Usage ## Basic usage This is most likely the setup you will probably end up using. ``` var gulp = require('gulp'); var spriter = require('gulp-css-spriter'); gulp.task('css', function() { return gulp.src('./src/css/styles.css') .pipe(spriter({ // The path and file name of where we will save the sprite sheet 'spriteSheet': './dist/images/spritesheet.png', // Because we don't know where you will end up saving the CSS file at this point in the pipe, // we need a litle help identifying where it will be. 'pathToSpriteSheetFromCSS': '../images/spritesheet.png' })) .pipe(gulp.dest('./dist/css')); }); ``` ## Barebones usage The slimmest usage possible. ``` var gulp = require('gulp'); var spriter = require('gulp-css-spriter'); gulp.task('css', function() { return gulp.src('./styles.css') .pipe(spriter()) .pipe(gulp.dest('./')); }); ``` ## Minify CSS output usage If you want to use [@meta data](#meta-options) but are using a preprocessor such as Sass or Less, you will need to use a output style that doesn't strip comments. After piping the CSS through `gulp-css-spriter`, you can then run it through a CSS minifier(separate plugin), such as [`gulp-minify-css`](https://www.npmjs.com/package/gulp-minify-css). ``` var gulp = require('gulp'); var spriter = require('gulp-css-spriter'); var minifyCSS = require('gulp-minify-css'); // https://www.npmjs.com/package/gulp-minify-css gulp.task('css', function() { return gulp.src('./styles.css') .pipe(spriter()) .pipe(minifyCSS()) .pipe(gulp.dest('./')); }); ``` # Options - `options`: object - hash of options - `includeMode`: string - Determines whether meta data is necessary or not - Values: 'implicit', 'explicit' - Default: 'implicit' - For example, if `explicit`, you must have meta `include` as `true` in order for the image declarations to be included in the spritesheet: `/* @meta {"spritesheet": {"include": true}} */` - If left default at `implicit`, all images will be included in the spritesheet; except for image declarations with meta `include` as `false`: `/* @meta {"spritesheet": {"include": false}} */` - `spriteSheet`: string - The path and file name of where we will save the sprite sheet - Default: 'spritesheet.png' - `pathToSpriteSheetFromCSS`: string - Because we don't know where you will end up saving the CSS file at this point in the pipe, we need a litle help identifying where it will be. We will use this as the reference to the sprite sheet image in the CSS piped in. - Default: 'spritesheet.png' - `spriteSheetBuildCallback`: function - Same as the [spritesmith callback](https://www.npmjs.com/package/spritesmith#-spritesmith-params-callback-) - Default: null - Callback has a parameters as so: `function(err, result)` - `result.image`: Binary string representation of image - `result.coordinates`: Object mapping filename to {x, y, width, height} of image - `result.properties`: Object with metadata about spritesheet {width, height} - `silent`: bool - We ignore any images that are not found but are supposed to be sprited by default - Default: true - `shouldVerifyImagesExist`: bool - Check to make sure each image declared in the CSS exists before passing it to the spriter. Although silenced by default(`options.silent`), if an image is not found, an error is thrown. - Default: true - `spritesmithOptions`: object - Any option you pass in here, will be passed through to spritesmith. [See spritesmith options documenation](https://www.npmjs.com/package/spritesmith#-spritesmith-params-callback-) - Default: {} - `outputIndent`: bool - Used to format output CSS. You should be using a separate beautifier plugin. The reason the output code is reformatted is because it is easier to "parse->stringify" than "replace in place". - Default: '\t' # What we emit `gulp-css-spriter` emits the transformed CSS with updated image references to the sprite sheet as a normal Gulp [vinyl file](https://www.npmjs.com/package/vinyl). We also attach the binary sprite sheet image in `chunk.spriteSheet` in case you want to consume it later down the pipe. # Meta info `gulp-css-spriter` uses a JSON format to add info onto CSS declarations. The example below will exclude this declaration from the spritesheet. ``` /* @meta {"spritesheet": {"include": false}} */ background: url('../images/dummy-blue.png'); ``` Please note that if you are compiling from Sass/Less and are not getting correct results, to check the outputted CSS and make sure the comments are still in tact and on the line you expect. For Sass, use multiline `/* */` comment syntax and put them above declarations. This is because gulp-sass/node-sass/libsass removes single line comments and puts mult-line comments that are on the same line as a declaration, below the declaraton. The `@meta` comment data can be above or on the same line as the declaration for it to apply. ``` /* @meta {"spritesheet": {"include": false}} */ background: url('../images/dummy-blue.png'); /* @meta {"spritesheet": {"include": false}} */ ``` ## Meta options - `spritesheet`: object - hash of options that `gulp-css-spriter` will factor in - `include`: bool - determines whether or not the declaration should be included in the spritesheet. This can be left undefined if the `includeMode` is 'implicit' # What we emit `gulp-css-spriter` transforms your CSS image paths to the spritesheet appropriately then emits the CSS as a normal Gulp [vinyl file](https://www.npmjs.com/package/vinyl). - Gulp [vinyl file](https://www.npmjs.com/package/vinyl). We emit the CSS you passed in with transformed image paths ## Events ### `.on('log', function(message) { })` We emit log messages such as when a image defined in the CSS can't be found on disk. ### `.on('error', function(err) { })` A normal gulp error. There are a variety of errors. See source code for more details. # Testing We have a series of unit tests. We use [Mocha](http://mochajs.org/). Install Mocha globally: ``` npm install -g mocha ``` Run tests with: `mocha` or `npm test` ================================================ FILE: lib/spriter/index.js ================================================ // gulp-css-spriter: https://www.npmjs.com/package/gulp-css-spriter // Sprite Sheet Generation from CSS source files. // // By: Eric Eastwood: EricEastwood.com // // Meta info looks like: `/* @meta {"spritesheet": {"include": false}} */` var fs = require('fs-extra'); var path = require('path'); var Promise = require('bluebird'); var outputFile = Promise.promisify(fs.outputFile); var stat = Promise.promisify(fs.stat); var through = require('through2'); var extend = require('extend') var gutil = require('gulp-util'); var css = require('css'); var spritesmith = require('spritesmith'); var spritesmithBuild = Promise.promisify(spritesmith); var spriterUtil = require('./lib/spriter-util'); var getBackgroundImageDeclarations = require('./lib/get-background-image-declarations'); var transformFileWithSpriteSheetData = require('./lib/transform-file-with-sprite-sheet-data'); var gmutil = require('../gmutil'), store = require('../store') // consts const PLUGIN_NAME = 'gulp-css-spriter'; const gm_sprite_img_dir = 'gm_sprite_img' const gm_sprite_subfix = '_sprite_sheet.png' var spriter = function(options) { var defaults = { // ('implicit'|'explicit') 'includeMode': 'implicit', // The path and file name of where we will save the sprite sheet 'spriteSheet': 'spritesheet.png', // Because we don't know where you will end up saving the CSS file at this point in the pipe, // we need a litle help identifying where it will be. 'pathToSpriteSheetFromCSS': 'spritesheet.png', // Same as the spritesmith callback `function(err, result)` // result.image: Binary string representation of image // result.coordinates: Object mapping filename to {x, y, width, height} of image // result.properties: Object with metadata about spritesheet {width, height} 'spriteSheetBuildCallback': null, // If true, we ignore any images that are not found on disk // Note: this plugin will still emit an error if you do not verify that the images exist 'silent': true, // Check to make sure each image declared in the CSS exists before passing it to the spriter. // Although silenced by default(`options.silent`), if an image is not found, an error is thrown. 'shouldVerifyImagesExist': true, // Any option you pass in here, will be passed through to spritesmith // https://www.npmjs.com/package/spritesmith#-spritesmith-params-callback- 'spritesmithOptions': {}, // Used to format output CSS // You should be using a separate beautifier plugin 'outputIndent': '\t' }; var settings = extend({}, defaults, options); // Keep track of all the chunks that come in so that we can re-emit in the flush var chunkList = []; // We use an object for imageMap so we don't get any duplicates var imageMap = {}; // Check to make sure all of the images exist(`options.shouldVerifyImagesExist`) before trying to sprite them var imagePromiseArray = []; // var currentChunkFile; var stream = through.obj(function(chunk, enc, cb) { // http://nodejs.org/docs/latest/api/stream.html#stream_transform_transform_chunk_encoding_callback //console.log('transform'); // Each `chunk` is a vinyl file: https://www.npmjs.com/package/vinyl // chunk.cwd // chunk.base // chunk.path // chunk.contents var self = this; if (chunk.isStream()) { self.emit('error', new gutil.PluginError(PLUGIN_NAME, 'Cannot operate on stream')); } else if (chunk.isBuffer()) { var contents = String(chunk.contents); var styles; try { styles = css.parse(contents, { 'silent': settings.silent, 'source': chunk.path }); } catch(err) { err.message = 'Something went wrong when parsing the CSS: ' + err.message; self.emit('log', err.message); // Emit an error if necessary if(!settings.silent) { self.emit('error', err); } } var fileDir = path.relative(settings['dist_root'], chunk.base) var fileName = path.basename(chunk.relative) // add for gulpman chunk.base = settings['cwd'] // currentChunkFile = chunk var relDistPath = path.join( gm_sprite_img_dir, fileName+gm_sprite_subfix ) var distSpritePath = path.join(settings['dist_root'], fileDir, relDistPath) settings['spriteSheet'] = distSpritePath settings['pathToSpriteSheetFromCSS'] = relDistPath // Gather a list of all of the image declarations var chunkBackgroundImageDeclarations = getBackgroundImageDeclarations(styles, settings.includeMode); // Go through each declaration and gather the image paths // We find the new images that we found in this chunk verify they exist below // We use an object so we don't get any duplicates var newImagesfFromChunkMap = {}; var backgroundURLMatchAllRegex = new RegExp(spriterUtil.backgroundURLRegex.source, "gi"); chunkBackgroundImageDeclarations.forEach(function(declaration) { // Match each background image in the declaration (there could be multiple background images per value) spriterUtil.matchBackgroundImages(declaration.value, function(imagePath) { imagePath = path.join(path.dirname(chunk.path), imagePath); // If not already in the overall list of images collected // Add to the queue/list of images to be verified if(!imageMap[imagePath]) { newImagesfFromChunkMap[imagePath] = true; } // Add it to the main overall list to keep track imageMap[imagePath] = true; }); }); // Filter out any images that do not exist depending on `settings.shouldVerifyImagesExist` Object.keys(newImagesfFromChunkMap).forEach(function(imagePath) { var filePromise; if(settings.shouldVerifyImagesExist) { filePromise = stat(imagePath).then(function() { return { doesExist: true, path: imagePath }; }, function() { return { doesExist: false, path: imagePath }; }); } else { // If they don't want us to verify it exists, just pass it on with a undefined `doesExist` property filePromise = Promise.resolve({ doesExist: undefined, path: imagePath }); } imagePromiseArray.push(filePromise); }); // Keep track of each chunk and what declarations go with it // Because the positions/line numbers pertain to that chunk only chunkList.push(chunk); } // "call callback when the transform operation is complete." cb(); }, function(cb) { // http://nodejs.org/docs/latest/api/stream.html#stream_transform_flush_callback //console.log('flush'); var self = this; // @debug // Create an verified image list when all of the async checks have finished var imagesVerifiedPromise = Promise.settle(imagePromiseArray).then(function(results) { var imageList = []; Array.prototype.forEach.call(results, function(result) { imageInfo = result.value(); if(imageInfo.doesExist === true || imageInfo.doesExist === undefined) { imageList.push(imageInfo.path); } else { // Tell them that we could not find the image var logMessage = 'Image could not be found: ' + imageInfo.path; self.emit('log', logMessage); // Emit an error if necessary if(!settings.silent) { self.emit('error', { 'name': 'NotFound', 'message': logMessage, 'plugin': PLUGIN_NAME }); } } }); return imageList; }); // Start spriting once we know the true list of images that exist imagesVerifiedPromise.then(function(imageList) { // fix the invalid png files when no-sprite-img // @debug ..可能有问题。。 if(!imageList.length) { chunkList.forEach(chunk=>{ self.push(chunk) }) return cb(); } // Generate the spritesheet var spritesmithOptions = extend({}, settings.spritesmithOptions, { src: imageList }); var spriteSmithBuildPromise = spritesmithBuild(spritesmithOptions); spriteSmithBuildPromise.then(function(result) { var whenImageDealtWithPromise = new Promise(function(resolve, reject) { // Save out the spritesheet image if(settings.spriteSheet) { var spriteSheetSavedPromise = outputFile(settings.spriteSheet, result.image, 'binary').then(function() { //console.log("The file was saved!"); // Push all of the chunks back on the pipe chunkList.forEach(function(chunk) { var transformedChunk = chunk.clone(); // gmutil.alert('IMG: '+imageList) // save into relevancy store store.save(imageList, chunk.path, 'sprite') try { transformedChunk = transformFileWithSpriteSheetData(transformedChunk, result.coordinates, settings.pathToSpriteSheetFromCSS, settings.includeMode, settings.silent, settings.outputIndent); } catch(err) { err.message = 'Something went wrong when transforming chunks: ' + err.message; self.emit('log', err.message); // Emit an error if necessary if(!settings.silent) { self.emit('error', err); } reject(err); } // Attach the spritesheet in case someone wants to use it down the pipe transformedChunk.spritesheet = result.image; // Push it back on the main pipe self.push(transformedChunk); }); }, function() { settings.spriteSheetBuildCallback(err, null); reject(err); }); spriteSheetSavedPromise.finally(function() { // Call a callback from the settings the user can hook onto if(settings.spriteSheetBuildCallback) { settings.spriteSheetBuildCallback(null, result); } resolve(); }); } else { resolve(); } }); whenImageDealtWithPromise.finally(function() { // "call callback when the flush operation is complete." cb(); }); }, function(err) { if(err) { err.message = 'Error creating sprite sheet image:\n' + err.message; self.emit('error', new gutil.PluginError(PLUGIN_NAME, err)); } }); }); }); // returning the file stream return stream; }; module.exports = spriter; ================================================ FILE: lib/spriter/lib/get-background-image-declarations.js ================================================ var mapOverStylesAndTransformBackgroundImageDeclarations = require('./map-over-styles-and-transform-background-image-declarations'); // Pass in a styles object from `css.parse` // See main module for `includeMode` values function getBackgroundImageDeclarations(styles, includeMode) { includeMode = includeMode || 'implicit'; // First get all of the background image declarations var backgroundImageDeclarations = []; mapOverStylesAndTransformBackgroundImageDeclarations(styles, includeMode, function(declaration) { backgroundImageDeclarations.push(declaration); }); return backgroundImageDeclarations; } module.exports = getBackgroundImageDeclarations; ================================================ FILE: lib/spriter/lib/get-meta-info-for-declaration.js ================================================ var extend = require('extend'); function getMetaInfoForDeclaration(declarations, declarationIndex) { var resultantMetaData = {}; if(declarationIndex > 0 && declarationIndex < declarations.length) { var mainDeclaration = declarations[declarationIndex]; if(mainDeclaration) { // Meta data can exist before or on the same line as the declaration. // Both Meta blocks are valid for the background property // ex. // /* @meta {"spritesheet": {"include": false}} */ // background: url('../images/aenean-purple.png'); /* @meta {"sprite": {"skip": true}} */ var beforeDeclaration = declarations[declarationIndex-1]; var afterDeclaration = declarations[declarationIndex+1]; if(beforeDeclaration) { // The before declaration should be valid no matter what (even if multiple lines above) // The parse function does all the nice checking for us extend(resultantMetaData, parseCommentDecarationForMeta(beforeDeclaration)); } if(afterDeclaration) { //console.log(mainDeclaration); //console.log(afterDeclaration); //console.log(afterDeclaration.position.start.line, mainDeclaration.position.start.line); // Make sure that the comment starts on the same line as the main declaration if((((afterDeclaration || {}).position || {}).start || {}).line === (((mainDeclaration || {}).position || {}).start || {}).line) { extend(resultantMetaData, parseCommentDecarationForMeta(afterDeclaration)); } } } } return resultantMetaData; } function parseCommentDecarationForMeta(declaration) { if(declaration.type === "comment") { //console.log(declaration); var metaMatches = declaration.comment.match(/@meta\s*({.*?}(?!}))/); if(metaMatches) { var parsedMeta = {}; try { parsedMeta = JSON.parse(metaMatches[1]); } catch(e) { //console.warn('Meta info was found but failed was not valid JSON'); } return parsedMeta; } } } module.exports = getMetaInfoForDeclaration; ================================================ FILE: lib/spriter/lib/map-over-styles-and-transform-background-image-declarations.js ================================================ var extend = require('extend'); var spriterUtil = require('./spriter-util'); var getMetaInfoForDeclaration = require('./get-meta-info-for-declaration'); var transformMap = require('./transform-map'); function mapOverStylesAndTransformBackgroundImageDeclarations(styles, includeMode, cb) { // Map over all return mapOverStylesAndTransformAllBackgroundImageDeclarations(styles, function(declaration) { // Then filter down to only the proper ones (according to their meta data) if(shouldIncludeFactoringInMetaData(declaration.meta, includeMode)) { return cb.apply(null, arguments); } }); } // Boolean function to determine if the meta data permits using this declaration function shouldIncludeFactoringInMetaData(meta, includeMode) { var metaIncludeValue = (meta && meta.spritesheet && meta.spritesheet.include); var shouldIncludeBecauseImplicit = includeMode === 'implicit' && (metaIncludeValue === undefined || metaIncludeValue); var shouldIncludeBecauseExplicit = includeMode === 'explicit' && metaIncludeValue; var shouldInclude = shouldIncludeBecauseImplicit || shouldIncludeBecauseExplicit; // Only return declartions that shouldn't be skipped return shouldInclude; } // Pass in a styles object from `css.parse` // Loop over all of the styles and transform/modify the background image declarations // Returns a new styles object that has the transformed declarations function mapOverStylesAndTransformAllBackgroundImageDeclarations(styles, cb) { // Clone the declartion to keep it immutable var transformedStyles = extend(true, {}, styles); // Go over each background `url()` declarations transformedStyles.stylesheet.rules.map(function(rule, ruleIndex) { if(rule.type === 'rule') { rule.declarations = transformMap(rule.declarations, function(declaration, declarationIndex, declarations) { // Clone the declartion to keep it immutable var transformedDeclaration = extend(true, {}, declaration); transformedDeclaration = attachInfoToDeclaration(declarations, declarationIndex); /*// background-image always has a url if(transformedDeclaration.property === 'background-image') { return cb(transformedDeclaration, declarationIndex, declarations); } // Background is a shorthand property so make sure `url()` is in there else if(transformedDeclaration.property === 'background') { var hasImageValue = spriterUtil.backgroundURLRegex.test(transformedDeclaration.value); if(hasImageValue) { return cb(transformedDeclaration, declarationIndex, declarations); } }*/ // background-image always has a url且 // 判断url是否有?__spriter后缀 var gm_sprite_reg = /\?_gm_sprite/i, gm_sprite_str = '?_gm_sprite'; if (transformedDeclaration.property === 'background-image' && gm_sprite_reg.test(transformedDeclaration.value)) { transformedDeclaration.value = transformedDeclaration.value.replace(gm_sprite_str, ''); return cb(transformedDeclaration, declarationIndex, declarations); } //Background is a short hand property so make sure `url()` is in there // 且判断url是否有?__spriter后缀 else if(transformedDeclaration.property === 'background' && gm_sprite_reg.test(transformedDeclaration.value)) { transformedDeclaration.value = transformedDeclaration.value.replace(gm_sprite_str, ''); var hasImageValue = spriterUtil.backgroundURLRegex.test(transformedDeclaration.value); if (hasImageValue) { return cb(transformedDeclaration, declarationIndex, declarations); } } // Wrap in an object so that the declaration doesn't get interpreted return { 'value': transformedDeclaration }; }); } return rule; }); return transformedStyles; } // We do NOT directly modify the declaration in the rule // We pass the whole rule and current index so we can properly look at the metaData around each declaration // and add it to the declaration function attachInfoToDeclaration(declarations, declarationIndex) { if(declarations.length > declarationIndex) { // Clone the declartion to keep it immutable var declaration = extend(true, {}, declarations[declarationIndex]); var declarationMetaInfo = getMetaInfoForDeclaration(declarations, declarationIndex); // Add the meta into to the declaration declaration.meta = extend(true, {}, declaration.meta, declarationMetaInfo); return declaration; } return null; } module.exports = mapOverStylesAndTransformBackgroundImageDeclarations; ================================================ FILE: lib/spriter/lib/spriter-util.js ================================================ var backgroundURLRegex = (/(.*?url\(["\']?)(.*?\.(?:png|jpg|gif))(["\']?\).*?;?)/i); function matchBackgroundImages(declarationValue, cb) { var backgroundURLMatchAllRegex = new RegExp(backgroundURLRegex.source, "gi"); return declarationValue.replace(backgroundURLMatchAllRegex, function(match, p1, p2, p3, offset, string) { var imagePath = p2; return p1 + cb(imagePath) + p3; }); } module.exports = { 'backgroundURLRegex': backgroundURLRegex, 'matchBackgroundImages':matchBackgroundImages }; ================================================ FILE: lib/spriter/lib/transform-file-with-sprite-sheet-data.js ================================================ var path = require('path'); var extend = require('extend'); var css = require('css'); var spriterUtil = require('./spriter-util'); var mapOverStylesAndTransformBackgroundImageDeclarations = require('./map-over-styles-and-transform-background-image-declarations'); var backgroundURLMatchAllRegex = new RegExp(spriterUtil.backgroundURLRegex.source, "gi"); // Replace all the paths that need replacing function transformFileWithSpriteSheetData(vinylFile, coordinateMap, pathToSpriteSheetFromCSS, /*optional*/includeMode, /*optional*/isSilent, /*optional*/outputIndent) { includeMode = includeMode ? includeMode : 'implicit'; isSilent = (isSilent !== undefined) ? isSilent : false; outputIndent = outputIndent ? outputIndent : '\t'; // Clone the declartion to keep it immutable var resultantFile = vinylFile.clone(); if(resultantFile) { var styles = css.parse(String(resultantFile.contents), { 'silent': isSilent, 'source': vinylFile.path }); styles = mapOverStylesAndTransformBackgroundImageDeclarations(styles, includeMode, function(declaration) { var coordList = []; declaration.value = spriterUtil.matchBackgroundImages(declaration.value, function(imagePath) { var coords = coordinateMap[path.join(path.dirname(resultantFile.path), imagePath)]; //console.log('coords', coords); // Make sure there are coords for this image in the sprite sheet, otherwise we won't include it if(coords) { coordList.push("-" + coords.x + "px -" + coords.y + "px"); // If there are coords in the spritemap for this image, lets use the spritemap return pathToSpriteSheetFromCSS; } return imagePath; }); return { 'value': declaration, /* */ // Add the appropriate background position according to the spritemap 'insertElements': (function() { if(coordList.length > 0) { return { type: 'declaration', property: 'background-position', value: coordList.join(', ') }; } })() /* */ }; }); //console.log(styles.stylesheet.rules[0].declarations); // Put it back into string form var resultantContents = css.stringify(styles, { indent: outputIndent }); //console.log(resultantContents); resultantFile.contents = new Buffer(resultantContents); } return resultantFile; } module.exports = transformFileWithSpriteSheetData; ================================================ FILE: lib/spriter/lib/transform-map.js ================================================ var extend = require('extend'); function transformMap(arr, cb) { var resultantArray = extend(true, [], arr); for(var i = 0; i < resultantArray.length; i++) { var el = resultantArray[i]; var result = cb(el, i, resultantArray); var defaults = { value: el, insertElements: [], appendElements: [] }; // You can pass in a bare value or as the `value` property of an object result = typeof result === 'object' ? result : { value: result }; // Massage the result into shape result = extend({}, defaults, result); // Transform the current value resultantArray[i] = result.value ? result.value : result; // Insert after the current element var insertElements = [].concat(result.insertElements); if(insertElements.length > 0) { Array.prototype.splice.apply(resultantArray, [i+1, 0].concat(insertElements)); } // Add the elements onto the end var appendElements = [].concat(result.appendElements); if(appendElements.length > 0) { resultantArray = resultantArray.concat(appendElements); } } return resultantArray; } module.exports = transformMap; ================================================ FILE: lib/spriter/package.json ================================================ { "name": "gulp-css-spriter", "version": "0.3.3", "description": "Sprite Sheet Generation from CSS source files. The best and different approach to sprite sheets.", "main": "index.js", "repository": { "type": "git", "url": "https://github.com/MadLittleMods/gulp-css-spriter.git" }, "keywords": [ "css", "gulp", "gulpplugin", "gulpfriendly", "sprite", "spritesheet", "sass", "less" ], "author": { "name": "Eric Eastwood", "email": "contact@ericeastwood.com", "url": "http://ericeastwood.com/" }, "license": "MIT", "bugs": { "url": "https://github.com/MadLittleMods/gulp-css-spriter/issues" }, "scripts": { "test": "mocha" }, "dependencies": { "bluebird": "^2.9.3", "css": "^2.1.0", "extend": "^2.0.0", "fs-extra": "^0.14.0", "gulp-util": "^3.0.1", "spritesmith": "^1.0.3", "through2": "^0.6.2" }, "devDependencies": { "chai": "^1.10.0", "chai-as-promised": "^4.1.1", "gulp": "^3.8.10", "mocha": "^2.1.0" }, "gitHead": "2a4f030a00e0135ff8270acf1f34bb0c2537d102", "homepage": "https://github.com/MadLittleMods/gulp-css-spriter", "_id": "gulp-css-spriter@0.3.3", "_shasum": "4f69315ac01d92a0dc9996c02054cbd4826aeac1", "_from": "gulp-css-spriter@latest", "_npmVersion": "1.4.23", "_npmUser": { "name": "mlm", "email": "contact@ericeastwood.com" }, "maintainers": [ { "name": "mlm", "email": "contact@ericeastwood.com" } ], "dist": { "shasum": "4f69315ac01d92a0dc9996c02054cbd4826aeac1", "tarball": "http://registry.npmjs.org/gulp-css-spriter/-/gulp-css-spriter-0.3.3.tgz" }, "directories": {}, "_resolved": "https://registry.npmjs.org/gulp-css-spriter/-/gulp-css-spriter-0.3.3.tgz" } ================================================ FILE: lib/store.js ================================================ /** * For create JSON file */ var fs = require('fs'), path = require('path'), j = path.join var gmutil = require('./gmutil') var _cwd = process.cwd() // var jsonFileName = 'gm-relevancy.json', // jsonFilePath var dataBase = { 'name':'gm-relevancy', 'time': (new Date()).getTime(), 'source': {}, 'sprite': {} // 'requiredCSS': {}, } function initStore(db) { // check global namespace if(!global['gm_ns']) { global['gm_ns'] = {} } // update dataBase from global is existed if(global['gm_ns']['data_base']){ dataBase = db || global['gm_ns']['data_base'] }else{ global['gm_ns']['data_base'] = db || dataBase } } function _write(fpath){ fs.writeFileSync(fpath, JSON.stringify(dataBase, null, 4)) } function _push (sourceFile, refFile, dbType) { // 如果已经存储,那么不再重复push if(_isInList(sourceFile, refFile, dbType)) return true !dataBase[dbType] && (dataBase[dbType] = {}) if(dataBase[dbType][sourceFile]){ dataBase[dbType][sourceFile].push(refFile) }else { dataBase[dbType][sourceFile] = [refFile] } } function _check(sourceAbsPath, handler, dbType, handlerType, evtObj){ // gmutil.alert('Store: \n') // console.log(global['gm_ns']['data_base']) var dbType = dbType || 'source' if(sourceAbsPath in dataBase[dbType]){ // gmutil.alert('HIT Store: \n') // console.log(dataBase) if(handler){ dataBase[dbType][sourceAbsPath].forEach(item=>{ gmutil.warn('*Relevancy Process: '+item) // the handler default as file type var hfn = handlerType || path.extname(item).slice(1) handler[hfn] && handler[hfn](item, evtObj) }) } return true }else { return false } } function _isInList(sourceFile, refFile, dbType){ var r return (dataBase[dbType]) && (r = dataBase[dbType][sourceFile]) && r.indexOf(refFile) !== -1 } function _save (sourceFile, refFile, dbType) { var dbType = dbType || 'source' // gmutil.alert(sourceFile+' :\n'+refFile) if(typeof sourceFile == 'string'){ // just save in memory now, not write in file return _push(sourceFile, refFile, dbType) }else if(gmutil.isArray(sourceFile)){ sourceFile.forEach((e,i)=>{ _push(e, refFile, dbType) }) return true; }else { gmutil.error("*Relevancy Store Error:\n") throw Error('Unknown Type: '+sourceFile) } } function getStore(){ return dataBase } // init store initStore() // api exports.save = _save exports.check = _check exports.get = getStore ================================================ FILE: meta/home/index.html ================================================ HOME PAGE

Welcome to Gulpman!

Now You Can Create Your Own Modular Front-end Build System Easily!

How to use ReactJS in Gulpman ?

  1. Put ReactJS file in html by script tag.
  2. such as:

    <script src="react.min.js" type="text/javascript"></script>
    <script src="react-dom.min.js" type="text/javascript"></script>

  3. Or Import React in Your ES6/JSX:

    import 'react'

  4. Then you can directly use the React and ReactDOM Object in your ES6/JSX files.

Example:

Waiting ...

================================================ FILE: meta/home/main.es6 ================================================ /** * FOR HOME */ import 'react' let HelloMessage = React.createClass({ render () { return
The Content Are Created By {this.props.name}
} }) function renderHello (argument) { ReactDOM.render( , document.getElementById('demo1') ) } setTimeout(()=>{ renderHello() }, 1200) export { renderHello } ================================================ FILE: meta/home/main.scss ================================================ /** * FOR HOME */ .logo { background: url(./img/logo.png) no-repeat; } // for sprite demo .demo-sprite { background: url(./img/logo.png?_gm_sprite) no-repeat; width: 50px; height: 50px; } .demo-inline { // if you want use inline-base64, // add `?_gm_inline` after img url } .header { width: 600px; margin: 0 auto; text-align: center; p { text-align: center; } } .more-info { margin-top: 20px; border: 1px dashed #8EB139; padding: 20px; background-color: #FFAA89; border-radius: 8px; h3 { color: white; } a { text-decoration: none; } ul li { line-height: 30px; } } .demo-container { margin-top: 30px; border: 1px dashed #8EB139; padding: 20px; background-color: #5B9EB2; border-radius: 8px; ol li p { color: #14581F; text-shadow: 2px 2px 2px #9A9A9A; } h3 { color: white; } } ================================================ FILE: package.json ================================================ { "name": "gulpman", "version": "2.0.0", "description": "Create Modular Front-End Build System. Based on gulp, very easy and light", "engines": { "node": ">=4.0.0" }, "main": "index.js", "scripts": { "test": "make test" }, "repository": { "type": "git", "url": "git+https://github.com/xunuoi/gulpman.git" }, "keywords": [ "gulp", "modular", "gulpman", "scss", "es6", "react", "jsx", "build", "easy", "fis", "component" ], "author": "Lucas X", "license": "MIT", "bugs": { "url": "https://github.com/xunuoi/gulpman/issues" }, "homepage": "https://github.com/xunuoi/gulpman#readme", "devDependencies": { "gulp": "^3.9.0" }, "dependencies": { "gulp-babel": "^6.1.2", "browserify": "^13.1.0", "stringify": "^5.1.0", "colors": "^1.1.2", "event-stream": "^3.3.2", "globby": "^6.0.0", "gulp-cssnano": "^2.1.2", "gulp-imagemin": "^3.0.2", "gulp-load-plugins": "^1.2.4", "gulp-concat": "^2.6.0", "gulp-rename": "^1.2.2", "gulp-rev-all": "^0.9.7", "gulp-sequence": "^0.4.4", "gulp-uglify": "^2.0.0", "gulp-sourcemaps": "^1.6.0", "imagemin-pngquant": "^5.0.0", "readable-stream": "^2.0.5", "object-assign": "^4.0.1", "shelljs": "^0.5.3", "through2": "^2.0.1", "vinyl-buffer": "^1.0.0", "vinyl-source-stream": "^1.1.0", "gulp-util": "^3.0.7", "jsmin2": "^1.2.1", "uglifycss": "0.0.20", "bluebird": "^3.4.1", "css": "^2.2.1", "extend": "^3.0.0", "fs-extra": "^0.30.0", "spritesmith": "^2.0.1" } } ================================================ FILE: presetlib/jquery.js ================================================ /*! * jQuery JavaScript Library v2.1.4 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2015-04-28T16:01Z */ (function( global, factory ) { if (false && typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper `window` // is present, execute the factory and get jQuery. // For environments that do not have a `window` with a `document` // (such as Node.js), expose a factory as module.exports. // This accentuates the need for the creation of a real `window`. // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info. module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Support: Firefox 18+ // Can't be in strict mode, several libs including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // var arr = []; var slice = arr.slice; var concat = arr.concat; var push = arr.push; var indexOf = arr.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var support = {}; var // Use the correct document accordingly with window argument (sandbox) document = window.document, version = "2.1.4", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // Support: Android<4.1 // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num != null ? // Return just the one element from the set ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return all the elements in a clean array slice.call( this ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: arr.sort, splice: arr.splice }; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // Skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // Extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { // parseFloat NaNs numeric-cast false positives (null|true|false|"") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN // adding 1 corrects loss of precision from parseFloat (#15100) return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0; }, isPlainObject: function( obj ) { // Not plain objects: // - Any object or value whose internal [[Class]] property is not "[object Object]" // - DOM nodes // - window if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } if ( obj.constructor && !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { return false; } // If the function hasn't returned already, we're confident that // |obj| is a plain object, created by {} or constructed with new Object return true; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, type: function( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android<4.0, iOS<6 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call(obj) ] || "object" : typeof obj; }, // Evaluates a script in a global context globalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf("use strict") === 1 ) { script = document.createElement("script"); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect global eval indirect( code ); } } }, // Convert dashed to camelCase; used by the css and data modules // Support: IE9-11+ // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Support: Android<4.1 trim: function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their new values if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, now: Date.now, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { // Support: iOS 8.2 (not reproducible in simulator) // `in` check used to prevent JIT error (gh-2145) // hasOwn isn't used here due to false negatives // regarding Nodelist length in IE var length = "length" in obj && obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v2.2.0-pre * http://sizzlejs.com/ * * Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-12-16 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // General-purpose constants MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // http://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + characterEncoding + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; nodeType = context.nodeType; if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } if ( !seed && documentIsHTML ) { // Try to shortcut find operations when possible (e.g., not under DocumentFragment) if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document (jQuery #6963) if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType !== 1 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, parent, doc = node ? node.ownerDocument || node : preferredDoc; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; parent = doc.defaultView; // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent !== parent.top ) { // IE11 does not have attachEvent, so all must suffer if ( parent.addEventListener ) { parent.addEventListener( "unload", unloadHandler, false ); } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", unloadHandler ); } } /* Support tests ---------------------------------------------------------------------- */ documentIsHTML = !isXML( doc ); /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Support: IE<9 support.getElementsByClassName = rnative.test( doc.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [ m ] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 docElem.appendChild( div ).innerHTML = "" + ""; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( div.querySelectorAll("[msallowcapture^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.2+, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.7+ if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push("~="); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibing-combinator selector` fails if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push(".#.+[+~]"); } }); assert(function( div ) { // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( div.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch (e) {} } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); // Don't keep the element (issue #299) input[0] = null; return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (oldCache = outerCache[ dir ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements outerCache[ dir ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); // Avoid hanging onto element (issue #299) checkContext = null; return ret; } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context !== document && context; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( (selector = compiled.selector || selector) ); results = results || []; // Try to minimize operations if there is no seed and only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome 14-35+ // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = ""; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = ""; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) >= 0 ) !== not; }); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }; jQuery.fn.extend({ find: function( selector ) { var i, len = this.length, ret = [], self = this; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } }); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // A simple way to check for HTML strings // Prioritize #id over to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, init = jQuery.fn.init = function( selector, context ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // Option to run scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Support: Blackberry 4.6 // gEBID returns nodes no longer in the document (#6963) if ( elem && elem.parentNode ) { // Inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return typeof rootjQuery.ready !== "undefined" ? rootjQuery.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // Methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.extend({ dir: function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }, sibling: function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; } }); jQuery.fn.extend({ has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter(function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within the set index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // Index in selector if ( typeof elem === "string" ) { return indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { return this.pushStack( jQuery.unique( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return elem.contentDocument || jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.unique( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; }); var rnotwhite = (/\S+/g); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // Add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // If we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); // The deferred used on DOM ready var readyList; jQuery.fn.ready = function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }; jQuery.extend({ // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.triggerHandler ) { jQuery( document ).triggerHandler( "ready" ); jQuery( document ).off( "ready" ); } } }); /** * The ready event handler and self cleanup method */ function completed() { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); jQuery.ready(); } jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // We once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); } } return readyList.promise( obj ); }; // Kick off the DOM ready check even if the user does not jQuery.ready.promise(); // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, len = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < len; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : len ? fn( elems[0], key ) : emptyGet; }; /** * Determines whether an object can have data */ jQuery.acceptData = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any /* jshint -W018 */ return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }; function Data() { // Support: Android<4, // Old WebKit does not have Object.preventExtensions/freeze method, // return new empty object instead with no [[set]] accessor Object.defineProperty( this.cache = {}, 0, { get: function() { return {}; } }); this.expando = jQuery.expando + Data.uid++; } Data.uid = 1; Data.accepts = jQuery.acceptData; Data.prototype = { key: function( owner ) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return the key for a frozen object. if ( !Data.accepts( owner ) ) { return 0; } var descriptor = {}, // Check if the owner object already has a cache key unlock = owner[ this.expando ]; // If not, create one if ( !unlock ) { unlock = Data.uid++; // Secure it in a non-enumerable, non-writable property try { descriptor[ this.expando ] = { value: unlock }; Object.defineProperties( owner, descriptor ); // Support: Android<4 // Fallback to a less secure definition } catch ( e ) { descriptor[ this.expando ] = unlock; jQuery.extend( owner, descriptor ); } } // Ensure the cache object if ( !this.cache[ unlock ] ) { this.cache[ unlock ] = {}; } return unlock; }, set: function( owner, data, value ) { var prop, // There may be an unlock assigned to this node, // if there is no entry for this "owner", create one inline // and set the unlock as though an owner entry had always existed unlock = this.key( owner ), cache = this.cache[ unlock ]; // Handle: [ owner, key, value ] args if ( typeof data === "string" ) { cache[ data ] = value; // Handle: [ owner, { properties } ] args } else { // Fresh assignments by object are shallow copied if ( jQuery.isEmptyObject( cache ) ) { jQuery.extend( this.cache[ unlock ], data ); // Otherwise, copy the properties one-by-one to the cache object } else { for ( prop in data ) { cache[ prop ] = data[ prop ]; } } } return cache; }, get: function( owner, key ) { // Either a valid cache is found, or will be created. // New caches will be created and the unlock returned, // allowing direct access to the newly created // empty data object. A valid owner object must be provided. var cache = this.cache[ this.key( owner ) ]; return key === undefined ? cache : cache[ key ]; }, access: function( owner, key, value ) { var stored; // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ((key && typeof key === "string") && value === undefined) ) { stored = this.get( owner, key ); return stored !== undefined ? stored : this.get( owner, jQuery.camelCase(key) ); } // [*]When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, name, camel, unlock = this.key( owner ), cache = this.cache[ unlock ]; if ( key === undefined ) { this.cache[ unlock ] = {}; } else { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = key.concat( key.map( jQuery.camelCase ) ); } else { camel = jQuery.camelCase( key ); // Try the string as a key before any manipulation if ( key in cache ) { name = [ key, camel ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [ name ] : ( name.match( rnotwhite ) || [] ); } } i = name.length; while ( i-- ) { delete cache[ name[ i ] ]; } } }, hasData: function( owner ) { return !jQuery.isEmptyObject( this.cache[ owner[ this.expando ] ] || {} ); }, discard: function( owner ) { if ( owner[ this.expando ] ) { delete this.cache[ owner[ this.expando ] ]; } } }; var data_priv = new Data(); var data_user = new Data(); // Implementation Summary // // 1. Enforce API surface and semantic compatibility with 1.9.x branch // 2. Improve the module's maintainability by reducing the storage // paths to a single mechanism. // 3. Use the same single mechanism to support "private" and "user" data. // 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) // 5. Avoid exposing implementation details on user objects (eg. expando properties) // 6. Provide a clear path for implementation upgrade to WeakMap in 2014 var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /([A-Z])/g; function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later data_user.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend({ hasData: function( elem ) { return data_user.hasData( elem ) || data_priv.hasData( elem ); }, data: function( elem, name, data ) { return data_user.access( elem, name, data ); }, removeData: function( elem, name ) { data_user.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to data_priv methods, these can be deprecated. _data: function( elem, name, data ) { return data_priv.access( elem, name, data ); }, _removeData: function( elem, name ) { data_priv.remove( elem, name ); } }); jQuery.fn.extend({ data: function( key, value ) { var i, name, data, elem = this[ 0 ], attrs = elem && elem.attributes; // Gets all values if ( key === undefined ) { if ( this.length ) { data = data_user.get( elem ); if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE11+ // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } } data_priv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { data_user.set( this, key ); }); } return access( this, function( value ) { var data, camelKey = jQuery.camelCase( key ); // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // with the key as-is data = data_user.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to get data from the cache // with the key camelized data = data_user.get( elem, camelKey ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, camelKey, undefined ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each(function() { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = data_user.get( this, camelKey ); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* data_user.set( this, camelKey, value ); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if ( key.indexOf("-") !== -1 && data !== undefined ) { data_user.set( this, key, value ); } }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { data_user.remove( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = data_priv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = data_priv.access( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // Clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // Not public - generate a queueHooks object, or return the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return data_priv.get( elem, key ) || data_priv.access( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { data_priv.remove( elem, [ type + "queue", key ] ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // Ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = data_priv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHidden = function( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); }; var rcheckableType = (/^(?:checkbox|radio)$/i); (function() { var fragment = document.createDocumentFragment(), div = fragment.appendChild( document.createElement( "div" ) ), input = document.createElement( "input" ); // Support: Safari<=5.1 // Check state lost if the name is set (#11217) // Support: Windows Web Apps (WWA) // `name` and `type` must use .setAttribute for WWA (#14901) input.setAttribute( "type", "radio" ); input.setAttribute( "checked", "checked" ); input.setAttribute( "name", "t" ); div.appendChild( input ); // Support: Safari<=5.1, Android<4.2 // Older WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<=11+ // Make sure textarea (and checkbox) defaultValue is properly cloned div.innerHTML = ""; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; })(); var strundefined = typeof undefined; support.focusinBubbles = "onfocusin" in window; var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply( elem, arguments ) : undefined; }; } // Handle multiple events separated by a space types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.hasData( elem ) && data_priv.get( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; data_priv.remove( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && jQuery.acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, j, ret, matched, handleObj, handlerQueue = [], args = slice.call( arguments ), handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or 2) have namespace(s) // a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if ( !event.target ) { event.target = document; } // Support: Safari 6.0+, Chrome<28 // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && // Support: Android<4.0 src.returnValue === false ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && e.preventDefault ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && e.stopPropagation ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && e.stopImmediatePropagation ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks // Support: Chrome 15+ jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // Support: Firefox, Chrome, Safari // Create "bubbling" focus and blur events if ( !support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = data_priv.access( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } data_priv.access( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = data_priv.access( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); data_priv.remove( doc, fix ); } else { data_priv.access( doc, fix, attaches ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { // Support: IE9 option: [ 1, "" ], thead: [ 1, "", "
" ], col: [ 2, "", "
" ], tr: [ 2, "", "
" ], td: [ 3, "", "
" ], _default: [ 0, "", "" ] }; // Support: IE9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // Support: 1.x compatibility // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var i = 0, l = elems.length; for ( ; i < l; i++ ) { data_priv.set( elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( data_priv.hasData( src ) ) { pdataOld = data_priv.access( src ); pdataCur = data_priv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( data_user.hasData( src ) ) { udataOld = data_user.access( src ); udataCur = jQuery.extend( {}, udataOld ); data_user.set( dest, udataCur ); } } function getAll( context, tag ) { var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Fix IE bugs, see support tests function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Fix IE cloning issues if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var elem, tmp, tag, wrap, contains, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: QtWebKit, PhantomJS // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1>" ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: QtWebKit, PhantomJS // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Ensure the created nodes are orphaned (#12392) tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; }, cleanData: function( elems ) { var data, elem, type, key, special = jQuery.event.special, i = 0; for ( ; (elem = elems[ i ]) !== undefined; i++ ) { if ( jQuery.acceptData( elem ) ) { key = elem[ data_priv.expando ]; if ( key && (data = data_priv.cache[ key ]) ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } if ( data_priv.cache[ key ] ) { // Discard any remaining `private` data delete data_priv.cache[ key ]; } } } // Discard any remaining `user` data delete data_user.cache[ elem[ data_user.expando ] ]; } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().each(function() { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.textContent = value; } }); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1>" ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because push.apply(_, arraylike) throws push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); var iframe, elemdisplay = {}; /** * Retrieve the actual display of a element * @param {String} name nodeName of the element * @param {Object} doc Document object */ // Called only from within defaultDisplay function actualDisplay( name, doc ) { var style, elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), // getDefaultComputedStyle might be reliably used only on attached element display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? // Use of this method is a temporary fix (more like optimization) until something better comes along, // since it was removed from specification and supported only in FF style.display : jQuery.css( elem[ 0 ], "display" ); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; } /** * Try to determine the default display value of an element * @param {String} nodeName */ function defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = (iframe || jQuery( "