├── .editorconfig
├── .eslintignore
├── .eslintrc.js
├── .gitignore
├── .npmignore
├── .prettierrc
├── README.md
├── bin
├── rc-tools-run.js
└── rc-tools.js
├── config
├── .prettierrc
├── eslintrc.js
├── tsconfig.json
└── tslint.json
├── lib
├── FileSizeReporter.js
├── checkDep.js
├── cli
│ ├── index.js
│ └── run.js
├── constants.js
├── genStorybook.js
├── getAutoprefixer.js
├── getBabelCommonConfig.js
├── getNpm.js
├── getTSCommonConfig.js
├── getWebpackCommonConfig.js
├── getWebpackConfig.js
├── gulpTasks
│ ├── cleanTasks.js
│ ├── pageTasks.js
│ └── util.js
├── gulpfile.js
├── init.js
├── initStoryConfigJs.js
├── postcssConfig.js
├── replaceLib.js
├── resolveCwd.js
├── server
│ ├── index.js
│ ├── js2html.js
│ └── packageUtil.js
├── storybook
│ ├── addons.js
│ ├── config.js
│ ├── manager-head.html
│ ├── preview-head.html
│ └── webpack.config.js
├── tests
│ ├── setup.js
│ ├── ts-jest.config.js
│ └── tsconfig.test.json
└── util.js
├── package.json
├── public
├── change.svg
├── favicon.ico
├── modernizr.js
├── out.svg
├── padding.svg
├── qrcode.js
└── qrcode.svg
├── scripts
├── checkDep.js
├── debugJestPreprocessor.js
├── jestPreprocessor.js
└── update.sh
└── views
└── js2html.xtpl
/.editorconfig:
--------------------------------------------------------------------------------
1 | # top-most EditorConfig file
2 | root = true
3 |
4 | # Unix-style newlines with a newline ending every file
5 | [*.{js,css}]
6 | end_of_line = lf
7 | insert_final_newline = true
8 | indent_style = space
9 | indent_size = 2
10 |
--------------------------------------------------------------------------------
/.eslintignore:
--------------------------------------------------------------------------------
1 | lib/server/js2html.js
--------------------------------------------------------------------------------
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | extends: ['airbnb', 'prettier'],
3 | rules: {
4 | 'arrow-body-style': 0,
5 | strict: 0,
6 | 'no-console': 0,
7 | 'func-names': 0,
8 | 'space-before-function-paren': 0,
9 | 'no-param-reassign': 0,
10 | 'import/no-dynamic-require': 0,
11 | 'global-require': 0,
12 | 'consistent-return': 0,
13 | },
14 | };
15 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | *.log
3 | *.log.*
4 | .idea/
5 | .ipr
6 | .iws
7 | *~
8 | ~*
9 | *.diff
10 | *.patch
11 | *.bak
12 | .DS_Store
13 | Thumbs.db
14 | .project
15 | .*proj
16 | .svn/
17 | *.swp
18 | *.swo
19 | *.pyc
20 | *.pyo
21 | .build
22 | node_modules
23 | _site
24 | sea-modules
25 | spm_modules
26 | .cache
27 | dist
28 | tests/*.css
29 | yarn.lock
30 | .vscode
31 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | bower_components/
2 | *.cfg
3 | node_modules/
4 | nohup.out
5 | *.iml
6 | .idea/
7 | .ipr
8 | .iws
9 | *~
10 | ~*
11 | *.diff
12 | *.log
13 | *.patch
14 | *.bak
15 | .DS_Store
16 | Thumbs.db
17 | .project
18 | .*proj
19 | .svn/
20 | *.swp
21 | out/
22 | .build
23 | node_modules
24 | _site
25 | sea-modules
26 | spm_modules
27 | .cache
28 | dist
29 | tests/*.css
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "singleQuote": true,
3 | "trailingComma": "es5",
4 | "printWidth": 100,
5 | "overrides": [
6 | {
7 | "files": ".prettierrc",
8 | "options": { "parser": "json" }
9 | }
10 | ]
11 | }
12 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # rc-tools
2 |
3 | offline tools for react component
4 |
5 | [![NPM version][npm-image]][npm-url]
6 | [![gemnasium deps][gemnasium-image]][gemnasium-url]
7 | [![node version][node-image]][node-url]
8 | [![npm download][download-image]][download-url]
9 | [![david-dm][david-image]][david-url]
10 |
11 | [npm-image]: http://img.shields.io/npm/v/rc-tools.svg?style=flat-square
12 | [npm-url]: http://npmjs.org/package/rc-tools
13 | [travis-image]: https://img.shields.io/travis/react-component/rc-tools.svg?style=flat-square
14 | [travis-url]: https://travis-ci.org/react-component/rc-tools
15 | [coveralls-image]: https://img.shields.io/coveralls/react-component/rc-tools.svg?style=flat-square
16 | [coveralls-url]: https://coveralls.io/r/react-component/rc-tools?branch=master
17 | [gemnasium-image]: http://img.shields.io/gemnasium/react-component/rc-tools.svg?style=flat-square
18 | [gemnasium-url]: https://gemnasium.com/react-component/rc-tools
19 | [node-image]: https://img.shields.io/badge/node.js-%3E=_0.11-green.svg?style=flat-square
20 | [node-url]: http://nodejs.org/download/
21 | [download-image]: https://img.shields.io/npm/dm/rc-tools.svg?style=flat-square
22 | [download-url]: https://npmjs.org/package/rc-tools
23 | [david-image]: https://david-dm.org/react-component/rc-tools.svg
24 | [david-url]: https://david-dm.org/react-component/rc-tools
25 |
26 | ## Usage
27 |
28 | ```
29 | $ rc-tools run lint: run lint by https://github.com/airbnb/javascript
30 | $ rc-tools run pub: compile and npm publish
31 | $ rc-tools run watch --out-dir=/xx: watch and compile to /xx, default to lib
32 | $ rc-tools run build: build examples
33 | $ rc-tools run gh-pages: push example to gh-pages
34 | $ rc-tools run start: start dev server
35 | ```
36 |
37 |
38 | package.json demo
39 |
40 | ```js
41 | ({
42 | config: {
43 | entry:{}, // webpack entry for build dist umd
44 | port: 8000, // dev server port
45 | output:{}, // webpack output for build dist umd
46 | }
47 | })
48 | ```
49 |
50 | ## History
51 |
52 | ### 9.0.0
53 |
54 | - upgrade all deps
55 | - add `test` task
56 |
57 | ### 8.0.0
58 |
59 | - upgrade eslint to the latest version
60 | - introduce prettier
61 |
62 | ### 7.0.0
63 |
64 | - upgrade to webpack3
65 |
66 | ### 6.0.0
67 |
68 | - move test to rc-test
69 |
--------------------------------------------------------------------------------
/bin/rc-tools-run.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env node
2 | require('../lib/cli/run');
3 |
--------------------------------------------------------------------------------
/bin/rc-tools.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env node
2 |
3 | require('../lib/cli/');
4 |
--------------------------------------------------------------------------------
/config/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "singleQuote": true,
3 | "trailingComma": "all",
4 | "printWidth": 100,
5 | "overrides": [
6 | {
7 | "files": ".prettierrc",
8 | "options": { "parser": "json" }
9 | }
10 | ]
11 | }
12 |
--------------------------------------------------------------------------------
/config/eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | extends: ['airbnb', 'prettier', 'prettier/react'],
3 | parser: 'babel-eslint',
4 | rules: {
5 | strict: 0,
6 | 'no-param-reassign': 0,
7 | 'arrow-body-style': 0,
8 | 'id-length': 0,
9 | 'import/no-extraneous-dependencies': 0,
10 | 'import/no-unresolved': 0,
11 | 'import/extensions': 0,
12 | 'no-underscore-dangle': 0,
13 | 'react/jsx-filename-extension': 0,
14 | 'react/require-default-props': 0,
15 | 'react/forbid-prop-types': 0,
16 | 'react/no-unused-prop-types': 0,
17 | 'no-plusplus': 0,
18 | 'no-bitwise': [2, { allow: ['~'] }],
19 | 'jsx-a11y/no-static-element-interactions': 0,
20 | 'jsx-a11y/anchor-has-content': 0,
21 | 'jsx-a11y/click-events-have-key-events': 0,
22 | 'jsx-a11y/anchor-is-valid': 0,
23 | 'jsx-a11y/label-has-for': 0,
24 | 'prefer-destructuring': 0,
25 | 'no-class-assign': 0,
26 | 'react/no-array-index-key': 0,
27 | 'react/no-find-dom-node': 0,
28 | },
29 | globals: {
30 | expect: true,
31 | document: true,
32 | window: true,
33 | },
34 | env: {
35 | jest: true,
36 | node: true,
37 | mocha: true,
38 | },
39 | };
40 |
--------------------------------------------------------------------------------
/config/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "declaration": true,
4 | "strict": true,
5 | "outDir": "build/dist",
6 | "module": "esnext",
7 | "target": "es2016",
8 | "lib": ["es6", "dom"],
9 | "sourceMap": true,
10 | "jsx": "react",
11 | "allowSyntheticDefaultImports": true,
12 | "moduleResolution": "node",
13 | "rootDirs": ["./src", "./typings"],
14 | "forceConsistentCasingInFileNames": true,
15 | "noImplicitReturns": true,
16 | "suppressImplicitAnyIndexErrors": true,
17 | "noUnusedLocals": true,
18 | "allowJs": false,
19 | "noImplicitThis": false,
20 | "experimentalDecorators": true
21 | },
22 | "include": ["./src", "./typings/"],
23 | "typings": "./typings/index.d.ts",
24 | "exclude": [
25 | "node_modules",
26 | "build",
27 | "scripts",
28 | "acceptance-tests",
29 | "webpack",
30 | "jest",
31 | "src/setupTests.ts",
32 | "tslint:latest",
33 | "tslint-config-prettier"
34 | ]
35 | }
36 |
--------------------------------------------------------------------------------
/config/tslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": ["tslint:latest", "tslint-react", "tslint-config-prettier"],
3 | "rules": {
4 | "no-var-requires": false,
5 | "no-submodule-imports": false,
6 | "object-literal-sort-keys": false,
7 | "jsx-no-lambda": false,
8 | "no-implicit-dependencies": false,
9 | "no-console": false,
10 | "interface-name": false
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/lib/FileSizeReporter.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015-present, Facebook, Inc.
3 | * All rights reserved.
4 | *
5 | * This source code is licensed under the BSD-style license found in the
6 | * LICENSE file in the root directory of this source tree. An additional grant
7 | * of patent rights can be found in the PATENTS file in the same directory.
8 | */
9 |
10 | 'use strict';
11 |
12 | const fs = require('fs');
13 | const path = require('path');
14 | const chalk = require('chalk');
15 | const filesize = require('filesize');
16 | const recursive = require('recursive-readdir');
17 | const stripAnsi = require('strip-ansi');
18 | const gzipSize = require('gzip-size').sync;
19 |
20 | /* eslint prefer-template:0 */
21 |
22 | function removeFileNameHash(buildFolder, fileName) {
23 | return fileName.replace(buildFolder, '');
24 | }
25 |
26 | // Input: 1024, 2048
27 | // Output: "(+1 KB)"
28 | function getDifferenceLabel(currentSize, previousSize) {
29 | const FIFTY_KILOBYTES = 1024 * 50;
30 | const difference = currentSize - previousSize;
31 | const fileSize = !Number.isNaN(difference) ? filesize(difference) : 0;
32 | if (difference >= FIFTY_KILOBYTES) {
33 | return chalk.red('+' + fileSize);
34 | } if (difference < FIFTY_KILOBYTES && difference > 0) {
35 | return chalk.yellow('+' + fileSize);
36 | } if (difference < 0) {
37 | return chalk.green(fileSize);
38 | }
39 | return '';
40 | }
41 |
42 | function measureFileSizesBeforeBuild(buildFolder) {
43 | return new Promise(resolve => {
44 | recursive(buildFolder, (err, fileNames) => {
45 | let sizes;
46 | if (!err && fileNames) {
47 | sizes = fileNames
48 | .filter(fileName => /\.(js|css)$/.test(fileName))
49 | .reduce((memo, fileName) => {
50 | const contents = fs.readFileSync(fileName);
51 | const key = removeFileNameHash(buildFolder, fileName);
52 | memo[key] = gzipSize(contents);
53 | return memo;
54 | }, {});
55 | }
56 | resolve({
57 | root: buildFolder,
58 | sizes: sizes || {},
59 | });
60 | });
61 | });
62 | }
63 |
64 | // Prints a detailed summary of build files.
65 | function printFileSizesAfterBuild(
66 | webpackStats,
67 | previousSizeMap,
68 | buildFolder,
69 | maxBundleGzipSize,
70 | maxChunkGzipSize
71 | ) {
72 | const { root, sizes } = previousSizeMap;
73 | const stats = webpackStats.toJson();
74 | let assets = [];
75 | if (stats.children) {
76 | stats.children.forEach(c => {
77 | assets = assets.concat(c.assets);
78 | });
79 | } else {
80 | assets = stats.assets || [];
81 | }
82 | assets = assets.filter(asset => /\.(js|css)$/.test(asset.name)).map(asset => {
83 | const fileContents = fs.readFileSync(path.join(root, asset.name));
84 | const size = gzipSize(fileContents);
85 | const previousSize = sizes[removeFileNameHash(root, asset.name)];
86 | const difference = getDifferenceLabel(size, previousSize);
87 | return {
88 | folder: path.join(path.basename(buildFolder), path.dirname(asset.name)),
89 | name: path.basename(asset.name),
90 | size,
91 | sizeLabel: filesize(size) + (difference ? ' (' + difference + ')' : ''),
92 | };
93 | });
94 | assets.sort((a, b) => b.size - a.size);
95 | const longestSizeLabelLength = Math.max.apply(
96 | null,
97 | assets.map(a => stripAnsi(a.sizeLabel).length)
98 | );
99 | let suggestBundleSplitting = false;
100 | assets.forEach(asset => {
101 | let { sizeLabel } = asset;
102 | const sizeLength = stripAnsi(sizeLabel).length;
103 | if (sizeLength < longestSizeLabelLength) {
104 | const rightPadding = ' '.repeat(longestSizeLabelLength - sizeLength);
105 | sizeLabel += rightPadding;
106 | }
107 | const isMainBundle = asset.name.indexOf('main.') === 0;
108 | const maxRecommendedSize = isMainBundle ? maxBundleGzipSize : maxChunkGzipSize;
109 | const isLarge = maxRecommendedSize && asset.size > maxRecommendedSize;
110 | if (isLarge && path.extname(asset.name) === '.js') {
111 | suggestBundleSplitting = true;
112 | }
113 | console.log(
114 | ' ' +
115 | (isLarge ? chalk.yellow(sizeLabel) : sizeLabel) +
116 | ' ' +
117 | chalk.dim(asset.folder + path.sep) +
118 | chalk.cyan(asset.name)
119 | );
120 | });
121 | if (suggestBundleSplitting) {
122 | console.log();
123 | console.log(chalk.yellow('The bundle size is significantly larger than recommended.'));
124 | console.log(chalk.yellow('Consider reducing it with code splitting: https://goo.gl/9VhYWB'));
125 | console.log(
126 | chalk.yellow('You can also analyze the project dependencies: https://goo.gl/LeUzfb')
127 | );
128 | }
129 | }
130 |
131 | module.exports = {
132 | measureFileSizesBeforeBuild,
133 | printFileSizesAfterBuild,
134 | };
135 |
--------------------------------------------------------------------------------
/lib/checkDep.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const matchRequire = require('match-require');
4 | const glob = require('glob');
5 | const fs = require('fs');
6 | const path = require('path');
7 | const chalk = require('chalk');
8 |
9 | const resolveCwd = require('./resolveCwd');
10 |
11 | const pkg = require(resolveCwd('package.json'));
12 |
13 | const ignoreMods = {
14 | path: 1,
15 | 'react-native': 1,
16 | react: 1,
17 | 'react-dom': 1,
18 | 'react/addons': 1,
19 | };
20 |
21 | ignoreMods[pkg.name] = 1;
22 |
23 | function check(done, dir) {
24 | dir = dir || 'src';
25 | glob(`${dir}/**/*.@(js|jsx|ts|tsx)`, {}, (err, files) => {
26 | const errors = [];
27 | const codeDeps = {};
28 | files.forEach(file => {
29 | file = resolveCwd(file);
30 | const extname = path.extname(file);
31 | if (extname === '.js' || extname === '.jsx') {
32 | const ts = file.replace(/\.jsx?$/, '.ts');
33 | const tsx = file.replace(/\.jsx?$/, '.tsx');
34 | if (fs.existsSync(ts) || fs.existsSync(tsx)) {
35 | return;
36 | }
37 | }
38 | const content = fs.readFileSync(file, 'utf-8');
39 | let deps = matchRequire.findAll(content);
40 | deps = deps.filter(dep => {
41 | return !matchRequire.isRelativeModule(dep);
42 | });
43 | deps = deps.map(dep => {
44 | return matchRequire.splitPackageName(dep).packageName;
45 | });
46 | deps.forEach(dep => {
47 | codeDeps[dep] = 1;
48 | });
49 | });
50 |
51 | const pkgDeps = pkg.dependencies || {};
52 | const peerDeps = pkg.peerDependencies || {};
53 |
54 | const miss = [];
55 | const redundant = [];
56 |
57 | Object.keys(codeDeps).forEach(td => {
58 | if (!pkgDeps[td] && !peerDeps[td] && !ignoreMods[td]) {
59 | miss.push(td);
60 | }
61 | });
62 |
63 | Object.keys(pkgDeps).forEach(rd => {
64 | if (!codeDeps[rd] && rd !== 'babel-runtime') {
65 | redundant.push(rd);
66 | }
67 | });
68 |
69 | if (miss.length) {
70 | errors.push(`missing dependency in dependencies of package.json: ${miss.join(';')}`);
71 | }
72 |
73 | if (redundant.length) {
74 | errors.push(`redundant dependency in dependencies of package.json: ${redundant.join(';')}`);
75 | }
76 |
77 | errors.forEach((msg) => {
78 | console.log(chalk.red(msg));
79 | });
80 | done(errors.length);
81 | });
82 | }
83 |
84 | module.exports = check;
85 |
--------------------------------------------------------------------------------
/lib/cli/index.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env node
2 |
3 | 'use strict';
4 |
5 | const program = require('commander');
6 | const packageInfo = require('../../package.json');
7 |
8 | program
9 | .version(packageInfo.version)
10 | .command('run [name]', 'run specified task')
11 | .parse(process.argv);
12 |
13 | // https://github.com/tj/commander.js/pull/260
14 | const proc = program.runningCommand;
15 | if (proc) {
16 | proc.on('close', process.exit.bind(process));
17 | proc.on('error', () => {
18 | process.exit(1);
19 | });
20 | }
21 |
22 | process.on('SIGINT', () => {
23 | if (proc) {
24 | proc.kill('SIGKILL');
25 | }
26 | process.exit(0);
27 | });
28 |
29 | const subCmd = program.args[0];
30 | if (!subCmd || subCmd !== 'run') {
31 | program.help();
32 | }
33 |
--------------------------------------------------------------------------------
/lib/cli/run.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env node
2 |
3 | const program = require('commander');
4 |
5 | program.on('--help', () => {
6 | console.log(' Usage:'.to.bold.blue.color);
7 | console.log();
8 | console.log(' $', 'rc-tools run lint'.to.magenta.color, 'lint source within lib');
9 | console.log(' $', 'rc-tools run pub'.to.magenta.color, 'publish component');
10 | console.log(' $', 'rc-tools run server'.to.magenta.color, 'start server');
11 | console.log(' $', 'rc-tools run pretter'.to.magenta.color, 'pretter all code');
12 | console.log(
13 | ' $',
14 | 'rc-tools run init-eslint'.to.magenta.color,
15 | 'generate eslint configuration file'
16 | );
17 | console.log(
18 | ' $',
19 | 'rc-tools run init-tslint'.to.magenta.color,
20 | 'generate tslint configuration file'
21 | );
22 | console.log(' $', 'rc-tools run chrome-test'.to.magenta.color, 'run chrome tests');
23 | console.log();
24 | });
25 |
26 | program.parse(process.argv);
27 |
28 | function runTask(toRun) {
29 | const gulp = require('gulp');
30 | const metadata = { task: toRun };
31 | // Gulp >= 4.0.0 (doesn't support events)
32 | const taskInstance = gulp.task(toRun);
33 | if (taskInstance === undefined) {
34 | gulp.emit('task_not_found', metadata);
35 | return;
36 | }
37 | const start = process.hrtime();
38 | gulp.emit('task_start', metadata);
39 | try {
40 | taskInstance.apply(gulp);
41 | metadata.hrDuration = process.hrtime(start);
42 | gulp.emit('task_stop', metadata);
43 | gulp.emit('stop');
44 | } catch (err) {
45 | err.hrDuration = process.hrtime(start);
46 | err.task = metadata.task;
47 | gulp.emit('task_err', err);
48 | }
49 | }
50 |
51 | const task = program.args[0];
52 |
53 | if (!task) {
54 | program.help();
55 | } else if (task === 'server') {
56 | const port = process.env.npm_package_config_port || 8000;
57 | console.log(`Listening at http://localhost:${port}`);
58 | const app = require('../server/')();
59 | app.listen(port);
60 | } else {
61 | console.log('rc-tools run', task);
62 | require('../gulpfile');
63 | runTask(task);
64 | }
65 |
--------------------------------------------------------------------------------
/lib/constants.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | module.exports = {
4 | tsCompiledDir: '_ts2js',
5 | };
6 |
--------------------------------------------------------------------------------
/lib/genStorybook.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs-extra');
2 | const path = require('path');
3 | const glob = require('glob');
4 |
5 | /**
6 | * ReactDom.render(, document.getElementById('__react-content'));
7 | * to
8 | * export default ()=>
9 | */
10 | const replaceFileContent = (filePath) => {
11 | const regex = /[\s\S]*^(\S*\.render\(([\s\S]*), document\.getElementById\('__react-content'\)\);)/m;
12 | const content = fs.readFileSync(filePath, 'utf-8');
13 | // 有了 export default 说明已经是新版本的了直接放过
14 | if (content.includes('export default')) {
15 | return true;
16 | }
17 | const regexObj = content.match(regex);
18 | if (!regexObj) {
19 | return false;
20 | }
21 | const className = regexObj[2];
22 | const renderString = regexObj[1];
23 | if (!renderString || !className) {
24 | return false;
25 | }
26 | const newContent = content.replace(renderString, `export default ()=>${className}`);
27 |
28 | fs.writeFileSync(filePath, newContent);
29 | return true;
30 | };
31 |
32 | const genStorybook = (dir) => {
33 | const config = require(path.join(dir, './package.json'));
34 |
35 | const firstUpperCase = ([ first, ...rest ]) => first.toUpperCase() + rest.join('');
36 |
37 | // get all files
38 | const files = glob.sync(path.join(dir, './examples/*.js'), {});
39 |
40 | const importString = [];
41 | const importSourceString = [];
42 | const addString = [];
43 | const jsList = files.filter((filePath) => replaceFileContent(filePath)).map((fileName) => {
44 | return fileName.split('/').pop().replace('.js', '');
45 | });
46 |
47 | // single-animation => SingleAnimation
48 | jsList.forEach((fileName) => {
49 | const ComponentName = fileName.split('-').map((item) => firstUpperCase(item)).join('');
50 |
51 | importString.push(`import ${ComponentName} from '../examples/${fileName}';`);
52 | importSourceString.push(
53 | `import ${ComponentName}Source from 'rc-source-loader!../examples/${fileName}';`,
54 | );
55 |
56 | addString.push(`.add('${fileName}', () => <${ComponentName} />,{
57 | source: {
58 | code: ${ComponentName}Source,
59 | },
60 | })`);
61 | });
62 |
63 | const fileContent = `
64 | /* eslint-disable import/no-webpack-loader-syntax */
65 | import React from 'react';
66 | import Markdown from 'react-markdown';
67 | import { checkA11y } from '@storybook/addon-a11y';
68 | import { storiesOf } from '@storybook/react';
69 | import { withConsole } from '@storybook/addon-console';
70 | import { withViewport } from '@storybook/addon-viewport';
71 | import { withInfo } from '@storybook/addon-info';
72 | ${importSourceString.join('\n')}
73 | ${importString.join('\n')}
74 | import READMECode from '../README.md';
75 |
76 | storiesOf('${config.name}', module)
77 | .addDecorator(checkA11y)
78 | .addDecorator(withInfo)
79 | .addDecorator((storyFn, context) => withConsole()(storyFn)(context))
80 | .addDecorator(withViewport())
81 | .add(
82 | 'readMe',
83 | () => (
84 |
90 |
91 |
92 | ),
93 | {
94 | source: {
95 | code: READMECode,
96 | },
97 | },
98 | )
99 | ${addString.join('\n')}
100 | `;
101 | if (!fs.existsSync(path.join(dir, './storybook/'))) {
102 | fs.mkdir(path.join(dir, './storybook/'));
103 | }
104 | fs.writeFileSync(path.join(dir, './storybook/index.js'), fileContent);
105 | };
106 |
107 | module.exports = genStorybook;
108 |
--------------------------------------------------------------------------------
/lib/getAutoprefixer.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const autoprefixer = require('autoprefixer');
4 |
5 | module.exports = function() {
6 | return autoprefixer({
7 | remove: false,
8 | });
9 | };
10 |
--------------------------------------------------------------------------------
/lib/getBabelCommonConfig.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const argv = require('minimist')(process.argv.slice(2));
4 |
5 | module.exports = function(modules) {
6 | const plugins = [
7 | require.resolve('@babel/plugin-transform-member-expression-literals'),
8 | require.resolve('@babel/plugin-transform-object-assign'),
9 | require.resolve('@babel/plugin-transform-property-literals'),
10 | require.resolve('@babel/plugin-transform-spread'),
11 | require.resolve('@babel/plugin-transform-template-literals'),
12 | require.resolve('@babel/plugin-proposal-export-default-from'),
13 | require.resolve('@babel/plugin-proposal-export-namespace-from'),
14 | require.resolve('@babel/plugin-proposal-object-rest-spread'),
15 | require.resolve('@babel/plugin-proposal-class-properties'),
16 | ];
17 | if (argv['babel-runtime']) {
18 | plugins.push([
19 | require.resolve('@babel/plugin-transform-runtime'),
20 | {
21 | helpers: false,
22 | },
23 | ]);
24 | }
25 | return {
26 | presets: [
27 | [
28 | require.resolve('@babel/preset-env'),
29 | {
30 | modules,
31 | exclude: ['transform-typeof-symbol'],
32 | },
33 | ],
34 | require.resolve(`@babel/preset-react`),
35 | ],
36 | plugins,
37 | };
38 | };
39 |
--------------------------------------------------------------------------------
/lib/getNpm.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const { runCmd } = require('./util');
4 |
5 | module.exports = function(done) {
6 | if (process.env.NPM_CLI) {
7 | done(process.env.NPM_CLI);
8 | return;
9 | }
10 | runCmd('which', ['tnpm'], code => {
11 | let npm = 'npm';
12 | if (!code) {
13 | npm = 'tnpm';
14 | }
15 | done(npm);
16 | });
17 | };
18 |
--------------------------------------------------------------------------------
/lib/getTSCommonConfig.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const fs = require('fs');
4 | const path = require('path');
5 |
6 | const cwd = process.cwd();
7 |
8 | function getConfigFilePath() {
9 | return path.join(cwd, 'tsconfig.json');
10 | }
11 |
12 | function getTemplateConfigFilePath(fileName) {
13 | return path.join(__dirname, '..', 'config', fileName);
14 | }
15 |
16 | // get `compilerOptions`
17 | function getCompilerOptions() {
18 | const defaultConfig = require(getTemplateConfigFilePath('tsconfig.json'));
19 |
20 | let customizeConfig = {};
21 | if (fs.existsSync(getConfigFilePath())) {
22 | customizeConfig = require(getConfigFilePath()) || {};
23 | }
24 |
25 | return {
26 | ...defaultConfig.compilerOptions,
27 | ...customizeConfig.compilerOptions,
28 | };
29 | }
30 |
31 | function relativePath(subPath) {
32 | if (subPath[0] === '/') return subPath;
33 | return path.join(cwd, subPath);
34 | }
35 |
36 | // Provide `tsconfig.json` file path. If customize not exist, will create a tmp file for this.
37 | getCompilerOptions.getConfigFilePath = function() {
38 | if (fs.existsSync(getConfigFilePath())) {
39 | return getConfigFilePath();
40 | }
41 |
42 | const defaultConfig = require(getTemplateConfigFilePath('tsconfig.json'));
43 | const tmpConfigFilePath = getTemplateConfigFilePath('~tsconfig.json');
44 | const tmpConfig = {
45 | ...defaultConfig,
46 | include: (defaultConfig.include || []).map(relativePath),
47 |
48 | compilerOptions: {
49 | ...defaultConfig.compilerOptions,
50 | rootDirs: defaultConfig.compilerOptions.rootDirs.map(relativePath),
51 | },
52 | };
53 |
54 | fs.writeFileSync(tmpConfigFilePath, JSON.stringify(tmpConfig, null, 2));
55 |
56 | return tmpConfigFilePath;
57 | };
58 |
59 | module.exports = getCompilerOptions;
60 |
--------------------------------------------------------------------------------
/lib/getWebpackCommonConfig.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const path = require('path');
4 | const fs = require('fs');
5 | const MiniCssExtractPlugin = require("mini-css-extract-plugin");
6 | const assign = require('object-assign');
7 | const resolveCwd = require('./resolveCwd');
8 | const getBabelCommonConfig = require('./getBabelCommonConfig');
9 | const getTSCommonConfig = require('./getTSCommonConfig');
10 | const constants = require('./constants');
11 | const replaceLib = require('./replaceLib');
12 |
13 | const tsConfig = getTSCommonConfig();
14 |
15 | const pkg = require(resolveCwd('package.json'));
16 | const cwd = process.cwd();
17 |
18 | function getResolve() {
19 | const alias = {};
20 | const resolve = {
21 | modules: [cwd, 'node_modules'],
22 | extensions: ['.web.ts', '.web.tsx', '.web.js', '.web.jsx', '.ts', '.tsx', '.js', '.jsx'],
23 | alias,
24 | };
25 | const { name } = pkg;
26 |
27 | // https://github.com/react-component/react-component.github.io/issues/13
28 | // just for compatibility, we hope to delete /index.js. just use /src/index.js as all entry
29 | let pkgSrcMain = resolveCwd('index.js');
30 | if (!fs.existsSync(pkgSrcMain)) {
31 | pkgSrcMain = resolveCwd('src/index.js');
32 | if (!fs.existsSync(pkgSrcMain)) {
33 | console.error('Get webpack.resolve.alias error: no /index.js or /src/index.js exist !!');
34 | }
35 | }
36 |
37 | // resolve import { foo } from 'rc-component'
38 | // to 'rc-component/index.js' or 'rc-component/src/index.js'
39 | alias[`${name}$`] = pkgSrcMain;
40 |
41 | // resolve import foo from 'rc-component/lib/foo' to 'rc-component/src/foo.js'
42 | alias[`${name}/lib`] = resolveCwd('./src');
43 | alias[`${name}/${constants.tsCompiledDir}`] = cwd;
44 |
45 | alias[name] = cwd;
46 | return resolve;
47 | }
48 |
49 | const postcssLoader = {
50 | loader: 'postcss',
51 | options: { plugins: require('./postcssConfig') },
52 | };
53 |
54 | module.exports = {
55 | getResolve,
56 | getResolveLoader() {
57 | return {
58 | modules: [
59 | path.resolve(__dirname, '../node_modules'),
60 | // npm3 flat module
61 | path.resolve(__dirname, '../../'),
62 | ],
63 | moduleExtensions: ['-loader'],
64 | };
65 | },
66 | getLoaders(c) {
67 | const commonjs = c || false;
68 | const babelConfig = getBabelCommonConfig(commonjs);
69 | if (commonjs === false) {
70 | babelConfig.plugins.push(replaceLib);
71 | }
72 | const babelLoader = {
73 | loader: 'babel',
74 | options: babelConfig,
75 | };
76 | return [
77 | assign(
78 | {
79 | test: /\.jsx?$/,
80 | exclude: /node_modules/,
81 | },
82 | babelLoader
83 | ),
84 | {
85 | test: /\.svg$/,
86 | loader: 'svg-sprite',
87 | },
88 | {
89 | test: /\.tsx?$/,
90 | exclude: /node_modules/,
91 | use: [
92 | babelLoader,
93 | {
94 | loader: 'ts',
95 | options: {
96 | transpileOnly: true,
97 | configFile: getTSCommonConfig.getConfigFilePath(),
98 | compilerOptions: tsConfig,
99 | },
100 | },
101 | ],
102 | },
103 | // Needed for the css-loader when [bootstrap-webpack](https://github.com/bline/bootstrap-webpack)
104 | // loads bootstrap's css.
105 | {
106 | test: /\.woff2?(\?v=\d+\.\d+\.\d+)?$/,
107 | loader: 'url',
108 | options: {
109 | limit: 10000,
110 | minetype: 'application/font-woff',
111 | },
112 | },
113 | {
114 | test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
115 | loader: 'url',
116 | options: {
117 | limit: 10000,
118 | minetype: 'application/octet-stream',
119 | },
120 | },
121 | {
122 | test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
123 | loader: 'file',
124 | },
125 | {
126 | test: /\.(png|jpg|jpeg|webp)$/i,
127 | loader: 'file',
128 | },
129 | ];
130 | },
131 | getCssLoaders(extractCss) {
132 | let cssLoader = [
133 | {
134 | loader: 'css',
135 | options: {
136 | importLoaders: 1,
137 | sourceMap: true,
138 | },
139 | },
140 | postcssLoader,
141 | ];
142 | let lessLoader = cssLoader.concat([
143 | {
144 | loader: 'less',
145 | options: {
146 | sourceMap: true,
147 | },
148 | },
149 | ]);
150 | if (extractCss) {
151 | cssLoader = [MiniCssExtractPlugin.loader].concat(cssLoader);
152 | lessLoader = [MiniCssExtractPlugin.loader].concat(lessLoader);
153 | } else {
154 | const styleLoader = {
155 | loader: 'style',
156 | };
157 | cssLoader.unshift(styleLoader);
158 | lessLoader.unshift(styleLoader);
159 | }
160 | return [
161 | {
162 | test: /\.css$/,
163 | use: cssLoader,
164 | },
165 | {
166 | test: /\.less$/,
167 | use: lessLoader,
168 | },
169 | ];
170 | },
171 | };
172 |
--------------------------------------------------------------------------------
/lib/getWebpackConfig.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const path = require('path');
4 | const fs = require('fs-extra');
5 | const ProgressBarPlugin = require('progress-bar-webpack-plugin');
6 | const MiniCssExtractPlugin = require('mini-css-extract-plugin');
7 | const getWebpackCommonConfig = require('./getWebpackCommonConfig');
8 |
9 | function getEntry() {
10 | // eslint-disable-next-line no-use-before-define
11 | const exampleDir = resolveCwd('examples');
12 | const files = fs.readdirSync(exampleDir);
13 | const entry = {};
14 | files.forEach(file => {
15 | const extname = path.extname(file);
16 | const name = path.basename(file, extname);
17 | if (extname === '.js' || extname === '.jsx' || extname === '.tsx' || extname === '.ts') {
18 | const htmlFile = path.join(exampleDir, `${name}.html`);
19 | if (fs.existsSync(htmlFile)) {
20 | entry[`examples/${name}`] = [`./examples/${file}`];
21 | }
22 | }
23 | });
24 | return entry;
25 | }
26 |
27 | const resolveCwd = require('./resolveCwd');
28 |
29 | module.exports = ({ common, inlineSourceMap, prod }) => {
30 | const plugins = [new ProgressBarPlugin()];
31 | plugins.push(new MiniCssExtractPlugin());
32 |
33 | const config = {
34 | mode: prod ? 'production' : 'development',
35 | devtool: inlineSourceMap ? '#inline-source-map' : '#source-map',
36 |
37 | resolveLoader: getWebpackCommonConfig.getResolveLoader(),
38 |
39 | entry: getEntry(),
40 |
41 | output: {
42 | path: resolveCwd('build'),
43 | filename: '[name].js',
44 | },
45 |
46 | module: {
47 | noParse: [/moment.js/],
48 | rules: getWebpackCommonConfig.getLoaders().concat(getWebpackCommonConfig.getCssLoaders(true)),
49 | },
50 |
51 | resolve: getWebpackCommonConfig.getResolve(),
52 |
53 | plugins,
54 | };
55 |
56 | if (common) {
57 | config.optimization = {
58 | splitChunks: {
59 | cacheGroups: {
60 | commons: {
61 | name: 'common',
62 | chunks: 'initial',
63 | minChunks: 2,
64 | },
65 | },
66 | },
67 | };
68 | }
69 |
70 | return config;
71 | };
72 |
--------------------------------------------------------------------------------
/lib/gulpTasks/cleanTasks.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs');
2 | const shelljs = require('shelljs');
3 | const resolveCwd = require('../resolveCwd');
4 |
5 | function cleanCompile() {
6 | try {
7 | if (fs.existsSync(resolveCwd('lib'))) {
8 | shelljs.rm('-rf', resolveCwd('lib'));
9 | }
10 | if (fs.existsSync(resolveCwd('es'))) {
11 | shelljs.rm('-rf', resolveCwd('es'));
12 | }
13 | if (fs.existsSync(resolveCwd('assets'))) {
14 | shelljs.rm('-rf', resolveCwd('assets/*.css'));
15 | }
16 | } catch (err) {
17 | console.log('Clean up failed:', err);
18 | throw err;
19 | }
20 | }
21 |
22 | function cleanBuild() {
23 | if (fs.existsSync(resolveCwd('build'))) {
24 | shelljs.rm('-rf', resolveCwd('build'));
25 | }
26 | }
27 |
28 | function clean() {
29 | cleanCompile();
30 | cleanBuild();
31 | }
32 |
33 | function registerTasks(gulp) {
34 | gulp.task(
35 | 'clean',
36 | gulp.series(done => {
37 | clean();
38 | done();
39 | })
40 | );
41 |
42 | gulp.task(
43 | 'cleanCompile',
44 | gulp.series(done => {
45 | cleanCompile();
46 | done();
47 | })
48 | );
49 |
50 | gulp.task(
51 | 'cleanBuild',
52 | gulp.series(done => {
53 | cleanBuild();
54 | done();
55 | })
56 | );
57 | }
58 |
59 | registerTasks.cleanCompile = cleanCompile;
60 | registerTasks.cleanBuild = cleanBuild;
61 | registerTasks.clean = clean;
62 |
63 | module.exports = registerTasks;
64 |
--------------------------------------------------------------------------------
/lib/gulpTasks/pageTasks.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Page related functions
3 | * - build
4 | * - gh-pages
5 | */
6 |
7 | const jsx2example = require('gulp-jsx2example');
8 | const glob = require('glob');
9 | const fs = require('fs');
10 | const path = require('path');
11 | const shelljs = require('shelljs');
12 | const chalk = require('chalk');
13 | const webpack = require('webpack');
14 | const storybook = require('@storybook/react/standalone');
15 | const resolveCwd = require('../resolveCwd');
16 | const genStorybook = require('../genStorybook');
17 | const InitStoryConfigJs = require('../initStoryConfigJs');
18 | const getWebpackConfig = require('../getWebpackConfig');
19 |
20 | const projectPath = resolveCwd('./');
21 | const pkg = require(resolveCwd('package.json'));
22 |
23 | module.exports = function(gulp) {
24 | const { cleanBuild } = require('./cleanTasks');
25 | const { printResult } = require('./util');
26 |
27 | const isStorybook = !glob.sync('examples/*.html').length;
28 |
29 | // ====================== Webpack ======================
30 | function webpackJS() {
31 | return new Promise((resolve, reject) => {
32 | webpack(
33 | getWebpackConfig({
34 | common: true,
35 | }),
36 | (err, stats) => {
37 | if (err) {
38 | console.error('error', err);
39 | }
40 | printResult(stats);
41 | if (err) {
42 | reject(err);
43 | } else {
44 | resolve();
45 | }
46 | },
47 | );
48 | });
49 | }
50 |
51 | function webpackBuild(done) {
52 | console.log('[webpack] building...');
53 | if (!fs.existsSync(resolveCwd('./examples/'))) {
54 | console.log(chalk.red('😢 `examples` folder not exist. exit...'));
55 | done();
56 | return;
57 | }
58 |
59 | // Execute webpack
60 | webpackJS()
61 | .then(() => {
62 | // Merge files into build folder
63 | console.log('[webpack] Render HTML...');
64 | const dir = resolveCwd('./examples/');
65 | let files = fs.readdirSync(dir);
66 | files = files
67 | .filter((f) => f[0] !== '~') // Remove '~tmp' file
68 | .map((f) => path.join(dir, f));
69 | const filesMap = {};
70 | files.forEach((f) => {
71 | filesMap[f] = 1;
72 | });
73 | files.forEach((f) => {
74 | if (f.match(/\.tsx?$/)) {
75 | let js = f.replace(/\.tsx?$/, '.js');
76 | if (filesMap[js]) {
77 | delete filesMap[js];
78 | }
79 | js = f.replace(/\.tsx?$/, '.jsx');
80 | if (filesMap[js]) {
81 | delete filesMap[js];
82 | }
83 | }
84 | });
85 | gulp
86 | .src(Object.keys(filesMap))
87 | .pipe(
88 | jsx2example({
89 | dest: 'build/examples/',
90 | }),
91 | ) // jsx2example(options)
92 | .pipe(gulp.dest('build/examples/'))
93 | .on('finish', done);
94 | })
95 | .catch(done);
96 | }
97 |
98 | // ===================== Storybook =====================
99 | gulp.task('storybook', () => {
100 | // 生成 storybook 的配置文件
101 | genStorybook(projectPath);
102 |
103 | InitStoryConfigJs(projectPath, pkg);
104 | storybook({
105 | mode: 'dev',
106 | port: '9001',
107 | configDir: path.join(__dirname, '../storybook/'),
108 | });
109 | });
110 |
111 | function storybookBuild(done) {
112 | console.log('[storybook] building...');
113 |
114 | // 生成 storybook 的配置文件
115 | genStorybook(projectPath);
116 |
117 | InitStoryConfigJs(projectPath, pkg);
118 |
119 | storybook({
120 | mode: 'static',
121 | // 相对路径,storybook 会自动拼接 cmd 所在的位置
122 | outputDir: './build',
123 | configDir: path.join(__dirname, '../storybook/'),
124 | }).then(done);
125 | }
126 |
127 | gulp.task('storybook-build', (done) => {
128 | console.log(chalk.red('💩 `storybook-build` is removed. Use `build` directly!'));
129 | done('removed');
130 | });
131 | gulp.task('storybook-gh-pages', (done) => {
132 | console.log(chalk.red('💩 `storybook-gh-pages` is removed. Use `gh-pages` directly!'));
133 | done('removed');
134 | });
135 |
136 | // ====================== Export =======================
137 | gulp.task(
138 | 'build',
139 | gulp.series('cleanBuild', (done) => {
140 | if (isStorybook) {
141 | storybookBuild(done);
142 | } else {
143 | webpackBuild(done);
144 | }
145 | }),
146 | );
147 |
148 | gulp.task(
149 | 'gh-pages',
150 | gulp.series('build', (done) => {
151 | console.log('[storybook] gh-paging...');
152 | if (pkg.scripts['pre-gh-pages']) {
153 | shelljs.exec('npm run pre-gh-pages');
154 | }
155 | if (fs.existsSync(resolveCwd('./build/'))) {
156 | console.log(chalk.green('🏁 uploading...'));
157 | const ghPages = require('gh-pages');
158 | ghPages.publish(
159 | resolveCwd('build'),
160 | {
161 | logger(message) {
162 | console.log(message);
163 | },
164 | },
165 | () => {
166 | cleanBuild();
167 | console.log('gh-paged');
168 | done();
169 | },
170 | );
171 | } else {
172 | console.log(chalk.red('😢 `build` folder not exist. exit...'));
173 | done();
174 | }
175 | }),
176 | );
177 | };
178 |
--------------------------------------------------------------------------------
/lib/gulpTasks/util.js:
--------------------------------------------------------------------------------
1 | function printResult(stats) {
2 | if (stats.toJson) {
3 | stats = stats.toJson();
4 | }
5 |
6 | (stats.errors || []).forEach(err => {
7 | console.error('error', err);
8 | });
9 |
10 | stats.assets.forEach(item => {
11 | const size = `${(item.size / 1024.0).toFixed(2)}kB`;
12 | console.log('generated', item.name, size);
13 | });
14 | }
15 |
16 | module.exports = {
17 | printResult,
18 | };
--------------------------------------------------------------------------------
/lib/gulpfile.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const gulp = require('gulp');
4 | const path = require('path');
5 | const through2 = require('through2');
6 | const webpack = require('webpack');
7 | const shelljs = require('shelljs');
8 | const babel = require('gulp-babel');
9 | const fs = require('fs-extra');
10 | const argv = require('minimist')(process.argv.slice(2));
11 | const postcss = require('gulp-postcss');
12 | const chalk = require('chalk');
13 | const ts = require('gulp-typescript');
14 | const merge2 = require('merge2');
15 | const glob = require('glob');
16 | const watch = require('gulp-watch');
17 | const assign = require('object-assign');
18 | const targz = require('tar.gz');
19 | const request = require('request');
20 | const minify = require('gulp-babel-minify');
21 | const prettier = require('gulp-prettier');
22 |
23 | const resolveCwd = require('./resolveCwd');
24 | const getWebpackConfig = require('./getWebpackConfig');
25 | const { runCmd, getNpmArgs } = require('./util');
26 | const getBabelCommonConfig = require('./getBabelCommonConfig');
27 | const getNpm = require('./getNpm');
28 | const tsConfig = require('./getTSCommonConfig')();
29 | const { tsCompiledDir } = require('./constants');
30 | const { measureFileSizesBeforeBuild, printFileSizesAfterBuild } = require('./FileSizeReporter');
31 | const replaceLib = require('./replaceLib');
32 | const { printResult } = require('./gulpTasks/util');
33 | const genStorybook = require('./genStorybook');
34 | const selfPackage = require('../package.json');
35 |
36 | const pkg = require(resolveCwd('package.json'));
37 | const cwd = process.cwd();
38 | const lessPath = new RegExp(`(["']${pkg.name})/assets/([^.'"]+).less`, 'g');
39 | const tsDefaultReporter = ts.reporter.defaultReporter();
40 | const src = argv.src || 'src';
41 |
42 | const tsFiles = [
43 | `${src}/**/*.@(png|svg|less)`,
44 | `${src}/**/*.tsx`,
45 | 'examples/**/*.tsx',
46 | 'tests/**/*.tsx',
47 | 'typings/**/*.d.ts',
48 | ];
49 |
50 | const mockRcTrigger = `
51 | import React from 'react';
52 |
53 | let Trigger;
54 |
55 | const ActualTrigger = require.requireActual('rc-trigger');
56 | const render = ActualTrigger.prototype.render;
57 |
58 | ActualTrigger.prototype.render = function () {
59 | const { popupVisible } = this.state;
60 | let component;
61 |
62 | if (popupVisible || this._component) {
63 | component = this.getComponent();
64 | }
65 |
66 | return (
67 |
68 | {render.call(this)}
69 | {component}
70 |
71 | );
72 | };
73 | Trigger = ActualTrigger;
74 |
75 | export default Trigger;
76 | `;
77 |
78 | const mockRcPortal = `
79 | import React from 'react';
80 |
81 | export default class Portal extends React.Component {
82 | componentDidMount() {
83 | this.createContainer();
84 | }
85 |
86 | createContainer() {
87 | this.container = true;
88 | this.forceUpdate();
89 | }
90 |
91 | render() {
92 | const { children } = this.props;
93 | if (this.container) {
94 | return children;
95 | }
96 | return null;
97 | }
98 | }
99 | `;
100 |
101 | // ============================== Clean ==============================
102 | const cleanTasks = require('./gulpTasks/cleanTasks');
103 |
104 | const { cleanCompile } = cleanTasks;
105 |
106 | cleanTasks(gulp);
107 |
108 | // ============================== Pages ==============================
109 | require('./gulpTasks/pageTasks')(gulp);
110 |
111 | // ============================== MISC ===============================
112 | gulp.task(
113 | 'check-deps',
114 | gulp.series(done => {
115 | if (argv['check-deps'] !== false) {
116 | require('./checkDep')(done);
117 | }
118 | })
119 | );
120 |
121 | function reportError() {
122 | console.log(chalk.bgRed('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'));
123 | console.log(chalk.bgRed('!! `npm publish` is forbidden for this package. !!'));
124 | console.log(chalk.bgRed('!! Use `npm run pub` instead. !!'));
125 | console.log(chalk.bgRed('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'));
126 | }
127 |
128 | gulp.task(
129 | 'guard',
130 | gulp.series(done => {
131 | const npmArgs = getNpmArgs();
132 | if (npmArgs) {
133 | for (let arg = npmArgs.shift(); arg; arg = npmArgs.shift()) {
134 | if (/^pu(b(l(i(sh?)?)?)?)?$/.test(arg) && npmArgs.indexOf('--with-rc-tools') < 0) {
135 | reportError();
136 | done(1);
137 | return;
138 | }
139 | }
140 | }
141 | done();
142 | })
143 | );
144 |
145 | // ============================= Native ==============================
146 | gulp.task(
147 | 'react-native-init',
148 | gulp.series(done => {
149 | const myDevDeps = pkg.devDependencies;
150 | const myDeps = pkg.dependencies;
151 | const myVersion = myDeps['react-native'] || myDevDeps['react-native'];
152 | const bundleMap = {
153 | 0.49: ['0.49', '0.x', '*'],
154 | 0.48: ['0.48'],
155 | 0.47: ['0.47'],
156 | 0.46: ['0.46'],
157 | 0.45: ['0.45'],
158 | 0.44: ['0.44'],
159 | 0.43: ['0.43'],
160 | 0.42: ['0.42', '0.41', '0.40'],
161 | 0.39: ['0.39'],
162 | };
163 | let bundleName;
164 | Object.keys(bundleMap).forEach(key => {
165 | if (bundleMap[key].find(v => myVersion.indexOf(v) > -1)) {
166 | bundleName = key;
167 | }
168 | });
169 | if (!bundleName) {
170 | console.warn(
171 | 'warnings: rc-tools now supports react-native@~0.49.x,' +
172 | 'and will install react-native@0.49.3, if has error, ' +
173 | 'please manual init.'
174 | );
175 | bundleName = '0.49';
176 | }
177 | const read = request.get(`http://p.tb.cn/rmsportal_321_${bundleName}.tar.gz`);
178 | const write = targz().createWriteStream(process.cwd());
179 | read.pipe(write);
180 | done();
181 | })
182 | );
183 |
184 | // ============================== Test ===============================
185 | gulp.task(
186 | 'test:react-15',
187 | gulp.series(done => {
188 | console.log(chalk.yellow('Install react 15 dependenicy...'));
189 | shelljs.exec(
190 | 'npm i --no-save react@15 react-dom@15 react-test-renderer@15 enzyme-adapter-react-15'
191 | );
192 |
193 | console.log(chalk.yellow('Read `tests/setup.js`...'));
194 | const testSetup = resolveCwd('./tests/setup.js');
195 | let content = fs.readFileSync(testSetup, 'UTF-8');
196 |
197 | content = content.replace('enzyme-adapter-react-16', 'enzyme-adapter-react-15');
198 |
199 | console.log(chalk.yellow('Modify `tests/setup.js` for `enzyme-adapter-react-15`...'));
200 | fs.writeFileSync(testSetup, content, 'UTF-8');
201 |
202 | // Add mock file
203 | const mockDir = resolveCwd('./tests/__mocks__/');
204 |
205 | console.log(chalk.yellow('Mock of `rc-trigger`...'));
206 | fs.ensureDirSync(mockDir);
207 | fs.writeFileSync(path.resolve(mockDir, 'rc-trigger.js'), mockRcTrigger, 'UTF-8');
208 |
209 | console.log(chalk.yellow('Mock of `rc-util/lib/Portal.js`...'));
210 | const rcUtilDir = path.resolve(mockDir, 'rc-util/lib');
211 | fs.ensureDirSync(rcUtilDir);
212 | fs.writeFileSync(path.resolve(rcUtilDir, 'Portal.js'), mockRcPortal, 'UTF-8');
213 |
214 | console.log(chalk.yellow('Start test...'));
215 | const ret = shelljs.exec('npx jest -u');
216 |
217 | done(ret.code);
218 | })
219 | );
220 |
221 | gulp.task('test', done => {
222 | let jestPath = require.resolve('jest');
223 | const cliRegex = /\/build\/jest\.js$/;
224 |
225 | if (!cliRegex.test(jestPath)) {
226 | console.log(chalk.red('Jest cli not found! Please reinstall or fire a issue fot this.'));
227 | done(1);
228 | return done(1);
229 | }
230 |
231 | jestPath = jestPath.replace(cliRegex, '/bin/jest.js');
232 |
233 | // Support args
234 | const additionalArgs = process.argv.slice(3);
235 | const mergedArgs = [
236 | 'npx',
237 | jestPath,
238 | '--config',
239 | path.join(__dirname, './tests/ts-jest.config.js'),
240 | '--colors',
241 | ]
242 | .concat(additionalArgs)
243 | .join(' ');
244 |
245 | // verbose
246 | if (argv.verbose) {
247 | console.log(chalk.yellow('Execute test:'), mergedArgs);
248 | }
249 |
250 | const ret = shelljs.exec(mergedArgs);
251 | if (ret.code) {
252 | process.exit(ret.code);
253 | }
254 |
255 | done(ret.code);
256 | });
257 |
258 | // ============================= Package =============================
259 | gulp.task('css', () => {
260 | const less = require('gulp-less');
261 | return gulp
262 | .src('assets/*.less')
263 | .pipe(less())
264 | .pipe(postcss([require('./getAutoprefixer')()]))
265 | .pipe(gulp.dest('assets'));
266 | });
267 |
268 | function babelifyInternal(js, modules) {
269 | function replacer(match, m1, m2) {
270 | return `${m1}/assets/${m2}.css`;
271 | }
272 |
273 | const babelConfig = getBabelCommonConfig(modules);
274 | if (modules === false) {
275 | babelConfig.plugins.push(replaceLib);
276 | }
277 |
278 | let stream = js.pipe(babel(babelConfig));
279 | if (argv.compress) {
280 | stream = stream.pipe(minify());
281 | }
282 | return stream
283 | .pipe(
284 | through2.obj(function(file, encoding, next) {
285 | const contents = file.contents.toString(encoding).replace(lessPath, replacer);
286 | file.contents = Buffer.from(contents);
287 | this.push(file);
288 | next();
289 | })
290 | )
291 | .pipe(gulp.dest(modules !== false ? 'lib' : 'es'));
292 | }
293 |
294 | function babelify(modules) {
295 | const streams = [];
296 | const assets = gulp
297 | .src([`${src}/**/*.@(png|svg|less|d.ts)`])
298 | .pipe(gulp.dest(modules === false ? 'es' : 'lib'));
299 | if (glob.sync('src/**/*.{ts,tsx}').length && !glob.sync('src/**/*.d.ts').length) {
300 | let error = 0;
301 | let reporter = tsDefaultReporter;
302 | if (argv['single-run']) {
303 | reporter = {
304 | error(e) {
305 | tsDefaultReporter.error(e);
306 | error = e;
307 | },
308 | finish: tsDefaultReporter.finish,
309 | };
310 | }
311 |
312 | const tsResult = gulp
313 | .src([`${src}/**/*.ts`, `${src}/**/*.tsx`, 'typings/**/*.d.ts'])
314 | .pipe(ts(tsConfig, reporter));
315 |
316 | const check = () => {
317 | if (error) {
318 | console.error('compile error', error);
319 | process.exit(1);
320 | }
321 | };
322 | tsResult.on('finish', check);
323 | tsResult.on('end', check);
324 |
325 | streams.push(
326 | tsResult.dts
327 | // .pipe(require('gulp-debug')())
328 | .pipe(gulp.dest(modules === false ? 'es' : 'lib'))
329 | );
330 | streams.push(babelifyInternal(tsResult.js, modules));
331 | } else {
332 | streams.push(babelifyInternal(gulp.src([`${src}/**/*.js`, `${src}/**/*.jsx`]), modules));
333 | }
334 | return merge2(streams.concat([assets]));
335 | }
336 |
337 | gulp.task('js', () => {
338 | console.log('[Parallel] compile js...');
339 | return babelify();
340 | });
341 |
342 | gulp.task('es', () => {
343 | console.log('[Parallel] compile es...');
344 | return babelify(false);
345 | });
346 |
347 | gulp.task('compile', gulp.series('cleanCompile', gulp.parallel('js', 'es', 'css')));
348 |
349 | // ============================ Code Style ===========================
350 |
351 | gulp.task(
352 | 'genPrettierrc',
353 | gulp.series(done => {
354 | const dir = resolveCwd('./');
355 | const prettierrc = path.join(__dirname, '../config/.prettierrc');
356 | const prettierrcContent = fs.readFileSync(prettierrc);
357 | fs.writeFileSync(path.join(dir, './.prettierrc'), prettierrcContent);
358 | done();
359 | })
360 | );
361 |
362 | gulp.task(
363 | 'genEslint',
364 | gulp.series(done => {
365 | const dir = resolveCwd('./');
366 | const eslintConfig = path.join(__dirname, '../config/eslintrc.js');
367 | const eslintContent = fs.readFileSync(eslintConfig);
368 | fs.writeFileSync(path.join(dir, './.eslintrc.js'), eslintContent);
369 | done();
370 | })
371 | );
372 |
373 | gulp.task(
374 | 'genTslint',
375 | gulp.series(done => {
376 | const dir = resolveCwd('./');
377 | const tslintConfig = path.join(__dirname, '../config/tslint.json');
378 | const tslintContent = fs.readFileSync(tslintConfig);
379 | fs.writeFileSync(path.join(dir, './tslint.json'), tslintContent);
380 |
381 | const tsConfigPath = path.join(__dirname, '../config/tsconfig.json');
382 | const tsContent = fs.readFileSync(tsConfigPath);
383 | fs.writeFileSync(path.join(dir, './tsconfig.json'), tsContent);
384 | done();
385 | })
386 | );
387 |
388 | gulp.task(
389 | 'prettier',
390 | gulp.series(() => {
391 | let fileList = (argv._ || []).slice(1);
392 | if (!fileList.length) {
393 | fileList = [
394 | './src/**/*.{js,jsx}',
395 | './tests/**/*.{js,jsx}',
396 | './code/**/*.{js,jsx}',
397 | './storybook/**/*.{js,jsx}',
398 | './examples/**/*.{js,jsx}',
399 | ];
400 | } else {
401 | console.log(chalk.blue(`Prettier:\n${fileList.join('\n')}`));
402 | }
403 |
404 | const prettierrc = path.join(__dirname, '../config/.prettierrc');
405 | const prettierrcContent = fs.readFileSync(prettierrc, 'utf8');
406 | return gulp
407 | .src(fileList)
408 | .pipe(
409 | prettier(JSON.parse(prettierrcContent), {
410 | reporter: 'error',
411 | })
412 | )
413 | .pipe(gulp.dest(file => file.base));
414 | })
415 | );
416 |
417 | gulp.task('gen-lint-config', gulp.series('genPrettierrc', 'genEslint', 'genTslint'));
418 |
419 | gulp.task(
420 | 'js-lint',
421 | gulp.series('check-deps', done => {
422 | const fileList = (argv._ || []).slice(1);
423 | if (argv['js-lint'] === false) {
424 | return done();
425 | }
426 | const eslintBin = require.resolve('eslint/bin/eslint');
427 | let eslintConfig = path.join(__dirname, '../config/eslintrc.js');
428 | const projectEslint = resolveCwd('./.eslintrc');
429 | if (fs.existsSync(projectEslint)) {
430 | eslintConfig = projectEslint;
431 | }
432 | let args = [eslintBin, '-c', eslintConfig];
433 | if (fileList.length) {
434 | const regex = /\.jsx?$/i;
435 | const jsFiles = fileList.filter(file => regex.test(file));
436 | if (!jsFiles.length) {
437 | done();
438 | return;
439 | }
440 | args = args.concat(jsFiles);
441 | } else {
442 | args = args.concat(['--ext', '.js,.jsx']);
443 |
444 | // eslint v5 will exit when not file find. We have to check first
445 | [src, 'tests', 'examples'].forEach(testPath => {
446 | if (glob.sync(`${testPath}/**/*.{js,ssx}`).length) {
447 | args.push(testPath);
448 | }
449 | });
450 | }
451 | if (argv.fix) {
452 | args.push('--fix');
453 | }
454 |
455 | runCmd('node', args, done);
456 | })
457 | );
458 |
459 | gulp.task(
460 | 'ts-lint',
461 | gulp.series('check-deps', done => {
462 | const fileList = (argv._ || []).slice(1);
463 | const tslintBin = require.resolve('tslint/bin/tslint');
464 | let tslintConfig = path.join(__dirname, '../config/tslint.json');
465 | const projectTslint = resolveCwd('./tslint.json');
466 | if (fs.existsSync(projectTslint)) {
467 | tslintConfig = projectTslint;
468 | }
469 | let args = [tslintBin, '-c', tslintConfig];
470 | if (fileList.length) {
471 | const regex = /\.tsx?$/i;
472 | const tsFileList = fileList.filter(file => regex.test(file));
473 | if (!tsFileList.length) {
474 | done();
475 | return;
476 | }
477 | args = args.concat(tsFileList);
478 | } else {
479 | args = args.concat([
480 | `${src}/**/*{.ts,.tsx}`,
481 | 'tests/**/*{.ts,.tsx}',
482 | 'examples/**/*{.ts,.tsx}',
483 | ]);
484 | }
485 |
486 | runCmd('node', args, done);
487 | })
488 | );
489 |
490 | gulp.task('lint', gulp.series('ts-lint', 'js-lint'));
491 |
492 | // =============================== NPM ===============================
493 | // [Legacy] This task helps to generate dist folder with compressed js file.
494 | // But `main` in `package.json` of RC is pointed to `lib/`.
495 | // task is still keep here for user directly call, but we don't help to package it anymore.
496 | gulp.task(
497 | 'dist',
498 | gulp.series(done => {
499 | console.log(chalk.yellow(`Notice: 'dist' is marked as legacy. Maybe you don't need this.`));
500 | const entry = pkg.config && pkg.config.entry;
501 | if (!entry) {
502 | done();
503 | return;
504 | }
505 | let webpackConfig;
506 | const buildFolder = path.join(cwd, 'dist/');
507 | if (fs.existsSync(path.join(cwd, 'webpack.config.js'))) {
508 | webpackConfig = require(path.join(cwd, 'webpack.config.js'))(
509 | getWebpackConfig({
510 | common: false,
511 | inlineSourceMap: false,
512 | }),
513 | { phase: 'dist' }
514 | );
515 | } else {
516 | const output = pkg.config && pkg.config.output;
517 | if (output && output.library === null) {
518 | output.library = undefined;
519 | }
520 | webpackConfig = assign(
521 | getWebpackConfig({
522 | common: false,
523 | inlineSourceMap: false,
524 | }),
525 | {
526 | output: Object.assign(
527 | {
528 | path: buildFolder,
529 | filename: '[name].js',
530 | library: pkg.name,
531 | libraryTarget: 'umd',
532 | libraryExport: 'default',
533 | },
534 | output
535 | ),
536 | externals: {
537 | react: {
538 | root: 'React',
539 | commonjs2: 'react',
540 | commonjs: 'react',
541 | amd: 'react',
542 | },
543 | 'react-dom': {
544 | root: 'ReactDOM',
545 | commonjs2: 'react-dom',
546 | commonjs: 'react-dom',
547 | amd: 'react-dom',
548 | },
549 | },
550 | }
551 | );
552 | const compressedWebpackConfig = Object.assign({}, webpackConfig);
553 | compressedWebpackConfig.entry = {};
554 | Object.keys(entry).forEach(e => {
555 | compressedWebpackConfig.entry[`${e}.min`] = entry[e];
556 | });
557 | compressedWebpackConfig.plugins = webpackConfig.plugins.concat([
558 | new webpack.optimize.UglifyJsPlugin({
559 | compress: {
560 | screw_ie8: true, // React doesn't support IE8
561 | warnings: false,
562 | },
563 | mangle: {
564 | screw_ie8: true,
565 | },
566 | output: {
567 | comments: false,
568 | screw_ie8: true,
569 | },
570 | }),
571 | new webpack.DefinePlugin({
572 | 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'production'),
573 | }),
574 | ]);
575 | webpackConfig.entry = entry;
576 | webpackConfig = [webpackConfig, compressedWebpackConfig];
577 | }
578 | measureFileSizesBeforeBuild(buildFolder).then(previousFileSizes => {
579 | shelljs.rm('-rf', buildFolder);
580 | webpack(webpackConfig, (err, stats) => {
581 | if (err) {
582 | console.error('error', err);
583 | }
584 | stats.toJson().children.forEach(printResult);
585 | printFileSizesAfterBuild(stats, previousFileSizes, buildFolder);
586 | done(err);
587 | });
588 | });
589 | })
590 | );
591 |
592 | gulp.task(
593 | 'publish',
594 | gulp.series('compile', done => {
595 | if (!fs.existsSync(resolveCwd('lib')) || !fs.existsSync(resolveCwd('es'))) {
596 | return done('missing lib/es dir');
597 | }
598 | console.log('publishing');
599 | const npm = argv.tnpm ? 'tnpm' : 'npm';
600 | const beta = !pkg.version.match(/^\d+\.\d+\.\d+$/);
601 | let args = [npm, 'publish', '--with-rc-tools'];
602 | if (beta) {
603 | args = args.concat(['--tag', 'beta']);
604 | } else if (argv.tag) {
605 | args = args.concat(['--tag', argv.tag]);
606 | }
607 | if (pkg.scripts['pre-publish']) {
608 | shelljs.exec(`npm run pre-publish`);
609 | }
610 | let ret = shelljs.exec(args.join(' ')).code;
611 | cleanCompile();
612 | console.log('published');
613 | if (!ret) {
614 | ret = undefined;
615 | }
616 | done(ret);
617 | })
618 | );
619 |
620 | gulp.task(
621 | 'compile_watch',
622 | gulp.series('compile', done => {
623 | console.log('file changed');
624 | const outDir = argv['out-dir'];
625 | if (outDir) {
626 | fs.copySync(resolveCwd('lib'), path.join(outDir, 'lib'));
627 | fs.copySync(resolveCwd('es'), path.join(outDir, 'es'));
628 | if (fs.existsSync(resolveCwd('assets'))) {
629 | fs.copySync(resolveCwd('assets'), path.join(outDir, 'assets'));
630 | }
631 | }
632 | done();
633 | })
634 | );
635 |
636 | gulp.task('pre-commit', gulp.series('prettier', 'lint'));
637 |
638 | gulp.task(
639 | 'pub',
640 | gulp.series('publish', 'gh-pages', done => {
641 | console.log('tagging');
642 | const { version } = pkg;
643 | shelljs.cd(cwd);
644 | shelljs.exec(`git tag ${version}`);
645 | shelljs.exec(`git push origin ${version}:${version}`);
646 | shelljs.exec('git push origin master:master');
647 | console.log('tagged');
648 | done();
649 | })
650 | );
651 |
652 | // =========================== Deprecated ============================
653 | gulp.task(
654 | 'watch',
655 | gulp.series('compile_watch', done => {
656 | gulp.watch([`${src}/**/*.js?(x)`, `${src}/**/*.ts?(x)`, 'assets/**/*.less'], ['compile_watch']);
657 | done();
658 | })
659 | );
660 |
661 | function compileTs(stream) {
662 | const assets = stream
663 | .pipe(
664 | through2.obj(function(file, encoding, next) {
665 | if (!file.path.endsWith('tsx')) {
666 | this.push(file);
667 | }
668 | next();
669 | })
670 | )
671 | .pipe(gulp.dest(path.join(cwd, tsCompiledDir)));
672 |
673 | return merge2([
674 | assets,
675 | stream
676 | .pipe(
677 | through2.obj(function(file, encoding, next) {
678 | if (file.path.endsWith('tsx')) {
679 | this.push(file);
680 | }
681 | next();
682 | })
683 | )
684 | .pipe(ts(tsConfig))
685 | .js.pipe(
686 | through2.obj(function(file, encoding, next) {
687 | // console.log(file.path, file.base);
688 | file.path = file.path.replace(/\.[jt]sx$/, '.js');
689 | this.push(file);
690 | next();
691 | })
692 | )
693 | .pipe(gulp.dest(path.join(cwd, tsCompiledDir))),
694 | ]);
695 | }
696 |
697 | gulp.task(
698 | 'compile_tsc',
699 | gulp.series(() => {
700 | shelljs.rm('-rf', resolveCwd(tsCompiledDir));
701 | return compileTs(
702 | gulp.src(tsFiles, {
703 | base: cwd,
704 | })
705 | );
706 | })
707 | );
708 |
709 | gulp.task(
710 | 'watch-tsc',
711 | gulp.series('compile_tsc', done => {
712 | watch(tsFiles, f => {
713 | if (f.event === 'unlink') {
714 | return;
715 | }
716 | const myPath = path.relative(cwd, f.path);
717 | compileTs(
718 | gulp.src([myPath, 'typings/**/*.d.ts'], {
719 | base: cwd,
720 | })
721 | );
722 | });
723 | done();
724 | })
725 | );
726 |
727 | gulp.task(
728 | 'update-self',
729 | gulp.series('compile', done => {
730 | getNpm(npm => {
731 | console.log(`${npm} updating ${selfPackage.name}`);
732 | runCmd(npm, ['update', selfPackage.name], c => {
733 | console.log(`${npm} update ${selfPackage.name} end`);
734 | done(c);
735 | });
736 | });
737 | done();
738 | })
739 | );
740 | gulp.task(
741 | 'runGenStorybook',
742 | gulp.series(done => {
743 | const dir = resolveCwd('./');
744 | genStorybook(dir);
745 | done();
746 | })
747 | );
748 |
--------------------------------------------------------------------------------
/lib/init.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | // from publish-please
4 |
5 | const path = require('path');
6 | const writeFile = require('fs').writeFileSync;
7 | const chalk = require('chalk');
8 |
9 | const pathJoin = path.join;
10 |
11 | function reportNoConfig() {
12 | console.log(
13 | chalk.bgRed('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
14 | );
15 | console.log(chalk.bgRed("!! Unable to setup rc-tools: project's package.json either missing !!"));
16 | console.log(chalk.bgRed('!! or malformed. Run `npm init` and then reinstall rc-tools. !!'));
17 | console.log(
18 | chalk.bgRed('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
19 | );
20 | }
21 |
22 | function reportCompletion() {
23 | console.log(chalk.bgGreen('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'));
24 | console.log(chalk.bgGreen('!! rc-tools was successfully installed for the project. !!'));
25 | console.log(chalk.bgGreen('!! Use `npm run pub` command for publishing. !!'));
26 | console.log(chalk.bgGreen('!! publishing configuration. !!'));
27 | console.log(chalk.bgGreen('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'));
28 | }
29 |
30 | function addConfigHooks(cfg, projectDir) {
31 | if (!cfg.scripts) {
32 | cfg.scripts = {};
33 | }
34 |
35 | if (cfg.scripts.pub) {
36 | return false;
37 | }
38 |
39 | cfg.scripts = Object.assign(cfg.scripts, {
40 | build: 'rc-tools run build',
41 | 'gh-pages': 'rc-tools run gh-pages',
42 | start: 'rc-tools run server',
43 | pub: 'rc-tools run update-self && rc-tools run pub',
44 | lint: 'rc-tools run lint',
45 | });
46 |
47 | if (cfg.scripts.prepublish) {
48 | cfg.scripts['pre-publish'] = cfg.scripts.prepublish;
49 | }
50 |
51 | cfg.scripts.prepublish = 'rc-tools run guard';
52 |
53 | writeFile(pathJoin(projectDir, 'package.json'), JSON.stringify(cfg, null, 2));
54 |
55 | return true;
56 | }
57 |
58 | function init() {
59 | const testMode = process.argv.indexOf('--test-mode') > -1;
60 |
61 | // NOTE: don't run on dev installation (running `npm install` in this repo)
62 | if (!testMode) {
63 | const { getNpmArgs } = require('./util');
64 | const npmArgs = getNpmArgs();
65 |
66 | if (!npmArgs || !npmArgs.some(arg => /^rc-tools(@\d+\.\d+.\d+)?$/.test(arg))) {
67 | return;
68 | }
69 | }
70 | // NOTE: /node_modules/rc-tools/lib
71 | const projectDir = pathJoin(__dirname, '../../../');
72 |
73 | const cfg = require(path.join(projectDir, 'package.json'));
74 |
75 | if (!cfg) {
76 | reportNoConfig();
77 | process.exit(1);
78 | } else if (addConfigHooks(cfg, projectDir)) {
79 | reportCompletion();
80 | }
81 | }
82 |
83 | init();
84 |
--------------------------------------------------------------------------------
/lib/initStoryConfigJs.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs-extra');
2 | const path = require('path');
3 |
4 | module.exports = (dir, { name, homepage }) => {
5 | const configJs = `
6 | import { configure,addParameters, addDecorator } from '@storybook/react';
7 | import withSource from 'storybook-addon-source';
8 |
9 | function loadStories() {
10 | require('${dir}storybook/index.js');
11 | }
12 |
13 | addDecorator(withSource);
14 |
15 | addParameters({
16 | options: {
17 | theme: {
18 | name: '${name}',
19 | brandUrl: '${homepage}',
20 | brandTitle: '${name}',
21 | },
22 | },
23 | });
24 |
25 | configure(loadStories, module);`;
26 |
27 | const manageHeaderHtml = `
28 |
32 |
37 | `;
38 | fs.writeFileSync(path.join(__dirname, './storybook/config.js'), configJs);
39 | fs.writeFileSync(path.join(__dirname, './storybook/manager-head.html'), manageHeaderHtml);
40 | };
41 |
--------------------------------------------------------------------------------
/lib/postcssConfig.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const autoprefixer = require('./getAutoprefixer')();
4 |
5 | module.exports = function() {
6 | return [autoprefixer];
7 | };
8 |
--------------------------------------------------------------------------------
/lib/replaceLib.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const { join, dirname } = require('path');
4 | const fs = require('fs');
5 |
6 | const cwd = process.cwd();
7 |
8 | function replacePath(path) {
9 | if (path.node.source && /\/lib\//.test(path.node.source.value)) {
10 | const esModule = path.node.source.value.replace('/lib/', '/es/');
11 | const esPath = dirname(join(cwd, `node_modules/${esModule}`));
12 | if (fs.existsSync(esPath)) {
13 | console.log(`[es build] replace ${path.node.source.value} with ${esModule}`);
14 | path.node.source.value = esModule;
15 | }
16 | }
17 | }
18 |
19 | function replaceLib() {
20 | return {
21 | visitor: {
22 | ImportDeclaration: replacePath,
23 | ExportNamedDeclaration: replacePath,
24 | },
25 | };
26 | }
27 |
28 | module.exports = replaceLib;
29 |
--------------------------------------------------------------------------------
/lib/resolveCwd.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const path = require('path');
4 |
5 | module.exports = function resolveCwd(...args) {
6 | args.unshift(process.cwd());
7 | return path.join(...args);
8 | };
9 |
--------------------------------------------------------------------------------
/lib/server/index.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const serve = require('koa-static');
4 | const path = require('path');
5 | const webpackMiddleware = require('koa-webpack-dev-middleware');
6 | const Koa = require('koa');
7 | const serveIndex = require('koa-serve-index');
8 | const koaBody = require('koa-body');
9 | const Router = require('koa-router');
10 | const webpack = require('webpack');
11 | const chalk = require('chalk');
12 | const fs = require('fs');
13 | const logger = require('koa-logger');
14 | const getWebpackConfig = require('../getWebpackConfig');
15 |
16 | require('xtpl').config({
17 | XTemplate: require('xtemplate'),
18 | });
19 |
20 | const cwd = process.cwd();
21 |
22 | module.exports = function(app) {
23 | const router = new Router();
24 |
25 | app = app || new Koa();
26 | app = require('xtpl/lib/koa')(app, {
27 | views: path.join(__dirname, '../../views'),
28 | });
29 | const root = cwd;
30 | app.use(logger());
31 | app.use(
32 | require('koa-favicon')(path.join(__dirname, '../../public/favicon.ico'))
33 | );
34 | // parse application/x-www-form-urlencoded
35 | app.use(
36 | koaBody({
37 | formidable: { uploadDir: path.join(cwd, 'tmp') },
38 | multipart: true,
39 | })
40 | );
41 |
42 | app
43 | .use(router.routes())
44 | .use(router.allowedMethods());
45 |
46 | // app.use(router(app));
47 | app.use(require('./js2html')());
48 | let webpackConfig = getWebpackConfig({
49 | common: false,
50 | inlineSourceMap: true,
51 | });
52 | webpackConfig.plugins.push(
53 | new webpack.ProgressPlugin((percentage, msg) => {
54 | const stream = process.stderr;
55 | if (stream.isTTY && percentage < 0.71) {
56 | stream.cursorTo(0);
57 | stream.write(chalk.magenta(msg));
58 | stream.clearLine(1);
59 | } else if (percentage === 1) {
60 | console.log(chalk.green('\nwebpack: bundle build is now finished.'));
61 | }
62 | })
63 | );
64 | const publicPath = '/';
65 | if (fs.existsSync(path.join(cwd, 'webpack.config.js'))) {
66 | webpackConfig = require(path.join(cwd, 'webpack.config.js'))(webpackConfig);
67 | }
68 |
69 | const compiler = webpack(webpackConfig);
70 | compiler.plugin('done', stats => {
71 | if (stats.hasErrors()) {
72 | console.log(
73 | stats.toString({
74 | colors: true,
75 | })
76 | );
77 | }
78 | });
79 | app.use(
80 | webpackMiddleware(compiler, {
81 | publicPath,
82 | hot: true,
83 | https: false,
84 | quiet: true,
85 | headers: {
86 | 'Cache-control': 'no-cache',
87 | },
88 | })
89 | );
90 | app.use(
91 | serveIndex(root, {
92 | hidden: true,
93 | view: 'details',
94 | icons: true,
95 | filter: filename => {
96 | return filename.indexOf('.') !== 0 && filename.indexOf('.js') < 0;
97 | },
98 | })
99 | );
100 | app.use(
101 | serve(root, {
102 | hidden: true,
103 | })
104 | );
105 | return app;
106 | };
107 |
--------------------------------------------------------------------------------
/lib/server/js2html.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var fs = require('fs');
4 | var path = require('path');
5 | var highlightJs = require('highlight.js');
6 | var assign = require('object-assign');
7 | var packageUtil = require('./packageUtil');
8 | var cwd = process.cwd();
9 | var pkg = require(path.join(cwd, 'package.json'));
10 | var srcPath = new RegExp('(["\']' + pkg.name + ')/src/', 'g');
11 | var internalIp = require('internal-ip');
12 | var request = require('koa-request');
13 | var tplName = 'js2html';
14 | const port = (pkg.config && pkg.config.port) || '8000';
15 |
16 | if (fs.existsSync(path.join(cwd, 'examples/template.xtpl'))) {
17 | tplName = path.join(cwd, 'examples/template.xtpl');
18 | }
19 |
20 | function replaceSrcToLib(modName) {
21 | return modName.replace(srcPath, function(m, m1) {
22 | return m1 + '/lib/';
23 | });
24 | }
25 |
26 | function transformJsForRender(code, jsName) {
27 | const addr = `//${internalIp.v4()}:${port}/examples/${jsName}.html`;
28 | return `
29 |
32 |
33 |
${
34 | highlightJs.highlightAuto(replaceSrcToLib(code)).value
35 | }
36 |
37 | `;
38 | }
39 |
40 | module.exports = function() {
41 | return function*(next) {
42 | var pathname = this.path;
43 | if (pathname.match(/\.html$/)) {
44 | var filePath = path.join(process.cwd(), pathname);
45 | if (fs.existsSync(filePath)) {
46 | var content = fs
47 | .readFileSync(filePath, {
48 | encoding: 'utf-8',
49 | })
50 | .trim();
51 | if (content && content !== 'placeholder') {
52 | yield* next;
53 | return;
54 | }
55 | }
56 | var jsName;
57 | var jsPath = pathname.replace(/\.html$/, '.tsx');
58 | jsName = path.basename(jsPath, '.tsx');
59 | var jsFile = path.join(process.cwd(), jsPath);
60 | if (!fs.existsSync(jsFile)) {
61 | jsFile = path.join(process.cwd(), pathname.replace(/\.html$/, '.ts'));
62 | }
63 | if (!fs.existsSync(jsFile)) {
64 | jsFile = path.join(process.cwd(), pathname.replace(/\.html$/, '.jsx'));
65 | }
66 | if (!fs.existsSync(jsFile)) {
67 | jsFile = path.join(process.cwd(), pathname.replace(/\.html$/, '.js'));
68 | }
69 | const response = yield request({
70 | url: `http://localhost:${port}/examples/${jsName}.css`,
71 | });
72 | const hasCss = response.statusCode === 200;
73 | var code = fs.readFileSync(jsFile, {
74 | encoding: 'utf-8',
75 | });
76 | yield this.render(
77 | tplName,
78 | assign(
79 | {
80 | name: jsName,
81 | hasCss,
82 | pkg,
83 | query: this.query,
84 | content: transformJsForRender(code, jsName),
85 | },
86 | packageUtil.getPackages()
87 | )
88 | );
89 | } else {
90 | yield* next;
91 | }
92 | };
93 | };
94 |
--------------------------------------------------------------------------------
/lib/server/packageUtil.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const path = require('path');
4 | const utils = require('modulex-util');
5 |
6 | const cwd = process.cwd();
7 | const NODE_MODULES = 'node_modules';
8 | const packages = {
9 | es5Shim: 1,
10 | es6Shim: 1,
11 | es6Promise: 1,
12 | normalize: 'normalize.css',
13 | consolePolyfill: 1,
14 | mocha: 1,
15 | 'highlight.js': 1,
16 | fastclick: 1,
17 | };
18 |
19 | function deCamelCase(m) {
20 | return `-${m.toLowerCase()}`;
21 | }
22 |
23 | function findPackage(packageName) {
24 | try {
25 | const file = require.resolve(packageName);
26 | const dir = path.dirname(file);
27 | let url = path.relative(cwd, dir);
28 | if (url.indexOf('/rc-tools/') !== -1) {
29 | const index = url.indexOf('/rc-tools/');
30 | return path.join(NODE_MODULES, url.substring(index));
31 | }
32 |
33 | if (!utils.startsWith(url, NODE_MODULES)) {
34 | url = path.join(NODE_MODULES, url);
35 | }
36 | return url;
37 | } catch (e) {
38 | return null;
39 | }
40 | }
41 |
42 | Object.keys(packages).forEach(p => {
43 | let name = p;
44 | if (typeof packages[p] === 'string') {
45 | name = packages[p];
46 | } else {
47 | name = name.replace(/[A-Z]/g, deCamelCase);
48 | }
49 | packages[p] = findPackage(`${name}/package.json`);
50 | });
51 |
52 | packages.highlightJs = packages['highlight.js'];
53 |
54 | packages.public = findPackage(`../../public/modernizr.js`);
55 |
56 | module.exports = {
57 | findPackage,
58 |
59 | getPackages() {
60 | return packages;
61 | },
62 | };
63 |
--------------------------------------------------------------------------------
/lib/storybook/addons.js:
--------------------------------------------------------------------------------
1 | import '@storybook/addon-actions/register';
2 | import '@storybook/addon-a11y/register';
3 | import '@storybook/addon-console';
4 | import '@storybook/addon-viewport/register';
5 | import 'storybook-addon-source/register';
6 |
--------------------------------------------------------------------------------
/lib/storybook/config.js:
--------------------------------------------------------------------------------
1 | /** temp file */
2 |
--------------------------------------------------------------------------------
/lib/storybook/manager-head.html:
--------------------------------------------------------------------------------
1 |
2 |
6 |
11 |
--------------------------------------------------------------------------------
/lib/storybook/preview-head.html:
--------------------------------------------------------------------------------
1 |
5 |
--------------------------------------------------------------------------------
/lib/storybook/webpack.config.js:
--------------------------------------------------------------------------------
1 | const tsConfig = require('../getTSCommonConfig');
2 | const resolveCwd = require('../resolveCwd');
3 |
4 | const pkg = require(resolveCwd('package.json'));
5 |
6 | module.exports = ({ config }) => {
7 | config.module.rules.push({
8 | test: /\.tsx?$/,
9 | use: [
10 | {
11 | loader: require.resolve('ts-loader'),
12 | options: {
13 | configFile: tsConfig.getConfigFilePath(),
14 | transpileOnly: true,
15 | },
16 | },
17 | require.resolve('react-docgen-typescript-loader'),
18 | ],
19 | });
20 |
21 | config.resolve.extensions.push('.ts', '.tsx');
22 | config.resolve.alias = {
23 | ...config.resolve.alias,
24 | [pkg.name]: resolveCwd('/'),
25 | };
26 | config.module.rules.push({
27 | test: /\.less$/,
28 | use: [
29 | {
30 | loader: 'style-loader',
31 | },
32 | {
33 | loader: 'css-loader',
34 | },
35 | {
36 | loader: 'less-loader',
37 | options: {
38 | javascriptEnabled: true,
39 | },
40 | },
41 | ],
42 | });
43 | config.resolve.extensions.push('.less');
44 | return config;
45 | };
46 |
--------------------------------------------------------------------------------
/lib/tests/setup.js:
--------------------------------------------------------------------------------
1 | /* eslint-disable import/no-extraneous-dependencies */
2 | require("@babel/polyfill");
3 | const Enzyme = require('enzyme');
4 | const Adapter = require('enzyme-adapter-react-16');
5 |
6 | Enzyme.configure({ adapter: new Adapter() });
--------------------------------------------------------------------------------
/lib/tests/ts-jest.config.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs');
2 | const path = require('path');
3 | const chalk = require('chalk');
4 |
5 | const argv = require('minimist')(process.argv.slice(2));
6 |
7 | const cwd = process.cwd();
8 |
9 | function projPath(...args) {
10 | return path.join(cwd, ...args);
11 | }
12 |
13 | function toolPath(...args) {
14 | return path.join(__dirname, '..', ...args);
15 | }
16 |
17 | const componentSetupFiles = [
18 | './tests/setup.ts', // User setup ts file
19 | './tests/setup.js', // User setup js file
20 | ].filter(subPath => {
21 | const filePath = projPath(subPath);
22 | if (fs.existsSync(filePath)) {
23 | console.log(
24 | chalk.yellow('Test setup file:'),
25 | filePath
26 | );
27 | return true;
28 | }
29 | return false;
30 | });
31 |
32 | const transformPath = toolPath(
33 | '../scripts',
34 | argv.verbose ? 'debugJestPreprocessor.js' : 'jestPreprocessor.js'
35 | );
36 |
37 | if (argv.verbose) {
38 | console.log(
39 | chalk.blue('[verbose] rootDir:'),
40 | cwd
41 | );
42 | console.log(
43 | chalk.blue('[verbose] Jest:'),
44 | require('jest/package.json').version
45 | );
46 | console.log(
47 | chalk.blue('[verbose] Transform file:'),
48 | transformPath
49 | );
50 | console.log(
51 | chalk.blue('[verbose] Transform exists:'),
52 | String(fs.existsSync(transformPath))
53 | );
54 | }
55 |
56 | module.exports = {
57 | verbose: !!argv.verbose,
58 |
59 | rootDir: cwd,
60 | setupFiles: [
61 | toolPath('./tests/setup.js'), // tools setup
62 | ...componentSetupFiles,
63 | ],
64 | testPathIgnorePatterns: ['/node_modules/', 'dekko', 'node'],
65 | modulePathIgnorePatterns: ['/examples/'],
66 | moduleFileExtensions: [
67 | 'js', 'jsx',
68 | 'ts', 'tsx',
69 | ],
70 |
71 | testMatch: [
72 | '**/tests/**/*.spec.js?(x)',
73 | '**/tests/**/*.spec.ts?(x)',
74 | ],
75 | transform: {
76 | '\\.jsx?$': transformPath,
77 | '\\.tsx?$': transformPath,
78 | },
79 | snapshotSerializers: [require.resolve('enzyme-to-json/serializer')],
80 | transformIgnorePatterns: [
81 | '/examples/',
82 | 'node_modules/[^/]+?/(?!(es|node_modules)/)'
83 | ],
84 | collectCoverageFrom: [
85 | '**/src/**.{js,jsx,ts,tsx}',
86 | "!**/node_modules/**",
87 | ],
88 | };
89 |
--------------------------------------------------------------------------------
/lib/tests/tsconfig.test.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "module": "commonjs",
5 | "declaration": true,
6 | "outDir": "./lib",
7 | "jsx": "react",
8 | "noUnusedLocals": true,
9 | "noImplicitReturns": true,
10 | "noFallthroughCasesInSwitch": true,
11 | "esModuleInterop": true
12 | },
13 | "typeRoots": ["../node_modules/@types", "./@types"],
14 | "exclude": ["node_modules", "lib"]
15 | }
16 |
--------------------------------------------------------------------------------
/lib/util.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const chalk = require('chalk');
4 |
5 | function runCmd(cmd, args, fn) {
6 | args = args || [];
7 | const runner = require('child_process').spawn(cmd, args, {
8 | // keep color
9 | stdio: 'inherit',
10 | });
11 | runner.on('close', code => {
12 | if (fn) {
13 | if (code) {
14 | console.log(chalk.yellow(`Error on execution: ${cmd} ${(args || []).join(' ')}`));
15 | }
16 | fn(code);
17 | }
18 | });
19 | }
20 |
21 | function getNpmArgs() {
22 | let npmArgv = null;
23 |
24 | try {
25 | npmArgv = JSON.parse(process.env.npm_config_argv);
26 | } catch (err) {
27 | return null;
28 | }
29 |
30 | if (typeof npmArgv !== 'object' || !npmArgv.cooked || !Array.isArray(npmArgv.cooked)) {
31 | return null;
32 | }
33 |
34 | return npmArgv.cooked;
35 | }
36 |
37 | module.exports = {
38 | runCmd,
39 | getNpmArgs,
40 | };
41 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "rc-tools",
3 | "version": "9.6.1-alpha.1",
4 | "description": "offline tools for react component",
5 | "keywords": [
6 | "react",
7 | "tools"
8 | ],
9 | "homepage": "http://github.com/react-component/rc-tools",
10 | "bugs": {
11 | "url": "http://github.com/react-component/rc-tools/issues"
12 | },
13 | "repository": {
14 | "type": "git",
15 | "url": "git@github.com:react-component/rc-tools.git"
16 | },
17 | "license": "MIT",
18 | "author": {
19 | "name": "yiminghe@gmail.com"
20 | },
21 | "bin": {
22 | "rc-tools": "./bin/rc-tools.js",
23 | "rc-tools-run": "./bin/rc-tools-run.js"
24 | },
25 | "scripts": {
26 | "checkDep": "node scripts/checkDep",
27 | "postinstall": "node lib/init.js",
28 | "lint": "eslint --ext .js,.jsx lib",
29 | "lint-staged": "lint-staged",
30 | "pub": "rm -rf yarn.lock && git push origin && npm publish"
31 | },
32 | "pre-commit": [
33 | "checkDep",
34 | "lint-staged"
35 | ],
36 | "lint-staged": {
37 | "**/*.js": "eslint --ext .js"
38 | },
39 | "dependencies": {
40 | "@babel/core": "~7.2.2",
41 | "@babel/plugin-proposal-class-properties": "~7.2.1",
42 | "@babel/plugin-proposal-export-default-from": "~7.2.0",
43 | "@babel/plugin-proposal-export-namespace-from": "~7.2.0",
44 | "@babel/plugin-proposal-object-rest-spread": "~7.2.0",
45 | "@babel/plugin-transform-member-expression-literals": "~7.2.0",
46 | "@babel/plugin-transform-object-assign": "~7.2.0",
47 | "@babel/plugin-transform-property-literals": "~7.2.0",
48 | "@babel/plugin-transform-runtime": "~7.2.0",
49 | "@babel/plugin-transform-spread": "~7.2.2",
50 | "@babel/plugin-transform-template-literals": "~7.2.0",
51 | "@babel/plugin-transform-typeof-symbol": "~7.2.0",
52 | "@babel/polyfill": "~7.2.5",
53 | "@babel/preset-env": "~7.2.0",
54 | "@babel/preset-react": "~7.0.0",
55 | "@babel/preset-stage-0": "~7.0.0",
56 | "@storybook/addon-a11y": "~5.0.0",
57 | "@storybook/addon-actions": "~5.0.0",
58 | "@storybook/addon-console": "~1.1.0",
59 | "@storybook/addon-info": "~5.0.0",
60 | "@storybook/addon-knobs": "~5.0.0",
61 | "@storybook/addon-links": "~5.0.0",
62 | "@storybook/addon-viewport": "~5.0.0",
63 | "@storybook/addons": "~5.0.0",
64 | "@storybook/cli": "~5.0.0",
65 | "@storybook/react": "~5.0.0",
66 | "@types/jest": "^23.3.10",
67 | "@types/storybook__react": "~4.0.0",
68 | "autoprefixer": "^9.x",
69 | "babel-core": "~7.0.0-bridge.0",
70 | "babel-eslint": "~10.0.1",
71 | "babel-jest": "~23.6.0",
72 | "babel-loader": "~8.0.4",
73 | "chalk": "^2.4.1",
74 | "commander": "2.19.x",
75 | "console-polyfill": "~0.3.0",
76 | "css-loader": "^2.0.1",
77 | "enzyme": "^3.8.0",
78 | "enzyme-adapter-react-16": "^1.7.1",
79 | "enzyme-to-json": "^3.3.5",
80 | "es5-shim": "4.x",
81 | "es6-promise": "~4.2.5",
82 | "es6-shim": "^0.35.4",
83 | "eslint": "^5.10.0",
84 | "eslint-config-airbnb": "^17.1.0",
85 | "eslint-config-prettier": "^3.3.0",
86 | "eslint-plugin-import": "^2.14.0",
87 | "eslint-plugin-jsx-a11y": "^6.1.2",
88 | "eslint-plugin-react": "^7.11.1",
89 | "fastclick": "~1.0.6",
90 | "file-loader": "^2.0.0",
91 | "filesize": "^3.6.1",
92 | "fs-extra": "^7.0.1",
93 | "gh-pages": "^2.0.1",
94 | "glob": "~7.1.3",
95 | "gulp": "^4.0.0",
96 | "gulp-babel": "^8.0.0",
97 | "gulp-babel-minify": "^0.5.0",
98 | "gulp-jsx2example": "^1.2.4",
99 | "gulp-less": "4.x",
100 | "gulp-postcss": "^8.0.0",
101 | "gulp-prettier": "^2.0.0",
102 | "gulp-typescript": "~5.0.0",
103 | "gulp-watch": "^5.0.1",
104 | "gzip-size": "^5.0.0",
105 | "highlight.js": "^9.13.1",
106 | "html5shiv": "3.x",
107 | "internal-ip": "^3.0.1",
108 | "jest": "^23.6.0",
109 | "koa": "^2.6.2",
110 | "koa-body": "^4.0.4",
111 | "koa-favicon": "^2.0.1",
112 | "koa-logger": "3.x",
113 | "koa-request": "~1.0.0",
114 | "koa-router": "7.x",
115 | "koa-serve-index": "^1.1.1",
116 | "koa-static": "^5.0.0",
117 | "koa-webpack-dev-middleware": "^2.0.2",
118 | "less": "^3.9.0",
119 | "less-loader": "^4.1.0",
120 | "match-require": "2.x",
121 | "merge2": "~1.2.3",
122 | "mini-css-extract-plugin": "^0.5.0",
123 | "minimist": "1.x",
124 | "modulex-util": "^1.1.10",
125 | "normalize.css": "^8.0.1",
126 | "object-assign": "4.x",
127 | "postcss-loader": "^3.0.0",
128 | "prettier": "^1.15.3",
129 | "progress-bar-webpack-plugin": "^1.11.0",
130 | "rc-source-loader": "^1.0.2",
131 | "react-docgen-typescript-loader": "^3.0.0",
132 | "react-markdown": "^4.0.6",
133 | "recursive-readdir": "^2.2.2",
134 | "request": "^2.88.0",
135 | "shelljs": "0.8.x",
136 | "storybook-addon-source": "latest",
137 | "strip-ansi": "^5.0.0",
138 | "style-loader": "^0.23.1",
139 | "svg-sprite-loader": "^4.1.3",
140 | "tar.gz": "^1.0.7",
141 | "through2": "^3.0.0",
142 | "ts-jest": "^23.10.5",
143 | "ts-loader": "^5.3.1",
144 | "tslint": "5.x",
145 | "tslint-config-prettier": "^1.17.0",
146 | "tslint-react": "^3.6.0",
147 | "typescript": "^3.2.2",
148 | "url-loader": "^1.1.2",
149 | "webpack": "^4.28.0",
150 | "xtemplate": "^4.6.1",
151 | "xtpl": "^3.4.0"
152 | },
153 | "devDependencies": {
154 | "gulp-debug": "^4.0.0",
155 | "lint-staged": "^8.1.0",
156 | "pre-commit": "1.x",
157 | "react": "^16.7.0",
158 | "react-dom": "^16.7.0"
159 | }
160 | }
161 |
--------------------------------------------------------------------------------
/public/change.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/react-component/rc-tools/78385966ec2f55ac806aa00bd1e185c3c408c910/public/favicon.ico
--------------------------------------------------------------------------------
/public/modernizr.js:
--------------------------------------------------------------------------------
1 | /*!
2 | * Modernizr v2.8.3
3 | * www.modernizr.com
4 | *
5 | * Copyright (c) Faruk Ates, Paul Irish, Alex Sexton
6 | * Available under the BSD and MIT licenses: www.modernizr.com/license/
7 | */
8 |
9 | /*
10 | * Modernizr tests which native CSS3 and HTML5 features are available in
11 | * the current UA and makes the results available to you in two ways:
12 | * as properties on a global Modernizr object, and as classes on the
13 | * element. This information allows you to progressively enhance
14 | * your pages with a granular level of control over the experience.
15 | *
16 | * Modernizr has an optional (not included) conditional resource loader
17 | * called Modernizr.load(), based on Yepnope.js (yepnopejs.com).
18 | * To get a build that includes Modernizr.load(), as well as choosing
19 | * which tests to include, go to www.modernizr.com/download/
20 | *
21 | * Authors Faruk Ates, Paul Irish, Alex Sexton
22 | * Contributors Ryan Seddon, Ben Alman
23 | */
24 |
25 | window.Modernizr = (function( window, document, undefined ) {
26 |
27 | var version = '2.8.3',
28 |
29 | Modernizr = {},
30 |
31 | /*>>cssclasses*/
32 | // option for enabling the HTML classes to be added
33 | enableClasses = true,
34 | /*>>cssclasses*/
35 |
36 | docElement = document.documentElement,
37 |
38 | /**
39 | * Create our "modernizr" element that we do most feature tests on.
40 | */
41 | mod = 'modernizr',
42 | modElem = document.createElement(mod),
43 | mStyle = modElem.style,
44 |
45 | /**
46 | * Create the input element for various Web Forms feature tests.
47 | */
48 | inputElem /*>>inputelem*/ = document.createElement('input') /*>>inputelem*/ ,
49 |
50 | /*>>smile*/
51 | smile = ':)',
52 | /*>>smile*/
53 |
54 | toString = {}.toString,
55 |
56 | // TODO :: make the prefixes more granular
57 | /*>>prefixes*/
58 | // List of property values to set for css tests. See ticket #21
59 | prefixes = ' -webkit- -moz- -o- -ms- '.split(' '),
60 | /*>>prefixes*/
61 |
62 | /*>>domprefixes*/
63 | // Following spec is to expose vendor-specific style properties as:
64 | // elem.style.WebkitBorderRadius
65 | // and the following would be incorrect:
66 | // elem.style.webkitBorderRadius
67 |
68 | // Webkit ghosts their properties in lowercase but Opera & Moz do not.
69 | // Microsoft uses a lowercase `ms` instead of the correct `Ms` in IE8+
70 | // erik.eae.net/archives/2008/03/10/21.48.10/
71 |
72 | // More here: github.com/Modernizr/Modernizr/issues/issue/21
73 | omPrefixes = 'Webkit Moz O ms',
74 |
75 | cssomPrefixes = omPrefixes.split(' '),
76 |
77 | domPrefixes = omPrefixes.toLowerCase().split(' '),
78 | /*>>domprefixes*/
79 |
80 | /*>>ns*/
81 | ns = {'svg': 'http://www.w3.org/2000/svg'},
82 | /*>>ns*/
83 |
84 | tests = {},
85 | inputs = {},
86 | attrs = {},
87 |
88 | classes = [],
89 |
90 | slice = classes.slice,
91 |
92 | featureName, // used in testing loop
93 |
94 |
95 | /*>>teststyles*/
96 | // Inject element with style element and some CSS rules
97 | injectElementWithStyles = function( rule, callback, nodes, testnames ) {
98 |
99 | var style, ret, node, docOverflow,
100 | div = document.createElement('div'),
101 | // After page load injecting a fake body doesn't work so check if body exists
102 | body = document.body,
103 | // IE6 and 7 won't return offsetWidth or offsetHeight unless it's in the body element, so we fake it.
104 | fakeBody = body || document.createElement('body');
105 |
106 | if ( parseInt(nodes, 10) ) {
107 | // In order not to give false positives we create a node for each test
108 | // This also allows the method to scale for unspecified uses
109 | while ( nodes-- ) {
110 | node = document.createElement('div');
111 | node.id = testnames ? testnames[nodes] : mod + (nodes + 1);
112 | div.appendChild(node);
113 | }
114 | }
115 |
116 | // '].join('');
122 | div.id = mod;
123 | // IE6 will false positive on some tests due to the style element inside the test div somehow interfering offsetHeight, so insert it into body or fakebody.
124 | // Opera will act all quirky when injecting elements in documentElement when page is served as xml, needs fakebody too. #270
125 | (body ? div : fakeBody).innerHTML += style;
126 | fakeBody.appendChild(div);
127 | if ( !body ) {
128 | //avoid crashing IE8, if background image is used
129 | fakeBody.style.background = '';
130 | //Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible
131 | fakeBody.style.overflow = 'hidden';
132 | docOverflow = docElement.style.overflow;
133 | docElement.style.overflow = 'hidden';
134 | docElement.appendChild(fakeBody);
135 | }
136 |
137 | ret = callback(div, rule);
138 | // If this is done after page load we don't want to remove the body so check if body exists
139 | if ( !body ) {
140 | fakeBody.parentNode.removeChild(fakeBody);
141 | docElement.style.overflow = docOverflow;
142 | } else {
143 | div.parentNode.removeChild(div);
144 | }
145 |
146 | return !!ret;
147 |
148 | },
149 | /*>>teststyles*/
150 |
151 | /*>>mq*/
152 | // adapted from matchMedia polyfill
153 | // by Scott Jehl and Paul Irish
154 | // gist.github.com/786768
155 | testMediaQuery = function( mq ) {
156 |
157 | var matchMedia = window.matchMedia || window.msMatchMedia;
158 | if ( matchMedia ) {
159 | return matchMedia(mq) && matchMedia(mq).matches || false;
160 | }
161 |
162 | var bool;
163 |
164 | injectElementWithStyles('@media ' + mq + ' { #' + mod + ' { position: absolute; } }', function( node ) {
165 | bool = (window.getComputedStyle ?
166 | getComputedStyle(node, null) :
167 | node.currentStyle)['position'] == 'absolute';
168 | });
169 |
170 | return bool;
171 |
172 | },
173 | /*>>mq*/
174 |
175 |
176 | /*>>hasevent*/
177 | //
178 | // isEventSupported determines if a given element supports the given event
179 | // kangax.github.com/iseventsupported/
180 | //
181 | // The following results are known incorrects:
182 | // Modernizr.hasEvent("webkitTransitionEnd", elem) // false negative
183 | // Modernizr.hasEvent("textInput") // in Webkit. github.com/Modernizr/Modernizr/issues/333
184 | // ...
185 | isEventSupported = (function() {
186 |
187 | var TAGNAMES = {
188 | 'select': 'input', 'change': 'input',
189 | 'submit': 'form', 'reset': 'form',
190 | 'error': 'img', 'load': 'img', 'abort': 'img'
191 | };
192 |
193 | function isEventSupported( eventName, element ) {
194 |
195 | element = element || document.createElement(TAGNAMES[eventName] || 'div');
196 | eventName = 'on' + eventName;
197 |
198 | // When using `setAttribute`, IE skips "unload", WebKit skips "unload" and "resize", whereas `in` "catches" those
199 | var isSupported = eventName in element;
200 |
201 | if ( !isSupported ) {
202 | // If it has no `setAttribute` (i.e. doesn't implement Node interface), try generic element
203 | if ( !element.setAttribute ) {
204 | element = document.createElement('div');
205 | }
206 | if ( element.setAttribute && element.removeAttribute ) {
207 | element.setAttribute(eventName, '');
208 | isSupported = is(element[eventName], 'function');
209 |
210 | // If property was created, "remove it" (by setting value to `undefined`)
211 | if ( !is(element[eventName], 'undefined') ) {
212 | element[eventName] = undefined;
213 | }
214 | element.removeAttribute(eventName);
215 | }
216 | }
217 |
218 | element = null;
219 | return isSupported;
220 | }
221 | return isEventSupported;
222 | })(),
223 | /*>>hasevent*/
224 |
225 | // TODO :: Add flag for hasownprop ? didn't last time
226 |
227 | // hasOwnProperty shim by kangax needed for Safari 2.0 support
228 | _hasOwnProperty = ({}).hasOwnProperty, hasOwnProp;
229 |
230 | if ( !is(_hasOwnProperty, 'undefined') && !is(_hasOwnProperty.call, 'undefined') ) {
231 | hasOwnProp = function (object, property) {
232 | return _hasOwnProperty.call(object, property);
233 | };
234 | }
235 | else {
236 | hasOwnProp = function (object, property) { /* yes, this can give false positives/negatives, but most of the time we don't care about those */
237 | return ((property in object) && is(object.constructor.prototype[property], 'undefined'));
238 | };
239 | }
240 |
241 | // Adapted from ES5-shim https://github.com/kriskowal/es5-shim/blob/master/es5-shim.js
242 | // es5.github.com/#x15.3.4.5
243 |
244 | if (!Function.prototype.bind) {
245 | Function.prototype.bind = function bind(that) {
246 |
247 | var target = this;
248 |
249 | if (typeof target != "function") {
250 | throw new TypeError();
251 | }
252 |
253 | var args = slice.call(arguments, 1),
254 | bound = function () {
255 |
256 | if (this instanceof bound) {
257 |
258 | var F = function(){};
259 | F.prototype = target.prototype;
260 | var self = new F();
261 |
262 | var result = target.apply(
263 | self,
264 | args.concat(slice.call(arguments))
265 | );
266 | if (Object(result) === result) {
267 | return result;
268 | }
269 | return self;
270 |
271 | } else {
272 |
273 | return target.apply(
274 | that,
275 | args.concat(slice.call(arguments))
276 | );
277 |
278 | }
279 |
280 | };
281 |
282 | return bound;
283 | };
284 | }
285 |
286 | /**
287 | * setCss applies given styles to the Modernizr DOM node.
288 | */
289 | function setCss( str ) {
290 | mStyle.cssText = str;
291 | }
292 |
293 | /**
294 | * setCssAll extrapolates all vendor-specific css strings.
295 | */
296 | function setCssAll( str1, str2 ) {
297 | return setCss(prefixes.join(str1 + ';') + ( str2 || '' ));
298 | }
299 |
300 | /**
301 | * is returns a boolean for if typeof obj is exactly type.
302 | */
303 | function is( obj, type ) {
304 | return typeof obj === type;
305 | }
306 |
307 | /**
308 | * contains returns a boolean for if substr is found within str.
309 | */
310 | function contains( str, substr ) {
311 | return !!~('' + str).indexOf(substr);
312 | }
313 |
314 | /*>>testprop*/
315 |
316 | // testProps is a generic CSS / DOM property test.
317 |
318 | // In testing support for a given CSS property, it's legit to test:
319 | // `elem.style[styleName] !== undefined`
320 | // If the property is supported it will return an empty string,
321 | // if unsupported it will return undefined.
322 |
323 | // We'll take advantage of this quick test and skip setting a style
324 | // on our modernizr element, but instead just testing undefined vs
325 | // empty string.
326 |
327 | // Because the testing of the CSS property names (with "-", as
328 | // opposed to the camelCase DOM properties) is non-portable and
329 | // non-standard but works in WebKit and IE (but not Gecko or Opera),
330 | // we explicitly reject properties with dashes so that authors
331 | // developing in WebKit or IE first don't end up with
332 | // browser-specific content by accident.
333 |
334 | function testProps( props, prefixed ) {
335 | for ( var i in props ) {
336 | var prop = props[i];
337 | if ( !contains(prop, "-") && mStyle[prop] !== undefined ) {
338 | return prefixed == 'pfx' ? prop : true;
339 | }
340 | }
341 | return false;
342 | }
343 | /*>>testprop*/
344 |
345 | // TODO :: add testDOMProps
346 | /**
347 | * testDOMProps is a generic DOM property test; if a browser supports
348 | * a certain property, it won't return undefined for it.
349 | */
350 | function testDOMProps( props, obj, elem ) {
351 | for ( var i in props ) {
352 | var item = obj[props[i]];
353 | if ( item !== undefined) {
354 |
355 | // return the property name as a string
356 | if (elem === false) return props[i];
357 |
358 | // let's bind a function
359 | if (is(item, 'function')){
360 | // default to autobind unless override
361 | return item.bind(elem || obj);
362 | }
363 |
364 | // return the unbound function or obj or value
365 | return item;
366 | }
367 | }
368 | return false;
369 | }
370 |
371 | /*>>testallprops*/
372 | /**
373 | * testPropsAll tests a list of DOM properties we want to check against.
374 | * We specify literally ALL possible (known and/or likely) properties on
375 | * the element including the non-vendor prefixed one, for forward-
376 | * compatibility.
377 | */
378 | function testPropsAll( prop, prefixed, elem ) {
379 |
380 | var ucProp = prop.charAt(0).toUpperCase() + prop.slice(1),
381 | props = (prop + ' ' + cssomPrefixes.join(ucProp + ' ') + ucProp).split(' ');
382 |
383 | // did they call .prefixed('boxSizing') or are we just testing a prop?
384 | if(is(prefixed, "string") || is(prefixed, "undefined")) {
385 | return testProps(props, prefixed);
386 |
387 | // otherwise, they called .prefixed('requestAnimationFrame', window[, elem])
388 | } else {
389 | props = (prop + ' ' + (domPrefixes).join(ucProp + ' ') + ucProp).split(' ');
390 | return testDOMProps(props, prefixed, elem);
391 | }
392 | }
393 | /*>>testallprops*/
394 |
395 |
396 | /**
397 | * Tests
398 | * -----
399 | */
400 |
401 | // The *new* flexbox
402 | // dev.w3.org/csswg/css3-flexbox
403 |
404 | tests['flexbox'] = function() {
405 | return testPropsAll('flexWrap');
406 | };
407 |
408 | // The *old* flexbox
409 | // www.w3.org/TR/2009/WD-css3-flexbox-20090723/
410 |
411 | tests['flexboxlegacy'] = function() {
412 | return testPropsAll('boxDirection');
413 | };
414 |
415 | // On the S60 and BB Storm, getContext exists, but always returns undefined
416 | // so we actually have to call getContext() to verify
417 | // github.com/Modernizr/Modernizr/issues/issue/97/
418 |
419 | tests['canvas'] = function() {
420 | var elem = document.createElement('canvas');
421 | return !!(elem.getContext && elem.getContext('2d'));
422 | };
423 |
424 | tests['canvastext'] = function() {
425 | return !!(Modernizr['canvas'] && is(document.createElement('canvas').getContext('2d').fillText, 'function'));
426 | };
427 |
428 | // webk.it/70117 is tracking a legit WebGL feature detect proposal
429 |
430 | // We do a soft detect which may false positive in order to avoid
431 | // an expensive context creation: bugzil.la/732441
432 |
433 | tests['webgl'] = function() {
434 | return !!window.WebGLRenderingContext;
435 | };
436 |
437 | /*
438 | * The Modernizr.touch test only indicates if the browser supports
439 | * touch events, which does not necessarily reflect a touchscreen
440 | * device, as evidenced by tablets running Windows 7 or, alas,
441 | * the Palm Pre / WebOS (touch) phones.
442 | *
443 | * Additionally, Chrome (desktop) used to lie about its support on this,
444 | * but that has since been rectified: crbug.com/36415
445 | *
446 | * We also test for Firefox 4 Multitouch Support.
447 | *
448 | * For more info, see: modernizr.github.com/Modernizr/touch.html
449 | */
450 |
451 | tests['touch'] = function() {
452 | var bool;
453 |
454 | if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
455 | bool = true;
456 | } else {
457 | injectElementWithStyles(['@media (',prefixes.join('touch-enabled),('),mod,')','{#modernizr{top:9px;position:absolute}}'].join(''), function( node ) {
458 | bool = node.offsetTop === 9;
459 | });
460 | }
461 |
462 | return bool;
463 | };
464 |
465 |
466 | // geolocation is often considered a trivial feature detect...
467 | // Turns out, it's quite tricky to get right:
468 | //
469 | // Using !!navigator.geolocation does two things we don't want. It:
470 | // 1. Leaks memory in IE9: github.com/Modernizr/Modernizr/issues/513
471 | // 2. Disables page caching in WebKit: webk.it/43956
472 | //
473 | // Meanwhile, in Firefox < 8, an about:config setting could expose
474 | // a false positive that would throw an exception: bugzil.la/688158
475 |
476 | tests['geolocation'] = function() {
477 | return 'geolocation' in navigator;
478 | };
479 |
480 |
481 | tests['postmessage'] = function() {
482 | return !!window.postMessage;
483 | };
484 |
485 |
486 | // Chrome incognito mode used to throw an exception when using openDatabase
487 | // It doesn't anymore.
488 | tests['websqldatabase'] = function() {
489 | return !!window.openDatabase;
490 | };
491 |
492 | // Vendors had inconsistent prefixing with the experimental Indexed DB:
493 | // - Webkit's implementation is accessible through webkitIndexedDB
494 | // - Firefox shipped moz_indexedDB before FF4b9, but since then has been mozIndexedDB
495 | // For speed, we don't test the legacy (and beta-only) indexedDB
496 | tests['indexedDB'] = function() {
497 | return !!testPropsAll("indexedDB", window);
498 | };
499 |
500 | // documentMode logic from YUI to filter out IE8 Compat Mode
501 | // which false positives.
502 | tests['hashchange'] = function() {
503 | return isEventSupported('hashchange', window) && (document.documentMode === undefined || document.documentMode > 7);
504 | };
505 |
506 | // Per 1.6:
507 | // This used to be Modernizr.historymanagement but the longer
508 | // name has been deprecated in favor of a shorter and property-matching one.
509 | // The old API is still available in 1.6, but as of 2.0 will throw a warning,
510 | // and in the first release thereafter disappear entirely.
511 | tests['history'] = function() {
512 | return !!(window.history && history.pushState);
513 | };
514 |
515 | tests['draganddrop'] = function() {
516 | var div = document.createElement('div');
517 | return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div);
518 | };
519 |
520 | // FF3.6 was EOL'ed on 4/24/12, but the ESR version of FF10
521 | // will be supported until FF19 (2/12/13), at which time, ESR becomes FF17.
522 | // FF10 still uses prefixes, so check for it until then.
523 | // for more ESR info, see: mozilla.org/en-US/firefox/organizations/faq/
524 | tests['websockets'] = function() {
525 | return 'WebSocket' in window || 'MozWebSocket' in window;
526 | };
527 |
528 |
529 | // css-tricks.com/rgba-browser-support/
530 | tests['rgba'] = function() {
531 | // Set an rgba() color and check the returned value
532 |
533 | setCss('background-color:rgba(150,255,150,.5)');
534 |
535 | return contains(mStyle.backgroundColor, 'rgba');
536 | };
537 |
538 | tests['hsla'] = function() {
539 | // Same as rgba(), in fact, browsers re-map hsla() to rgba() internally,
540 | // except IE9 who retains it as hsla
541 |
542 | setCss('background-color:hsla(120,40%,100%,.5)');
543 |
544 | return contains(mStyle.backgroundColor, 'rgba') || contains(mStyle.backgroundColor, 'hsla');
545 | };
546 |
547 | tests['multiplebgs'] = function() {
548 | // Setting multiple images AND a color on the background shorthand property
549 | // and then querying the style.background property value for the number of
550 | // occurrences of "url(" is a reliable method for detecting ACTUAL support for this!
551 |
552 | setCss('background:url(https://),url(https://),red url(https://)');
553 |
554 | // If the UA supports multiple backgrounds, there should be three occurrences
555 | // of the string "url(" in the return value for elemStyle.background
556 |
557 | return (/(url\s*\(.*?){3}/).test(mStyle.background);
558 | };
559 |
560 |
561 |
562 | // this will false positive in Opera Mini
563 | // github.com/Modernizr/Modernizr/issues/396
564 |
565 | tests['backgroundsize'] = function() {
566 | return testPropsAll('backgroundSize');
567 | };
568 |
569 | tests['borderimage'] = function() {
570 | return testPropsAll('borderImage');
571 | };
572 |
573 |
574 | // Super comprehensive table about all the unique implementations of
575 | // border-radius: muddledramblings.com/table-of-css3-border-radius-compliance
576 |
577 | tests['borderradius'] = function() {
578 | return testPropsAll('borderRadius');
579 | };
580 |
581 | // WebOS unfortunately false positives on this test.
582 | tests['boxshadow'] = function() {
583 | return testPropsAll('boxShadow');
584 | };
585 |
586 | // FF3.0 will false positive on this test
587 | tests['textshadow'] = function() {
588 | return document.createElement('div').style.textShadow === '';
589 | };
590 |
591 |
592 | tests['opacity'] = function() {
593 | // Browsers that actually have CSS Opacity implemented have done so
594 | // according to spec, which means their return values are within the
595 | // range of [0.0,1.0] - including the leading zero.
596 |
597 | setCssAll('opacity:.55');
598 |
599 | // The non-literal . in this regex is intentional:
600 | // German Chrome returns this value as 0,55
601 | // github.com/Modernizr/Modernizr/issues/#issue/59/comment/516632
602 | return (/^0.55$/).test(mStyle.opacity);
603 | };
604 |
605 |
606 | // Note, Android < 4 will pass this test, but can only animate
607 | // a single property at a time
608 | // goo.gl/v3V4Gp
609 | tests['cssanimations'] = function() {
610 | return testPropsAll('animationName');
611 | };
612 |
613 |
614 | tests['csscolumns'] = function() {
615 | return testPropsAll('columnCount');
616 | };
617 |
618 |
619 | tests['cssgradients'] = function() {
620 | /**
621 | * For CSS Gradients syntax, please see:
622 | * webkit.org/blog/175/introducing-css-gradients/
623 | * developer.mozilla.org/en/CSS/-moz-linear-gradient
624 | * developer.mozilla.org/en/CSS/-moz-radial-gradient
625 | * dev.w3.org/csswg/css3-images/#gradients-
626 | */
627 |
628 | var str1 = 'background-image:',
629 | str2 = 'gradient(linear,left top,right bottom,from(#9f9),to(white));',
630 | str3 = 'linear-gradient(left top,#9f9, white);';
631 |
632 | setCss(
633 | // legacy webkit syntax (FIXME: remove when syntax not in use anymore)
634 | (str1 + '-webkit- '.split(' ').join(str2 + str1) +
635 | // standard syntax // trailing 'background-image:'
636 | prefixes.join(str3 + str1)).slice(0, -str1.length)
637 | );
638 |
639 | return contains(mStyle.backgroundImage, 'gradient');
640 | };
641 |
642 |
643 | tests['cssreflections'] = function() {
644 | return testPropsAll('boxReflect');
645 | };
646 |
647 |
648 | tests['csstransforms'] = function() {
649 | return !!testPropsAll('transform');
650 | };
651 |
652 |
653 | tests['csstransforms3d'] = function() {
654 |
655 | var ret = !!testPropsAll('perspective');
656 |
657 | // Webkit's 3D transforms are passed off to the browser's own graphics renderer.
658 | // It works fine in Safari on Leopard and Snow Leopard, but not in Chrome in
659 | // some conditions. As a result, Webkit typically recognizes the syntax but
660 | // will sometimes throw a false positive, thus we must do a more thorough check:
661 | if ( ret && 'webkitPerspective' in docElement.style ) {
662 |
663 | // Webkit allows this media query to succeed only if the feature is enabled.
664 | // `@media (transform-3d),(-webkit-transform-3d){ ... }`
665 | injectElementWithStyles('@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}', function( node, rule ) {
666 | ret = node.offsetLeft === 9 && node.offsetHeight === 3;
667 | });
668 | }
669 | return ret;
670 | };
671 |
672 |
673 | tests['csstransitions'] = function() {
674 | return testPropsAll('transition');
675 | };
676 |
677 |
678 | /*>>fontface*/
679 | // @font-face detection routine by Diego Perini
680 | // javascript.nwbox.com/CSSSupport/
681 |
682 | // false positives:
683 | // WebOS github.com/Modernizr/Modernizr/issues/342
684 | // WP7 github.com/Modernizr/Modernizr/issues/538
685 | tests['fontface'] = function() {
686 | var bool;
687 |
688 | injectElementWithStyles('@font-face {font-family:"font";src:url("https://")}', function( node, rule ) {
689 | var style = document.getElementById('smodernizr'),
690 | sheet = style.sheet || style.styleSheet,
691 | cssText = sheet ? (sheet.cssRules && sheet.cssRules[0] ? sheet.cssRules[0].cssText : sheet.cssText || '') : '';
692 |
693 | bool = /src/i.test(cssText) && cssText.indexOf(rule.split(' ')[0]) === 0;
694 | });
695 |
696 | return bool;
697 | };
698 | /*>>fontface*/
699 |
700 | // CSS generated content detection
701 | tests['generatedcontent'] = function() {
702 | var bool;
703 |
704 | injectElementWithStyles(['#',mod,'{font:0/0 a}#',mod,':after{content:"',smile,'";visibility:hidden;font:3px/1 a}'].join(''), function( node ) {
705 | bool = node.offsetHeight >= 3;
706 | });
707 |
708 | return bool;
709 | };
710 |
711 |
712 |
713 | // These tests evaluate support of the video/audio elements, as well as
714 | // testing what types of content they support.
715 | //
716 | // We're using the Boolean constructor here, so that we can extend the value
717 | // e.g. Modernizr.video // true
718 | // Modernizr.video.ogg // 'probably'
719 | //
720 | // Codec values from : github.com/NielsLeenheer/html5test/blob/9106a8/index.html#L845
721 | // thx to NielsLeenheer and zcorpan
722 |
723 | // Note: in some older browsers, "no" was a return value instead of empty string.
724 | // It was live in FF3.5.0 and 3.5.1, but fixed in 3.5.2
725 | // It was also live in Safari 4.0.0 - 4.0.4, but fixed in 4.0.5
726 |
727 | tests['video'] = function() {
728 | var elem = document.createElement('video'),
729 | bool = false;
730 |
731 | // IE9 Running on Windows Server SKU can cause an exception to be thrown, bug #224
732 | try {
733 | if ( bool = !!elem.canPlayType ) {
734 | bool = new Boolean(bool);
735 | bool.ogg = elem.canPlayType('video/ogg; codecs="theora"') .replace(/^no$/,'');
736 |
737 | // Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546
738 | bool.h264 = elem.canPlayType('video/mp4; codecs="avc1.42E01E"') .replace(/^no$/,'');
739 |
740 | bool.webm = elem.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,'');
741 | }
742 |
743 | } catch(e) { }
744 |
745 | return bool;
746 | };
747 |
748 | tests['audio'] = function() {
749 | var elem = document.createElement('audio'),
750 | bool = false;
751 |
752 | try {
753 | if ( bool = !!elem.canPlayType ) {
754 | bool = new Boolean(bool);
755 | bool.ogg = elem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,'');
756 | bool.mp3 = elem.canPlayType('audio/mpeg;') .replace(/^no$/,'');
757 |
758 | // Mimetypes accepted:
759 | // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements
760 | // bit.ly/iphoneoscodecs
761 | bool.wav = elem.canPlayType('audio/wav; codecs="1"') .replace(/^no$/,'');
762 | bool.m4a = ( elem.canPlayType('audio/x-m4a;') ||
763 | elem.canPlayType('audio/aac;')) .replace(/^no$/,'');
764 | }
765 | } catch(e) { }
766 |
767 | return bool;
768 | };
769 |
770 |
771 | // In FF4, if disabled, window.localStorage should === null.
772 |
773 | // Normally, we could not test that directly and need to do a
774 | // `('localStorage' in window) && ` test first because otherwise Firefox will
775 | // throw bugzil.la/365772 if cookies are disabled
776 |
777 | // Also in iOS5 Private Browsing mode, attempting to use localStorage.setItem
778 | // will throw the exception:
779 | // QUOTA_EXCEEDED_ERRROR DOM Exception 22.
780 | // Peculiarly, getItem and removeItem calls do not throw.
781 |
782 | // Because we are forced to try/catch this, we'll go aggressive.
783 |
784 | // Just FWIW: IE8 Compat mode supports these features completely:
785 | // www.quirksmode.org/dom/html5.html
786 | // But IE8 doesn't support either with local files
787 |
788 | tests['localstorage'] = function() {
789 | try {
790 | localStorage.setItem(mod, mod);
791 | localStorage.removeItem(mod);
792 | return true;
793 | } catch(e) {
794 | return false;
795 | }
796 | };
797 |
798 | tests['sessionstorage'] = function() {
799 | try {
800 | sessionStorage.setItem(mod, mod);
801 | sessionStorage.removeItem(mod);
802 | return true;
803 | } catch(e) {
804 | return false;
805 | }
806 | };
807 |
808 |
809 | tests['webworkers'] = function() {
810 | return !!window.Worker;
811 | };
812 |
813 |
814 | tests['applicationcache'] = function() {
815 | return !!window.applicationCache;
816 | };
817 |
818 |
819 | // Thanks to Erik Dahlstrom
820 | tests['svg'] = function() {
821 | return !!document.createElementNS && !!document.createElementNS(ns.svg, 'svg').createSVGRect;
822 | };
823 |
824 | // specifically for SVG inline in HTML, not within XHTML
825 | // test page: paulirish.com/demo/inline-svg
826 | tests['inlinesvg'] = function() {
827 | var div = document.createElement('div');
828 | div.innerHTML = '';
829 | return (div.firstChild && div.firstChild.namespaceURI) == ns.svg;
830 | };
831 |
832 | // SVG SMIL animation
833 | tests['smil'] = function() {
834 | return !!document.createElementNS && /SVGAnimate/.test(toString.call(document.createElementNS(ns.svg, 'animate')));
835 | };
836 |
837 | // This test is only for clip paths in SVG proper, not clip paths on HTML content
838 | // demo: srufaculty.sru.edu/david.dailey/svg/newstuff/clipPath4.svg
839 |
840 | // However read the comments to dig into applying SVG clippaths to HTML content here:
841 | // github.com/Modernizr/Modernizr/issues/213#issuecomment-1149491
842 | tests['svgclippaths'] = function() {
843 | return !!document.createElementNS && /SVGClipPath/.test(toString.call(document.createElementNS(ns.svg, 'clipPath')));
844 | };
845 |
846 | /*>>webforms*/
847 | // input features and input types go directly onto the ret object, bypassing the tests loop.
848 | // Hold this guy to execute in a moment.
849 | function webforms() {
850 | /*>>input*/
851 | // Run through HTML5's new input attributes to see if the UA understands any.
852 | // We're using f which is the element created early on
853 | // Mike Taylr has created a comprehensive resource for testing these attributes
854 | // when applied to all input types:
855 | // miketaylr.com/code/input-type-attr.html
856 | // spec: www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
857 |
858 | // Only input placeholder is tested while textarea's placeholder is not.
859 | // Currently Safari 4 and Opera 11 have support only for the input placeholder
860 | // Both tests are available in feature-detects/forms-placeholder.js
861 | Modernizr['input'] = (function( props ) {
862 | for ( var i = 0, len = props.length; i < len; i++ ) {
863 | attrs[ props[i] ] = !!(props[i] in inputElem);
864 | }
865 | if (attrs.list){
866 | // safari false positive's on datalist: webk.it/74252
867 | // see also github.com/Modernizr/Modernizr/issues/146
868 | attrs.list = !!(document.createElement('datalist') && window.HTMLDataListElement);
869 | }
870 | return attrs;
871 | })('autocomplete autofocus list placeholder max min multiple pattern required step'.split(' '));
872 | /*>>input*/
873 |
874 | /*>>inputtypes*/
875 | // Run through HTML5's new input types to see if the UA understands any.
876 | // This is put behind the tests runloop because it doesn't return a
877 | // true/false like all the other tests; instead, it returns an object
878 | // containing each input type with its corresponding true/false value
879 |
880 | // Big thanks to @miketaylr for the html5 forms expertise. miketaylr.com/
881 | Modernizr['inputtypes'] = (function(props) {
882 |
883 | for ( var i = 0, bool, inputElemType, defaultView, len = props.length; i < len; i++ ) {
884 |
885 | inputElem.setAttribute('type', inputElemType = props[i]);
886 | bool = inputElem.type !== 'text';
887 |
888 | // We first check to see if the type we give it sticks..
889 | // If the type does, we feed it a textual value, which shouldn't be valid.
890 | // If the value doesn't stick, we know there's input sanitization which infers a custom UI
891 | if ( bool ) {
892 |
893 | inputElem.value = smile;
894 | inputElem.style.cssText = 'position:absolute;visibility:hidden;';
895 |
896 | if ( /^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined ) {
897 |
898 | docElement.appendChild(inputElem);
899 | defaultView = document.defaultView;
900 |
901 | // Safari 2-4 allows the smiley as a value, despite making a slider
902 | bool = defaultView.getComputedStyle &&
903 | defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== 'textfield' &&
904 | // Mobile android web browser has false positive, so must
905 | // check the height to see if the widget is actually there.
906 | (inputElem.offsetHeight !== 0);
907 |
908 | docElement.removeChild(inputElem);
909 |
910 | } else if ( /^(search|tel)$/.test(inputElemType) ){
911 | // Spec doesn't define any special parsing or detectable UI
912 | // behaviors so we pass these through as true
913 |
914 | // Interestingly, opera fails the earlier test, so it doesn't
915 | // even make it here.
916 |
917 | } else if ( /^(url|email)$/.test(inputElemType) ) {
918 | // Real url and email support comes with prebaked validation.
919 | bool = inputElem.checkValidity && inputElem.checkValidity() === false;
920 |
921 | } else {
922 | // If the upgraded input compontent rejects the :) text, we got a winner
923 | bool = inputElem.value != smile;
924 | }
925 | }
926 |
927 | inputs[ props[i] ] = !!bool;
928 | }
929 | return inputs;
930 | })('search tel url email datetime date month week time datetime-local number range color'.split(' '));
931 | /*>>inputtypes*/
932 | }
933 | /*>>webforms*/
934 |
935 |
936 | // End of test definitions
937 | // -----------------------
938 |
939 |
940 |
941 | // Run through all tests and detect their support in the current UA.
942 | // todo: hypothetically we could be doing an array of tests and use a basic loop here.
943 | for ( var feature in tests ) {
944 | if ( hasOwnProp(tests, feature) ) {
945 | // run the test, throw the return value into the Modernizr,
946 | // then based on that boolean, define an appropriate className
947 | // and push it into an array of classes we'll join later.
948 | featureName = feature.toLowerCase();
949 | Modernizr[featureName] = tests[feature]();
950 |
951 | classes.push((Modernizr[featureName] ? '' : 'no-') + featureName);
952 | }
953 | }
954 |
955 | /*>>webforms*/
956 | // input tests need to run.
957 | Modernizr.input || webforms();
958 | /*>>webforms*/
959 |
960 |
961 | /**
962 | * addTest allows the user to define their own feature tests
963 | * the result will be added onto the Modernizr object,
964 | * as well as an appropriate className set on the html element
965 | *
966 | * @param feature - String naming the feature
967 | * @param test - Function returning true if feature is supported, false if not
968 | */
969 | Modernizr.addTest = function ( feature, test ) {
970 | if ( typeof feature == 'object' ) {
971 | for ( var key in feature ) {
972 | if ( hasOwnProp( feature, key ) ) {
973 | Modernizr.addTest( key, feature[ key ] );
974 | }
975 | }
976 | } else {
977 |
978 | feature = feature.toLowerCase();
979 |
980 | if ( Modernizr[feature] !== undefined ) {
981 | // we're going to quit if you're trying to overwrite an existing test
982 | // if we were to allow it, we'd do this:
983 | // var re = new RegExp("\\b(no-)?" + feature + "\\b");
984 | // docElement.className = docElement.className.replace( re, '' );
985 | // but, no rly, stuff 'em.
986 | return Modernizr;
987 | }
988 |
989 | test = typeof test == 'function' ? test() : test;
990 |
991 | if (typeof enableClasses !== "undefined" && enableClasses) {
992 | docElement.className += ' ' + (test ? '' : 'no-') + feature;
993 | }
994 | Modernizr[feature] = test;
995 |
996 | }
997 |
998 | return Modernizr; // allow chaining.
999 | };
1000 |
1001 |
1002 | // Reset modElem.cssText to nothing to reduce memory footprint.
1003 | setCss('');
1004 | modElem = inputElem = null;
1005 |
1006 | /*>>shiv*/
1007 | /**
1008 | * @preserve HTML5 Shiv prev3.7.1 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
1009 | */
1010 | ;(function(window, document) {
1011 | /*jshint evil:true */
1012 | /** version */
1013 | var version = '3.7.0';
1014 |
1015 | /** Preset options */
1016 | var options = window.html5 || {};
1017 |
1018 | /** Used to skip problem elements */
1019 | var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i;
1020 |
1021 | /** Not all elements can be cloned in IE **/
1022 | var saveClones = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i;
1023 |
1024 | /** Detect whether the browser supports default html5 styles */
1025 | var supportsHtml5Styles;
1026 |
1027 | /** Name of the expando, to work with multiple documents or to re-shiv one document */
1028 | var expando = '_html5shiv';
1029 |
1030 | /** The id for the the documents expando */
1031 | var expanID = 0;
1032 |
1033 | /** Cached data for each document */
1034 | var expandoData = {};
1035 |
1036 | /** Detect whether the browser supports unknown elements */
1037 | var supportsUnknownElements;
1038 |
1039 | (function() {
1040 | try {
1041 | var a = document.createElement('a');
1042 | a.innerHTML = '';
1043 | //if the hidden property is implemented we can assume, that the browser supports basic HTML5 Styles
1044 | supportsHtml5Styles = ('hidden' in a);
1045 |
1046 | supportsUnknownElements = a.childNodes.length == 1 || (function() {
1047 | // assign a false positive if unable to shiv
1048 | (document.createElement)('a');
1049 | var frag = document.createDocumentFragment();
1050 | return (
1051 | typeof frag.cloneNode == 'undefined' ||
1052 | typeof frag.createDocumentFragment == 'undefined' ||
1053 | typeof frag.createElement == 'undefined'
1054 | );
1055 | }());
1056 | } catch(e) {
1057 | // assign a false positive if detection fails => unable to shiv
1058 | supportsHtml5Styles = true;
1059 | supportsUnknownElements = true;
1060 | }
1061 |
1062 | }());
1063 |
1064 | /*--------------------------------------------------------------------------*/
1065 |
1066 | /**
1067 | * Creates a style sheet with the given CSS text and adds it to the document.
1068 | * @private
1069 | * @param {Document} ownerDocument The document.
1070 | * @param {String} cssText The CSS text.
1071 | * @returns {StyleSheet} The style element.
1072 | */
1073 | function addStyleSheet(ownerDocument, cssText) {
1074 | var p = ownerDocument.createElement('p'),
1075 | parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement;
1076 |
1077 | p.innerHTML = 'x';
1078 | return parent.insertBefore(p.lastChild, parent.firstChild);
1079 | }
1080 |
1081 | /**
1082 | * Returns the value of `html5.elements` as an array.
1083 | * @private
1084 | * @returns {Array} An array of shived element node names.
1085 | */
1086 | function getElements() {
1087 | var elements = html5.elements;
1088 | return typeof elements == 'string' ? elements.split(' ') : elements;
1089 | }
1090 |
1091 | /**
1092 | * Returns the data associated to the given document
1093 | * @private
1094 | * @param {Document} ownerDocument The document.
1095 | * @returns {Object} An object of data.
1096 | */
1097 | function getExpandoData(ownerDocument) {
1098 | var data = expandoData[ownerDocument[expando]];
1099 | if (!data) {
1100 | data = {};
1101 | expanID++;
1102 | ownerDocument[expando] = expanID;
1103 | expandoData[expanID] = data;
1104 | }
1105 | return data;
1106 | }
1107 |
1108 | /**
1109 | * returns a shived element for the given nodeName and document
1110 | * @memberOf html5
1111 | * @param {String} nodeName name of the element
1112 | * @param {Document} ownerDocument The context document.
1113 | * @returns {Object} The shived element.
1114 | */
1115 | function createElement(nodeName, ownerDocument, data){
1116 | if (!ownerDocument) {
1117 | ownerDocument = document;
1118 | }
1119 | if(supportsUnknownElements){
1120 | return ownerDocument.createElement(nodeName);
1121 | }
1122 | if (!data) {
1123 | data = getExpandoData(ownerDocument);
1124 | }
1125 | var node;
1126 |
1127 | if (data.cache[nodeName]) {
1128 | node = data.cache[nodeName].cloneNode();
1129 | } else if (saveClones.test(nodeName)) {
1130 | node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode();
1131 | } else {
1132 | node = data.createElem(nodeName);
1133 | }
1134 |
1135 | // Avoid adding some elements to fragments in IE < 9 because
1136 | // * Attributes like `name` or `type` cannot be set/changed once an element
1137 | // is inserted into a document/fragment
1138 | // * Link elements with `src` attributes that are inaccessible, as with
1139 | // a 403 response, will cause the tab/window to crash
1140 | // * Script elements appended to fragments will execute when their `src`
1141 | // or `text` property is set
1142 | return node.canHaveChildren && !reSkip.test(nodeName) && !node.tagUrn ? data.frag.appendChild(node) : node;
1143 | }
1144 |
1145 | /**
1146 | * returns a shived DocumentFragment for the given document
1147 | * @memberOf html5
1148 | * @param {Document} ownerDocument The context document.
1149 | * @returns {Object} The shived DocumentFragment.
1150 | */
1151 | function createDocumentFragment(ownerDocument, data){
1152 | if (!ownerDocument) {
1153 | ownerDocument = document;
1154 | }
1155 | if(supportsUnknownElements){
1156 | return ownerDocument.createDocumentFragment();
1157 | }
1158 | data = data || getExpandoData(ownerDocument);
1159 | var clone = data.frag.cloneNode(),
1160 | i = 0,
1161 | elems = getElements(),
1162 | l = elems.length;
1163 | for(;i>shiv*/
1309 |
1310 | // Assign private properties to the return object with prefix
1311 | Modernizr._version = version;
1312 |
1313 | // expose these for the plugin API. Look in the source for how to join() them against your input
1314 | /*>>prefixes*/
1315 | Modernizr._prefixes = prefixes;
1316 | /*>>prefixes*/
1317 | /*>>domprefixes*/
1318 | Modernizr._domPrefixes = domPrefixes;
1319 | Modernizr._cssomPrefixes = cssomPrefixes;
1320 | /*>>domprefixes*/
1321 |
1322 | /*>>mq*/
1323 | // Modernizr.mq tests a given media query, live against the current state of the window
1324 | // A few important notes:
1325 | // * If a browser does not support media queries at all (eg. oldIE) the mq() will always return false
1326 | // * A max-width or orientation query will be evaluated against the current state, which may change later.
1327 | // * You must specify values. Eg. If you are testing support for the min-width media query use:
1328 | // Modernizr.mq('(min-width:0)')
1329 | // usage:
1330 | // Modernizr.mq('only screen and (max-width:768)')
1331 | Modernizr.mq = testMediaQuery;
1332 | /*>>mq*/
1333 |
1334 | /*>>hasevent*/
1335 | // Modernizr.hasEvent() detects support for a given event, with an optional element to test on
1336 | // Modernizr.hasEvent('gesturestart', elem)
1337 | Modernizr.hasEvent = isEventSupported;
1338 | /*>>hasevent*/
1339 |
1340 | /*>>testprop*/
1341 | // Modernizr.testProp() investigates whether a given style property is recognized
1342 | // Note that the property names must be provided in the camelCase variant.
1343 | // Modernizr.testProp('pointerEvents')
1344 | Modernizr.testProp = function(prop){
1345 | return testProps([prop]);
1346 | };
1347 | /*>>testprop*/
1348 |
1349 | /*>>testallprops*/
1350 | // Modernizr.testAllProps() investigates whether a given style property,
1351 | // or any of its vendor-prefixed variants, is recognized
1352 | // Note that the property names must be provided in the camelCase variant.
1353 | // Modernizr.testAllProps('boxSizing')
1354 | Modernizr.testAllProps = testPropsAll;
1355 | /*>>testallprops*/
1356 |
1357 |
1358 | /*>>teststyles*/
1359 | // Modernizr.testStyles() allows you to add custom styles to the document and test an element afterwards
1360 | // Modernizr.testStyles('#modernizr { position:absolute }', function(elem, rule){ ... })
1361 | Modernizr.testStyles = injectElementWithStyles;
1362 | /*>>teststyles*/
1363 |
1364 |
1365 | /*>>prefixed*/
1366 | // Modernizr.prefixed() returns the prefixed or nonprefixed property name variant of your input
1367 | // Modernizr.prefixed('boxSizing') // 'MozBoxSizing'
1368 |
1369 | // Properties must be passed as dom-style camelcase, rather than `box-sizing` hypentated style.
1370 | // Return values will also be the camelCase variant, if you need to translate that to hypenated style use:
1371 | //
1372 | // str.replace(/([A-Z])/g, function(str,m1){ return '-' + m1.toLowerCase(); }).replace(/^ms-/,'-ms-');
1373 |
1374 | // If you're trying to ascertain which transition end event to bind to, you might do something like...
1375 | //
1376 | // var transEndEventNames = {
1377 | // 'WebkitTransition' : 'webkitTransitionEnd',
1378 | // 'MozTransition' : 'transitionend',
1379 | // 'OTransition' : 'oTransitionEnd',
1380 | // 'msTransition' : 'MSTransitionEnd',
1381 | // 'transition' : 'transitionend'
1382 | // },
1383 | // transEndEventName = transEndEventNames[ Modernizr.prefixed('transition') ];
1384 |
1385 | Modernizr.prefixed = function(prop, obj, elem){
1386 | if(!obj) {
1387 | return testPropsAll(prop, 'pfx');
1388 | } else {
1389 | // Testing DOM property e.g. Modernizr.prefixed('requestAnimationFrame', window) // 'mozRequestAnimationFrame'
1390 | return testPropsAll(prop, obj, elem);
1391 | }
1392 | };
1393 | /*>>prefixed*/
1394 |
1395 |
1396 | /*>>cssclasses*/
1397 | // Remove "no-js" class from element, if it exists:
1398 | docElement.className = docElement.className.replace(/(^|\s)no-js(\s|$)/, '$1$2') +
1399 |
1400 | // Add the new classes to the element.
1401 | (enableClasses ? ' js ' + classes.join(' ') : '');
1402 | /*>>cssclasses*/
1403 |
1404 | return Modernizr;
1405 |
1406 | })(this, this.document);
1407 |
--------------------------------------------------------------------------------
/public/out.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/public/padding.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/public/qrcode.js:
--------------------------------------------------------------------------------
1 | (function () {
2 | function extend(object) {
3 | // Takes an unlimited number of extenders.
4 | var args = Array.prototype.slice.call(arguments, 1);
5 |
6 | // For each extender, copy their properties on our object.
7 | for (var i = 0, source; source = args[i]; i++) {
8 | if (!source) continue;
9 | for (var property in source) {
10 | object[property] = source[property];
11 | }
12 | }
13 |
14 | return object;
15 | };
16 |
17 | /**
18 | * 获取单个字符的utf8编码
19 | * unicode BMP平面约65535个字符
20 | * @param {num} code
21 | * return {array}
22 | */
23 | function unicodeFormat8(code) {
24 | // 1 byte
25 | var c0, c1, c2;
26 | if (code < 128) {
27 | return [code];
28 | // 2 bytes
29 | } else if (code < 2048) {
30 | c0 = 192 + (code >> 6);
31 | c1 = 128 + (code & 63);
32 | return [c0, c1];
33 | // 3 bytes
34 | } else {
35 | c0 = 224 + (code >> 12);
36 | c1 = 128 + (code >> 6 & 63);
37 | c2 = 128 + (code & 63);
38 | return [c0, c1, c2];
39 | }
40 | }
41 |
42 | /**
43 | * 获取字符串的utf8编码字节串
44 | * @param {string} string
45 | * @return {array}
46 | */
47 | function getUTF8Bytes(string) {
48 | var utf8codes = [];
49 | for (var i = 0; i < string.length; i++) {
50 | var code = string.charCodeAt(i);
51 | var utf8 = unicodeFormat8(code);
52 | for (var j = 0; j < utf8.length; j++) {
53 | utf8codes.push(utf8[j]);
54 | }
55 | }
56 | return utf8codes;
57 | }
58 |
59 | /**
60 | * 二维码算法实现
61 | * @param {string} data 要编码的信息字符串
62 | * @param {num} errorCorrectLevel 纠错等级
63 | */
64 | function QRCodeAlg(data, errorCorrectLevel) {
65 | this.typeNumber = -1; //版本
66 | this.errorCorrectLevel = errorCorrectLevel;
67 | this.modules = null; //二维矩阵,存放最终结果
68 | this.moduleCount = 0; //矩阵大小
69 | this.dataCache = null; //数据缓存
70 | this.rsBlocks = null; //版本数据信息
71 | this.totalDataCount = -1; //可使用的数据量
72 | this.data = data;
73 | this.utf8bytes = getUTF8Bytes(data);
74 | this.make();
75 | }
76 |
77 | QRCodeAlg.prototype = {
78 | constructor: QRCodeAlg,
79 | /**
80 | * 获取二维码矩阵大小
81 | * @return {num} 矩阵大小
82 | */
83 | getModuleCount: function () {
84 | return this.moduleCount;
85 | },
86 | /**
87 | * 编码
88 | */
89 | make: function () {
90 | this.getRightType();
91 | this.dataCache = this.createData();
92 | this.createQrcode();
93 | },
94 | /**
95 | * 设置二位矩阵功能图形
96 | * @param {bool} test 表示是否在寻找最好掩膜阶段
97 | * @param {num} maskPattern 掩膜的版本
98 | */
99 | makeImpl: function (maskPattern) {
100 |
101 | this.moduleCount = this.typeNumber * 4 + 17;
102 | this.modules = new Array(this.moduleCount);
103 |
104 | for (var row = 0; row < this.moduleCount; row++) {
105 |
106 | this.modules[row] = new Array(this.moduleCount);
107 |
108 | }
109 | this.setupPositionProbePattern(0, 0);
110 | this.setupPositionProbePattern(this.moduleCount - 7, 0);
111 | this.setupPositionProbePattern(0, this.moduleCount - 7);
112 | this.setupPositionAdjustPattern();
113 | this.setupTimingPattern();
114 | this.setupTypeInfo(true, maskPattern);
115 |
116 | if (this.typeNumber >= 7) {
117 | this.setupTypeNumber(true);
118 | }
119 | this.mapData(this.dataCache, maskPattern);
120 | },
121 | /**
122 | * 设置二维码的位置探测图形
123 | * @param {num} row 探测图形的中心横坐标
124 | * @param {num} col 探测图形的中心纵坐标
125 | */
126 | setupPositionProbePattern: function (row, col) {
127 |
128 | for (var r = -1; r <= 7; r++) {
129 |
130 | if (row + r <= -1 || this.moduleCount <= row + r) continue;
131 |
132 | for (var c = -1; c <= 7; c++) {
133 |
134 | if (col + c <= -1 || this.moduleCount <= col + c) continue;
135 |
136 | if ((0 <= r && r <= 6 && (c == 0 || c == 6)) || (0 <= c && c <= 6 && (r == 0 || r == 6)) || (2 <= r && r <= 4 && 2 <= c && c <= 4)) {
137 | this.modules[row + r][col + c] = true;
138 | } else {
139 | this.modules[row + r][col + c] = false;
140 | }
141 | }
142 | }
143 | },
144 | /**
145 | * 创建二维码
146 | * @return {[type]} [description]
147 | */
148 | createQrcode: function () {
149 |
150 | var minLostPoint = 0;
151 | var pattern = 0;
152 | var bestModules = null;
153 |
154 | for (var i = 0; i < 8; i++) {
155 |
156 | this.makeImpl(i);
157 |
158 | var lostPoint = QRUtil.getLostPoint(this);
159 | if (i == 0 || minLostPoint > lostPoint) {
160 | minLostPoint = lostPoint;
161 | pattern = i;
162 | bestModules = this.modules;
163 | }
164 | }
165 | this.modules = bestModules;
166 | this.setupTypeInfo(false, pattern);
167 |
168 | if (this.typeNumber >= 7) {
169 | this.setupTypeNumber(false);
170 | }
171 |
172 | },
173 | /**
174 | * 设置定位图形
175 | * @return {[type]} [description]
176 | */
177 | setupTimingPattern: function () {
178 |
179 | for (var r = 8; r < this.moduleCount - 8; r++) {
180 | if (this.modules[r][6] != null) {
181 | continue;
182 | }
183 | this.modules[r][6] = (r % 2 == 0);
184 |
185 | if (this.modules[6][r] != null) {
186 | continue;
187 | }
188 | this.modules[6][r] = (r % 2 == 0);
189 | }
190 | },
191 | /**
192 | * 设置矫正图形
193 | * @return {[type]} [description]
194 | */
195 | setupPositionAdjustPattern: function () {
196 |
197 | var pos = QRUtil.getPatternPosition(this.typeNumber);
198 |
199 | for (var i = 0; i < pos.length; i++) {
200 |
201 | for (var j = 0; j < pos.length; j++) {
202 |
203 | var row = pos[i];
204 | var col = pos[j];
205 |
206 | if (this.modules[row][col] != null) {
207 | continue;
208 | }
209 |
210 | for (var r = -2; r <= 2; r++) {
211 |
212 | for (var c = -2; c <= 2; c++) {
213 |
214 | if (r == -2 || r == 2 || c == -2 || c == 2 || (r == 0 && c == 0)) {
215 | this.modules[row + r][col + c] = true;
216 | } else {
217 | this.modules[row + r][col + c] = false;
218 | }
219 | }
220 | }
221 | }
222 | }
223 | },
224 | /**
225 | * 设置版本信息(7以上版本才有)
226 | * @param {bool} test 是否处于判断最佳掩膜阶段
227 | * @return {[type]} [description]
228 | */
229 | setupTypeNumber: function (test) {
230 |
231 | var bits = QRUtil.getBCHTypeNumber(this.typeNumber);
232 |
233 | for (var i = 0; i < 18; i++) {
234 | var mod = (!test && ((bits >> i) & 1) == 1);
235 | this.modules[Math.floor(i / 3)][i % 3 + this.moduleCount - 8 - 3] = mod;
236 | this.modules[i % 3 + this.moduleCount - 8 - 3][Math.floor(i / 3)] = mod;
237 | }
238 | },
239 | /**
240 | * 设置格式信息(纠错等级和掩膜版本)
241 | * @param {bool} test
242 | * @param {num} maskPattern 掩膜版本
243 | * @return {}
244 | */
245 | setupTypeInfo: function (test, maskPattern) {
246 |
247 | var data = (QRErrorCorrectLevel[this.errorCorrectLevel] << 3) | maskPattern;
248 | var bits = QRUtil.getBCHTypeInfo(data);
249 |
250 | // vertical
251 | for (var i = 0; i < 15; i++) {
252 |
253 | var mod = (!test && ((bits >> i) & 1) == 1);
254 |
255 | if (i < 6) {
256 | this.modules[i][8] = mod;
257 | } else if (i < 8) {
258 | this.modules[i + 1][8] = mod;
259 | } else {
260 | this.modules[this.moduleCount - 15 + i][8] = mod;
261 | }
262 |
263 | // horizontal
264 | var mod = (!test && ((bits >> i) & 1) == 1);
265 |
266 | if (i < 8) {
267 | this.modules[8][this.moduleCount - i - 1] = mod;
268 | } else if (i < 9) {
269 | this.modules[8][15 - i - 1 + 1] = mod;
270 | } else {
271 | this.modules[8][15 - i - 1] = mod;
272 | }
273 | }
274 |
275 | // fixed module
276 | this.modules[this.moduleCount - 8][8] = (!test);
277 |
278 | },
279 | /**
280 | * 数据编码
281 | * @return {[type]} [description]
282 | */
283 | createData: function () {
284 | var buffer = new QRBitBuffer();
285 | var lengthBits = this.typeNumber > 9 ? 16 : 8;
286 | buffer.put(4, 4); //添加模式
287 | buffer.put(this.utf8bytes.length, lengthBits);
288 | for (var i = 0, l = this.utf8bytes.length; i < l; i++) {
289 | buffer.put(this.utf8bytes[i], 8);
290 | }
291 | if (buffer.length + 4 <= this.totalDataCount * 8) {
292 | buffer.put(0, 4);
293 | }
294 |
295 | // padding
296 | while (buffer.length % 8 != 0) {
297 | buffer.putBit(false);
298 | }
299 |
300 | // padding
301 | while (true) {
302 |
303 | if (buffer.length >= this.totalDataCount * 8) {
304 | break;
305 | }
306 | buffer.put(QRCodeAlg.PAD0, 8);
307 |
308 | if (buffer.length >= this.totalDataCount * 8) {
309 | break;
310 | }
311 | buffer.put(QRCodeAlg.PAD1, 8);
312 | }
313 | return this.createBytes(buffer);
314 | },
315 | /**
316 | * 纠错码编码
317 | * @param {buffer} buffer 数据编码
318 | * @return {[type]}
319 | */
320 | createBytes: function (buffer) {
321 |
322 | var offset = 0;
323 |
324 | var maxDcCount = 0;
325 | var maxEcCount = 0;
326 |
327 | var length = this.rsBlock.length / 3;
328 |
329 | var rsBlocks = new Array();
330 |
331 | for (var i = 0; i < length; i++) {
332 |
333 | var count = this.rsBlock[i * 3 + 0];
334 | var totalCount = this.rsBlock[i * 3 + 1];
335 | var dataCount = this.rsBlock[i * 3 + 2];
336 |
337 | for (var j = 0; j < count; j++) {
338 | rsBlocks.push([dataCount, totalCount]);
339 | }
340 | }
341 |
342 | var dcdata = new Array(rsBlocks.length);
343 | var ecdata = new Array(rsBlocks.length);
344 |
345 | for (var r = 0; r < rsBlocks.length; r++) {
346 |
347 | var dcCount = rsBlocks[r][0];
348 | var ecCount = rsBlocks[r][1] - dcCount;
349 |
350 | maxDcCount = Math.max(maxDcCount, dcCount);
351 | maxEcCount = Math.max(maxEcCount, ecCount);
352 |
353 | dcdata[r] = new Array(dcCount);
354 |
355 | for (var i = 0; i < dcdata[r].length; i++) {
356 | dcdata[r][i] = 0xff & buffer.buffer[i + offset];
357 | }
358 | offset += dcCount;
359 |
360 | var rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount);
361 | var rawPoly = new QRPolynomial(dcdata[r], rsPoly.getLength() - 1);
362 |
363 | var modPoly = rawPoly.mod(rsPoly);
364 | ecdata[r] = new Array(rsPoly.getLength() - 1);
365 | for (var i = 0; i < ecdata[r].length; i++) {
366 | var modIndex = i + modPoly.getLength() - ecdata[r].length;
367 | ecdata[r][i] = (modIndex >= 0) ? modPoly.get(modIndex) : 0;
368 | }
369 | }
370 |
371 | var data = new Array(this.totalDataCount);
372 | var index = 0;
373 |
374 | for (var i = 0; i < maxDcCount; i++) {
375 | for (var r = 0; r < rsBlocks.length; r++) {
376 | if (i < dcdata[r].length) {
377 | data[index++] = dcdata[r][i];
378 | }
379 | }
380 | }
381 |
382 | for (var i = 0; i < maxEcCount; i++) {
383 | for (var r = 0; r < rsBlocks.length; r++) {
384 | if (i < ecdata[r].length) {
385 | data[index++] = ecdata[r][i];
386 | }
387 | }
388 | }
389 |
390 | return data;
391 |
392 | },
393 | /**
394 | * 布置模块,构建最终信息
395 | * @param {} data
396 | * @param {} maskPattern
397 | * @return {}
398 | */
399 | mapData: function (data, maskPattern) {
400 |
401 | var inc = -1;
402 | var row = this.moduleCount - 1;
403 | var bitIndex = 7;
404 | var byteIndex = 0;
405 |
406 | for (var col = this.moduleCount - 1; col > 0; col -= 2) {
407 |
408 | if (col == 6) col--;
409 |
410 | while (true) {
411 |
412 | for (var c = 0; c < 2; c++) {
413 |
414 | if (this.modules[row][col - c] == null) {
415 |
416 | var dark = false;
417 |
418 | if (byteIndex < data.length) {
419 | dark = (((data[byteIndex] >>> bitIndex) & 1) == 1);
420 | }
421 |
422 | var mask = QRUtil.getMask(maskPattern, row, col - c);
423 |
424 | if (mask) {
425 | dark = !dark;
426 | }
427 |
428 | this.modules[row][col - c] = dark;
429 | bitIndex--;
430 |
431 | if (bitIndex == -1) {
432 | byteIndex++;
433 | bitIndex = 7;
434 | }
435 | }
436 | }
437 |
438 | row += inc;
439 |
440 | if (row < 0 || this.moduleCount <= row) {
441 | row -= inc;
442 | inc = -inc;
443 | break;
444 | }
445 | }
446 | }
447 | }
448 |
449 | };
450 | /**
451 | * 填充字段
452 | */
453 | QRCodeAlg.PAD0 = 0xEC;
454 | QRCodeAlg.PAD1 = 0x11;
455 |
456 |
457 | //---------------------------------------------------------------------
458 | // 纠错等级对应的编码
459 | //---------------------------------------------------------------------
460 |
461 | var QRErrorCorrectLevel = [1, 0, 3, 2];
462 |
463 | //---------------------------------------------------------------------
464 | // 掩膜版本
465 | //---------------------------------------------------------------------
466 |
467 | var QRMaskPattern = {
468 | PATTERN000: 0,
469 | PATTERN001: 1,
470 | PATTERN010: 2,
471 | PATTERN011: 3,
472 | PATTERN100: 4,
473 | PATTERN101: 5,
474 | PATTERN110: 6,
475 | PATTERN111: 7
476 | };
477 |
478 | //---------------------------------------------------------------------
479 | // 工具类
480 | //---------------------------------------------------------------------
481 |
482 | var QRUtil = {
483 |
484 | /*
485 | 每个版本矫正图形的位置
486 | */
487 | PATTERN_POSITION_TABLE: [
488 | [],
489 | [6, 18],
490 | [6, 22],
491 | [6, 26],
492 | [6, 30],
493 | [6, 34],
494 | [6, 22, 38],
495 | [6, 24, 42],
496 | [6, 26, 46],
497 | [6, 28, 50],
498 | [6, 30, 54],
499 | [6, 32, 58],
500 | [6, 34, 62],
501 | [6, 26, 46, 66],
502 | [6, 26, 48, 70],
503 | [6, 26, 50, 74],
504 | [6, 30, 54, 78],
505 | [6, 30, 56, 82],
506 | [6, 30, 58, 86],
507 | [6, 34, 62, 90],
508 | [6, 28, 50, 72, 94],
509 | [6, 26, 50, 74, 98],
510 | [6, 30, 54, 78, 102],
511 | [6, 28, 54, 80, 106],
512 | [6, 32, 58, 84, 110],
513 | [6, 30, 58, 86, 114],
514 | [6, 34, 62, 90, 118],
515 | [6, 26, 50, 74, 98, 122],
516 | [6, 30, 54, 78, 102, 126],
517 | [6, 26, 52, 78, 104, 130],
518 | [6, 30, 56, 82, 108, 134],
519 | [6, 34, 60, 86, 112, 138],
520 | [6, 30, 58, 86, 114, 142],
521 | [6, 34, 62, 90, 118, 146],
522 | [6, 30, 54, 78, 102, 126, 150],
523 | [6, 24, 50, 76, 102, 128, 154],
524 | [6, 28, 54, 80, 106, 132, 158],
525 | [6, 32, 58, 84, 110, 136, 162],
526 | [6, 26, 54, 82, 110, 138, 166],
527 | [6, 30, 58, 86, 114, 142, 170]
528 | ],
529 |
530 | G15: (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0),
531 | G18: (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0),
532 | G15_MASK: (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1),
533 |
534 | /*
535 | BCH编码格式信息
536 | */
537 | getBCHTypeInfo: function (data) {
538 | var d = data << 10;
539 | while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) >= 0) {
540 | d ^= (QRUtil.G15 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15)));
541 | }
542 | return ((data << 10) | d) ^ QRUtil.G15_MASK;
543 | },
544 | /*
545 | BCH编码版本信息
546 | */
547 | getBCHTypeNumber: function (data) {
548 | var d = data << 12;
549 | while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) >= 0) {
550 | d ^= (QRUtil.G18 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18)));
551 | }
552 | return (data << 12) | d;
553 | },
554 | /*
555 | 获取BCH位信息
556 | */
557 | getBCHDigit: function (data) {
558 |
559 | var digit = 0;
560 |
561 | while (data != 0) {
562 | digit++;
563 | data >>>= 1;
564 | }
565 |
566 | return digit;
567 | },
568 | /*
569 | 获取版本对应的矫正图形位置
570 | */
571 | getPatternPosition: function (typeNumber) {
572 | return QRUtil.PATTERN_POSITION_TABLE[typeNumber - 1];
573 | },
574 | /*
575 | 掩膜算法
576 | */
577 | getMask: function (maskPattern, i, j) {
578 |
579 | switch (maskPattern) {
580 |
581 | case QRMaskPattern.PATTERN000:
582 | return (i + j) % 2 == 0;
583 | case QRMaskPattern.PATTERN001:
584 | return i % 2 == 0;
585 | case QRMaskPattern.PATTERN010:
586 | return j % 3 == 0;
587 | case QRMaskPattern.PATTERN011:
588 | return (i + j) % 3 == 0;
589 | case QRMaskPattern.PATTERN100:
590 | return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 == 0;
591 | case QRMaskPattern.PATTERN101:
592 | return (i * j) % 2 + (i * j) % 3 == 0;
593 | case QRMaskPattern.PATTERN110:
594 | return ((i * j) % 2 + (i * j) % 3) % 2 == 0;
595 | case QRMaskPattern.PATTERN111:
596 | return ((i * j) % 3 + (i + j) % 2) % 2 == 0;
597 |
598 | default:
599 | throw new Error("bad maskPattern:" + maskPattern);
600 | }
601 | },
602 | /*
603 | 获取RS的纠错多项式
604 | */
605 | getErrorCorrectPolynomial: function (errorCorrectLength) {
606 |
607 | var a = new QRPolynomial([1], 0);
608 |
609 | for (var i = 0; i < errorCorrectLength; i++) {
610 | a = a.multiply(new QRPolynomial([1, QRMath.gexp(i)], 0));
611 | }
612 |
613 | return a;
614 | },
615 | /*
616 | 获取评价
617 | */
618 | getLostPoint: function (qrCode) {
619 |
620 | var moduleCount = qrCode.getModuleCount(),
621 | lostPoint = 0,
622 | darkCount = 0;
623 |
624 | for (var row = 0; row < moduleCount; row++) {
625 |
626 | var sameCount = 0;
627 | var head = qrCode.modules[row][0];
628 |
629 | for (var col = 0; col < moduleCount; col++) {
630 |
631 | var current = qrCode.modules[row][col];
632 |
633 | //level 3 评价
634 | if (col < moduleCount - 6) {
635 | if (current && !qrCode.modules[row][col + 1] && qrCode.modules[row][col + 2] && qrCode.modules[row][col + 3] && qrCode.modules[row][col + 4] && !qrCode.modules[row][col + 5] && qrCode.modules[row][col + 6]) {
636 | if (col < moduleCount - 10) {
637 | if (qrCode.modules[row][col + 7] && qrCode.modules[row][col + 8] && qrCode.modules[row][col + 9] && qrCode.modules[row][col + 10]) {
638 | lostPoint += 40;
639 | }
640 | } else if (col > 3) {
641 | if (qrCode.modules[row][col - 1] && qrCode.modules[row][col - 2] && qrCode.modules[row][col - 3] && qrCode.modules[row][col - 4]) {
642 | lostPoint += 40;
643 | }
644 | }
645 |
646 | }
647 | }
648 |
649 | //level 2 评价
650 | if ((row < moduleCount - 1) && (col < moduleCount - 1)) {
651 | var count = 0;
652 | if (current) count++;
653 | if (qrCode.modules[row + 1][col]) count++;
654 | if (qrCode.modules[row][col + 1]) count++;
655 | if (qrCode.modules[row + 1][col + 1]) count++;
656 | if (count == 0 || count == 4) {
657 | lostPoint += 3;
658 | }
659 | }
660 |
661 | //level 1 评价
662 | if (head ^ current) {
663 | sameCount++;
664 | } else {
665 | head = current;
666 | if (sameCount >= 5) {
667 | lostPoint += (3 + sameCount - 5);
668 | }
669 | sameCount = 1;
670 | }
671 |
672 | //level 4 评价
673 | if (current) {
674 | darkCount++;
675 | }
676 |
677 | }
678 | }
679 |
680 | for (var col = 0; col < moduleCount; col++) {
681 |
682 | var sameCount = 0;
683 | var head = qrCode.modules[0][col];
684 |
685 | for (var row = 0; row < moduleCount; row++) {
686 |
687 | var current = qrCode.modules[row][col];
688 |
689 | //level 3 评价
690 | if (row < moduleCount - 6) {
691 | if (current && !qrCode.modules[row + 1][col] && qrCode.modules[row + 2][col] && qrCode.modules[row + 3][col] && qrCode.modules[row + 4][col] && !qrCode.modules[row + 5][col] && qrCode.modules[row + 6][col]) {
692 | if (row < moduleCount - 10) {
693 | if (qrCode.modules[row + 7][col] && qrCode.modules[row + 8][col] && qrCode.modules[row + 9][col] && qrCode.modules[row + 10][col]) {
694 | lostPoint += 40;
695 | }
696 | } else if (row > 3) {
697 | if (qrCode.modules[row - 1][col] && qrCode.modules[row - 2][col] && qrCode.modules[row - 3][col] && qrCode.modules[row - 4][col]) {
698 | lostPoint += 40;
699 | }
700 | }
701 | }
702 | }
703 |
704 | //level 1 评价
705 | if (head ^ current) {
706 | sameCount++;
707 | } else {
708 | head = current;
709 | if (sameCount >= 5) {
710 | lostPoint += (3 + sameCount - 5);
711 | }
712 | sameCount = 1;
713 | }
714 |
715 | }
716 | }
717 |
718 | // LEVEL4
719 |
720 | var ratio = Math.abs(100 * darkCount / moduleCount / moduleCount - 50) / 5;
721 | lostPoint += ratio * 10;
722 |
723 | return lostPoint;
724 | }
725 |
726 | };
727 |
728 |
729 | //---------------------------------------------------------------------
730 | // QRMath使用的数学工具
731 | //---------------------------------------------------------------------
732 |
733 | var QRMath = {
734 | /*
735 | 将n转化为a^m
736 | */
737 | glog: function (n) {
738 |
739 | if (n < 1) {
740 | throw new Error("glog(" + n + ")");
741 | }
742 |
743 | return QRMath.LOG_TABLE[n];
744 | },
745 | /*
746 | 将a^m转化为n
747 | */
748 | gexp: function (n) {
749 |
750 | while (n < 0) {
751 | n += 255;
752 | }
753 |
754 | while (n >= 256) {
755 | n -= 255;
756 | }
757 |
758 | return QRMath.EXP_TABLE[n];
759 | },
760 |
761 | EXP_TABLE: new Array(256),
762 |
763 | LOG_TABLE: new Array(256)
764 |
765 | };
766 |
767 | for (var i = 0; i < 8; i++) {
768 | QRMath.EXP_TABLE[i] = 1 << i;
769 | }
770 | for (var i = 8; i < 256; i++) {
771 | QRMath.EXP_TABLE[i] = QRMath.EXP_TABLE[i - 4] ^ QRMath.EXP_TABLE[i - 5] ^ QRMath.EXP_TABLE[i - 6] ^ QRMath.EXP_TABLE[i - 8];
772 | }
773 | for (var i = 0; i < 255; i++) {
774 | QRMath.LOG_TABLE[QRMath.EXP_TABLE[i]] = i;
775 | }
776 |
777 | //---------------------------------------------------------------------
778 | // QRPolynomial 多项式
779 | //---------------------------------------------------------------------
780 | /**
781 | * 多项式类
782 | * @param {Array} num 系数
783 | * @param {num} shift a^shift
784 | */
785 | function QRPolynomial(num, shift) {
786 |
787 | if (num.length == undefined) {
788 | throw new Error(num.length + "/" + shift);
789 | }
790 |
791 | var offset = 0;
792 |
793 | while (offset < num.length && num[offset] == 0) {
794 | offset++;
795 | }
796 |
797 | this.num = new Array(num.length - offset + shift);
798 | for (var i = 0; i < num.length - offset; i++) {
799 | this.num[i] = num[i + offset];
800 | }
801 | }
802 |
803 | QRPolynomial.prototype = {
804 |
805 | get: function (index) {
806 | return this.num[index];
807 | },
808 |
809 | getLength: function () {
810 | return this.num.length;
811 | },
812 | /**
813 | * 多项式乘法
814 | * @param {QRPolynomial} e 被乘多项式
815 | * @return {[type]} [description]
816 | */
817 | multiply: function (e) {
818 |
819 | var num = new Array(this.getLength() + e.getLength() - 1);
820 |
821 | for (var i = 0; i < this.getLength(); i++) {
822 | for (var j = 0; j < e.getLength(); j++) {
823 | num[i + j] ^= QRMath.gexp(QRMath.glog(this.get(i)) + QRMath.glog(e.get(j)));
824 | }
825 | }
826 |
827 | return new QRPolynomial(num, 0);
828 | },
829 | /**
830 | * 多项式模运算
831 | * @param {QRPolynomial} e 模多项式
832 | * @return {}
833 | */
834 | mod: function (e) {
835 | var tl = this.getLength(),
836 | el = e.getLength();
837 | if (tl - el < 0) {
838 | return this;
839 | }
840 | var num = new Array(tl);
841 | for (var i = 0; i < tl; i++) {
842 | num[i] = this.get(i);
843 | }
844 | while (num.length >= el) {
845 | var ratio = QRMath.glog(num[0]) - QRMath.glog(e.get(0));
846 |
847 | for (var i = 0; i < e.getLength(); i++) {
848 | num[i] ^= QRMath.gexp(QRMath.glog(e.get(i)) + ratio);
849 | }
850 | while (num[0] == 0) {
851 | num.shift();
852 | }
853 | }
854 | return new QRPolynomial(num, 0);
855 | }
856 | };
857 |
858 | //---------------------------------------------------------------------
859 | // RS_BLOCK_TABLE
860 | //---------------------------------------------------------------------
861 | /*
862 | 二维码各个版本信息[块数, 每块中的数据块数, 每块中的信息块数]
863 | */
864 | var RS_BLOCK_TABLE = [
865 |
866 | // L
867 | // M
868 | // Q
869 | // H
870 |
871 | // 1
872 | [1, 26, 19],
873 | [1, 26, 16],
874 | [1, 26, 13],
875 | [1, 26, 9],
876 |
877 | // 2
878 | [1, 44, 34],
879 | [1, 44, 28],
880 | [1, 44, 22],
881 | [1, 44, 16],
882 |
883 | // 3
884 | [1, 70, 55],
885 | [1, 70, 44],
886 | [2, 35, 17],
887 | [2, 35, 13],
888 |
889 | // 4
890 | [1, 100, 80],
891 | [2, 50, 32],
892 | [2, 50, 24],
893 | [4, 25, 9],
894 |
895 | // 5
896 | [1, 134, 108],
897 | [2, 67, 43],
898 | [2, 33, 15, 2, 34, 16],
899 | [2, 33, 11, 2, 34, 12],
900 |
901 | // 6
902 | [2, 86, 68],
903 | [4, 43, 27],
904 | [4, 43, 19],
905 | [4, 43, 15],
906 |
907 | // 7
908 | [2, 98, 78],
909 | [4, 49, 31],
910 | [2, 32, 14, 4, 33, 15],
911 | [4, 39, 13, 1, 40, 14],
912 |
913 | // 8
914 | [2, 121, 97],
915 | [2, 60, 38, 2, 61, 39],
916 | [4, 40, 18, 2, 41, 19],
917 | [4, 40, 14, 2, 41, 15],
918 |
919 | // 9
920 | [2, 146, 116],
921 | [3, 58, 36, 2, 59, 37],
922 | [4, 36, 16, 4, 37, 17],
923 | [4, 36, 12, 4, 37, 13],
924 |
925 | // 10
926 | [2, 86, 68, 2, 87, 69],
927 | [4, 69, 43, 1, 70, 44],
928 | [6, 43, 19, 2, 44, 20],
929 | [6, 43, 15, 2, 44, 16],
930 |
931 | // 11
932 | [4, 101, 81],
933 | [1, 80, 50, 4, 81, 51],
934 | [4, 50, 22, 4, 51, 23],
935 | [3, 36, 12, 8, 37, 13],
936 |
937 | // 12
938 | [2, 116, 92, 2, 117, 93],
939 | [6, 58, 36, 2, 59, 37],
940 | [4, 46, 20, 6, 47, 21],
941 | [7, 42, 14, 4, 43, 15],
942 |
943 | // 13
944 | [4, 133, 107],
945 | [8, 59, 37, 1, 60, 38],
946 | [8, 44, 20, 4, 45, 21],
947 | [12, 33, 11, 4, 34, 12],
948 |
949 | // 14
950 | [3, 145, 115, 1, 146, 116],
951 | [4, 64, 40, 5, 65, 41],
952 | [11, 36, 16, 5, 37, 17],
953 | [11, 36, 12, 5, 37, 13],
954 |
955 | // 15
956 | [5, 109, 87, 1, 110, 88],
957 | [5, 65, 41, 5, 66, 42],
958 | [5, 54, 24, 7, 55, 25],
959 | [11, 36, 12],
960 |
961 | // 16
962 | [5, 122, 98, 1, 123, 99],
963 | [7, 73, 45, 3, 74, 46],
964 | [15, 43, 19, 2, 44, 20],
965 | [3, 45, 15, 13, 46, 16],
966 |
967 | // 17
968 | [1, 135, 107, 5, 136, 108],
969 | [10, 74, 46, 1, 75, 47],
970 | [1, 50, 22, 15, 51, 23],
971 | [2, 42, 14, 17, 43, 15],
972 |
973 | // 18
974 | [5, 150, 120, 1, 151, 121],
975 | [9, 69, 43, 4, 70, 44],
976 | [17, 50, 22, 1, 51, 23],
977 | [2, 42, 14, 19, 43, 15],
978 |
979 | // 19
980 | [3, 141, 113, 4, 142, 114],
981 | [3, 70, 44, 11, 71, 45],
982 | [17, 47, 21, 4, 48, 22],
983 | [9, 39, 13, 16, 40, 14],
984 |
985 | // 20
986 | [3, 135, 107, 5, 136, 108],
987 | [3, 67, 41, 13, 68, 42],
988 | [15, 54, 24, 5, 55, 25],
989 | [15, 43, 15, 10, 44, 16],
990 |
991 | // 21
992 | [4, 144, 116, 4, 145, 117],
993 | [17, 68, 42],
994 | [17, 50, 22, 6, 51, 23],
995 | [19, 46, 16, 6, 47, 17],
996 |
997 | // 22
998 | [2, 139, 111, 7, 140, 112],
999 | [17, 74, 46],
1000 | [7, 54, 24, 16, 55, 25],
1001 | [34, 37, 13],
1002 |
1003 | // 23
1004 | [4, 151, 121, 5, 152, 122],
1005 | [4, 75, 47, 14, 76, 48],
1006 | [11, 54, 24, 14, 55, 25],
1007 | [16, 45, 15, 14, 46, 16],
1008 |
1009 | // 24
1010 | [6, 147, 117, 4, 148, 118],
1011 | [6, 73, 45, 14, 74, 46],
1012 | [11, 54, 24, 16, 55, 25],
1013 | [30, 46, 16, 2, 47, 17],
1014 |
1015 | // 25
1016 | [8, 132, 106, 4, 133, 107],
1017 | [8, 75, 47, 13, 76, 48],
1018 | [7, 54, 24, 22, 55, 25],
1019 | [22, 45, 15, 13, 46, 16],
1020 |
1021 | // 26
1022 | [10, 142, 114, 2, 143, 115],
1023 | [19, 74, 46, 4, 75, 47],
1024 | [28, 50, 22, 6, 51, 23],
1025 | [33, 46, 16, 4, 47, 17],
1026 |
1027 | // 27
1028 | [8, 152, 122, 4, 153, 123],
1029 | [22, 73, 45, 3, 74, 46],
1030 | [8, 53, 23, 26, 54, 24],
1031 | [12, 45, 15, 28, 46, 16],
1032 |
1033 | // 28
1034 | [3, 147, 117, 10, 148, 118],
1035 | [3, 73, 45, 23, 74, 46],
1036 | [4, 54, 24, 31, 55, 25],
1037 | [11, 45, 15, 31, 46, 16],
1038 |
1039 | // 29
1040 | [7, 146, 116, 7, 147, 117],
1041 | [21, 73, 45, 7, 74, 46],
1042 | [1, 53, 23, 37, 54, 24],
1043 | [19, 45, 15, 26, 46, 16],
1044 |
1045 | // 30
1046 | [5, 145, 115, 10, 146, 116],
1047 | [19, 75, 47, 10, 76, 48],
1048 | [15, 54, 24, 25, 55, 25],
1049 | [23, 45, 15, 25, 46, 16],
1050 |
1051 | // 31
1052 | [13, 145, 115, 3, 146, 116],
1053 | [2, 74, 46, 29, 75, 47],
1054 | [42, 54, 24, 1, 55, 25],
1055 | [23, 45, 15, 28, 46, 16],
1056 |
1057 | // 32
1058 | [17, 145, 115],
1059 | [10, 74, 46, 23, 75, 47],
1060 | [10, 54, 24, 35, 55, 25],
1061 | [19, 45, 15, 35, 46, 16],
1062 |
1063 | // 33
1064 | [17, 145, 115, 1, 146, 116],
1065 | [14, 74, 46, 21, 75, 47],
1066 | [29, 54, 24, 19, 55, 25],
1067 | [11, 45, 15, 46, 46, 16],
1068 |
1069 | // 34
1070 | [13, 145, 115, 6, 146, 116],
1071 | [14, 74, 46, 23, 75, 47],
1072 | [44, 54, 24, 7, 55, 25],
1073 | [59, 46, 16, 1, 47, 17],
1074 |
1075 | // 35
1076 | [12, 151, 121, 7, 152, 122],
1077 | [12, 75, 47, 26, 76, 48],
1078 | [39, 54, 24, 14, 55, 25],
1079 | [22, 45, 15, 41, 46, 16],
1080 |
1081 | // 36
1082 | [6, 151, 121, 14, 152, 122],
1083 | [6, 75, 47, 34, 76, 48],
1084 | [46, 54, 24, 10, 55, 25],
1085 | [2, 45, 15, 64, 46, 16],
1086 |
1087 | // 37
1088 | [17, 152, 122, 4, 153, 123],
1089 | [29, 74, 46, 14, 75, 47],
1090 | [49, 54, 24, 10, 55, 25],
1091 | [24, 45, 15, 46, 46, 16],
1092 |
1093 | // 38
1094 | [4, 152, 122, 18, 153, 123],
1095 | [13, 74, 46, 32, 75, 47],
1096 | [48, 54, 24, 14, 55, 25],
1097 | [42, 45, 15, 32, 46, 16],
1098 |
1099 | // 39
1100 | [20, 147, 117, 4, 148, 118],
1101 | [40, 75, 47, 7, 76, 48],
1102 | [43, 54, 24, 22, 55, 25],
1103 | [10, 45, 15, 67, 46, 16],
1104 |
1105 | // 40
1106 | [19, 148, 118, 6, 149, 119],
1107 | [18, 75, 47, 31, 76, 48],
1108 | [34, 54, 24, 34, 55, 25],
1109 | [20, 45, 15, 61, 46, 16]
1110 | ];
1111 |
1112 | /**
1113 | * 根据数据获取对应版本
1114 | * @return {[type]} [description]
1115 | */
1116 | QRCodeAlg.prototype.getRightType = function () {
1117 | for (var typeNumber = 1; typeNumber < 41; typeNumber++) {
1118 | var rsBlock = RS_BLOCK_TABLE[(typeNumber - 1) * 4 + this.errorCorrectLevel];
1119 | if (rsBlock == undefined) {
1120 | throw new Error("bad rs block @ typeNumber:" + typeNumber + "/errorCorrectLevel:" + this.errorCorrectLevel);
1121 | }
1122 | var length = rsBlock.length / 3;
1123 | var totalDataCount = 0;
1124 | for (var i = 0; i < length; i++) {
1125 | var count = rsBlock[i * 3 + 0];
1126 | var dataCount = rsBlock[i * 3 + 2];
1127 | totalDataCount += dataCount * count;
1128 | }
1129 |
1130 | var lengthBytes = typeNumber > 9 ? 2 : 1;
1131 | if (this.utf8bytes.length + lengthBytes < totalDataCount || typeNumber == 40) {
1132 | this.typeNumber = typeNumber;
1133 | this.rsBlock = rsBlock;
1134 | this.totalDataCount = totalDataCount;
1135 | break;
1136 | }
1137 | }
1138 | };
1139 |
1140 | //---------------------------------------------------------------------
1141 | // QRBitBuffer
1142 | //---------------------------------------------------------------------
1143 |
1144 | function QRBitBuffer() {
1145 | this.buffer = new Array();
1146 | this.length = 0;
1147 | }
1148 |
1149 | QRBitBuffer.prototype = {
1150 |
1151 | get: function (index) {
1152 | var bufIndex = Math.floor(index / 8);
1153 | return ((this.buffer[bufIndex] >>> (7 - index % 8)) & 1);
1154 | },
1155 |
1156 | put: function (num, length) {
1157 | for (var i = 0; i < length; i++) {
1158 | this.putBit(((num >>> (length - i - 1)) & 1));
1159 | }
1160 | },
1161 |
1162 | putBit: function (bit) {
1163 |
1164 | var bufIndex = Math.floor(this.length / 8);
1165 | if (this.buffer.length <= bufIndex) {
1166 | this.buffer.push(0);
1167 | }
1168 |
1169 | if (bit) {
1170 | this.buffer[bufIndex] |= (0x80 >>> (this.length % 8));
1171 | }
1172 |
1173 | this.length++;
1174 | }
1175 | };
1176 |
1177 |
1178 | /**
1179 | * 计算矩阵点的前景色
1180 | * @param {Obj} config
1181 | * @param {Number} config.row 点x坐标
1182 | * @param {Number} config.col 点y坐标
1183 | * @param {Number} config.count 矩阵大小
1184 | * @param {Number} config.options 组件的options
1185 | * @return {String}
1186 | */
1187 | var getForeGround = function (config) {
1188 | var options = config.options;
1189 | if (options.pdground && (
1190 | (config.row > 1 && config.row < 5 && config.col > 1 && config.col < 5)
1191 | || (config.row > (config.count - 6) && config.row < (config.count - 2) && config.col > 1 && config.col < 5)
1192 | || (config.row > 1 && config.row < 5 && config.col > (config.count - 6) && config.col < (config.count - 2))
1193 | )) {
1194 | return options.pdground;
1195 | }
1196 | return options.foreground;
1197 | }
1198 | /**
1199 | * 点是否在Position Detection
1200 | * @param {row} 矩阵行
1201 | * @param {col} 矩阵列
1202 | * @param {count} 矩阵大小
1203 | * @return {Boolean}
1204 | */
1205 | var inPositionDetection = function (row, col, count) {
1206 | if (
1207 | (row < 7 && col < 7)
1208 | || (row > (count - 8) && col < 7)
1209 | || (row < 7 && col > (count - 8) )
1210 | ) {
1211 | return true;
1212 | }
1213 | return false;
1214 | }
1215 | /**
1216 | * 获取当前屏幕的设备像素比 devicePixelRatio/backingStore
1217 | * @param {context} 当前 canvas 上下文,可以为 window
1218 | */
1219 | var getPixelRatio = function (context) {
1220 | var backingStore = context.backingStorePixelRatio
1221 | || context.webkitBackingStorePixelRatio
1222 | || context.mozBackingStorePixelRatio
1223 | || context.msBackingStorePixelRatio
1224 | || context.oBackingStorePixelRatio
1225 | || context.backingStorePixelRatio
1226 | || 1;
1227 |
1228 | return (window.devicePixelRatio || 1) / backingStore;
1229 | };
1230 |
1231 | var qrcodeAlgObjCache = [];
1232 |
1233 | /**
1234 | * 二维码构造函数,主要用于绘制
1235 | * @param {参数列表} opt 传递参数
1236 | * @return {}
1237 | */
1238 | var qrcode = function (opt) {
1239 | if (typeof opt === 'string') { // 只编码ASCII字符串
1240 | opt = {
1241 | text: opt
1242 | };
1243 | }
1244 | //设置默认参数
1245 | this.options = extend({}, {
1246 | text: '',
1247 | render: '',
1248 | size: 256,
1249 | correctLevel: 3,
1250 | background: '#ffffff',
1251 | foreground: '#000000',
1252 | image: '',
1253 | imageSize: 30
1254 | }, opt);
1255 |
1256 | //使用QRCodeAlg创建二维码结构
1257 | var qrCodeAlg = null;
1258 | for (var i = 0, l = qrcodeAlgObjCache.length; i < l; i++) {
1259 | if (qrcodeAlgObjCache[i].text == this.options.text && qrcodeAlgObjCache[i].text.correctLevel == this.options.correctLevel) {
1260 | qrCodeAlg = qrcodeAlgObjCache[i].obj;
1261 | break;
1262 | }
1263 | }
1264 |
1265 | if (i == l) {
1266 | qrCodeAlg = new QRCodeAlg(this.options.text, this.options.correctLevel);
1267 | qrcodeAlgObjCache.push({ text: this.options.text, correctLevel: this.options.correctLevel, obj: qrCodeAlg });
1268 | }
1269 |
1270 | if (this.options.render) {
1271 | switch (this.options.render) {
1272 | case 'canvas':
1273 | return this.createCanvas(qrCodeAlg);
1274 | case 'table':
1275 | return this.createTable(qrCodeAlg);
1276 | case 'svg':
1277 | return this.createSVG(qrCodeAlg);
1278 | default:
1279 | return this.createDefault(qrCodeAlg);
1280 | }
1281 | }
1282 | return this.createDefault(qrCodeAlg);
1283 | };
1284 |
1285 | extend(qrcode.prototype, {
1286 | // default create canvas -> svg -> table
1287 | createDefault (qrCodeAlg) {
1288 | var canvas = document.createElement('canvas');
1289 | if (canvas.getContext) {
1290 | return this.createCanvas(qrCodeAlg);
1291 | }
1292 | var SVG_NS = 'http://www.w3.org/2000/svg';
1293 | if (!!document.createElementNS && !!document.createElementNS(SVG_NS, 'svg').createSVGRect) {
1294 | return this.createSVG(qrCodeAlg);
1295 | }
1296 | return this.createTable(qrCodeAlg);
1297 | },
1298 | // canvas create
1299 | createCanvas (qrCodeAlg) {
1300 | var options = this.options;
1301 | var canvas = document.createElement('canvas');
1302 | var ctx = canvas.getContext('2d');
1303 | var count = qrCodeAlg.getModuleCount();
1304 | var ratio = getPixelRatio(ctx);
1305 | var size = options.size;
1306 | var ratioSize = size * ratio;
1307 | var ratioImgSize = options.imageSize * ratio;
1308 | // preload img
1309 | var loadImage = function (url, callback) {
1310 | var img = new Image();
1311 | img.src = url;
1312 | img.onload = function () {
1313 | callback(this);
1314 | img.onload = null
1315 | };
1316 | }
1317 |
1318 | //计算每个点的长宽
1319 | var tileW = (ratioSize / count).toPrecision(4);
1320 | var tileH = (ratioSize / count).toPrecision(4);
1321 |
1322 | canvas.width = ratioSize;
1323 | canvas.height = ratioSize;
1324 |
1325 | //绘制
1326 | for (var row = 0; row < count; row++) {
1327 | for (var col = 0; col < count; col++) {
1328 | var w = (Math.ceil((col + 1) * tileW) - Math.floor(col * tileW));
1329 | var h = (Math.ceil((row + 1) * tileW) - Math.floor(row * tileW));
1330 | var foreground = getForeGround({
1331 | row: row,
1332 | col: col,
1333 | count: count,
1334 | options: options
1335 | });
1336 | ctx.fillStyle = qrCodeAlg.modules[row][col] ? foreground : options.background;
1337 | ctx.fillRect(Math.round(col * tileW), Math.round(row * tileH), w, h);
1338 | }
1339 | }
1340 | if (options.image) {
1341 | loadImage(options.image, function (img) {
1342 | var x = ((ratioSize - ratioImgSize) / 2).toFixed(2);
1343 | var y = ((ratioSize - ratioImgSize) / 2).toFixed(2);
1344 | ctx.drawImage(img, x, y, ratioImgSize, ratioImgSize);
1345 | });
1346 | }
1347 | canvas.style.width = size + 'px';
1348 | canvas.style.height = size + 'px';
1349 | return canvas;
1350 | },
1351 | // table create
1352 | createTable (qrCodeAlg) {
1353 | var options = this.options;
1354 | var count = qrCodeAlg.getModuleCount();
1355 |
1356 | // 计算每个节点的长宽;取整,防止点之间出现分离
1357 | var tileW = Math.floor(options.size / count);
1358 | var tileH = Math.floor(options.size / count);
1359 | if (tileW <= 0) {
1360 | tileW = count < 80 ? 2 : 1;
1361 | }
1362 | if (tileH <= 0) {
1363 | tileH = count < 80 ? 2 : 1;
1364 | }
1365 |
1366 | //创建table节点
1367 | //重算码大小
1368 | var s = [];
1369 | s.push(``);
1370 |
1371 | // 绘制二维码
1372 | for (var row = 0; row < count; row++) {
1373 | s.push(``);
1374 | for (var col = 0; col < count; col++) {
1375 | var foreground = getForeGround({
1376 | row: row,
1377 | col: col,
1378 | count: count,
1379 | options: options
1380 | });
1381 | if (qrCodeAlg.modules[row][col]) {
1382 | s.push(` | `);
1383 | } else {
1384 | s.push(` | `);
1385 | }
1386 | }
1387 | s.push('
');
1388 | }
1389 | s.push('
');
1390 |
1391 | if (options.image) {
1392 | // 计算表格的总大小
1393 | var width = tileW * count;
1394 | var height = tileH * count;
1395 | var x = ((width - options.imageSize) / 2).toFixed(2);
1396 | var y = ((height - options.imageSize) / 2).toFixed(2);
1397 | s.unshift(``);
1400 | s.push(`

`);
1404 | s.push('
');
1405 | }
1406 |
1407 | var span = document.createElement('span');
1408 | span.innerHTML = s.join('');
1409 |
1410 | return span.firstChild;
1411 | },
1412 | // create svg
1413 | createSVG (qrCodeAlg){
1414 | let options = this.options;
1415 | let count = qrCodeAlg.getModuleCount();
1416 | let scale = count / options.size;
1417 |
1418 | // create svg
1419 | let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
1420 | svg.setAttribute('width', options.size);
1421 | svg.setAttribute('height', options.size);
1422 | svg.setAttribute('viewBox', `0 0 ${count} ${count}`);
1423 |
1424 | for (let row = 0; row < count; row++) {
1425 | for (let col = 0; col < count; col++) {
1426 | let rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
1427 | let foreground = getForeGround({
1428 | row: row,
1429 | col: col,
1430 | count: count,
1431 | options: options
1432 | });
1433 | rect.setAttribute('x', col);
1434 | rect.setAttribute('y', row);
1435 | rect.setAttribute('width', 1);
1436 | rect.setAttribute('height', 1);
1437 | rect.setAttribute('stroke-width', 0);
1438 | if (qrCodeAlg.modules[row][col]) {
1439 | rect.setAttribute('fill', foreground);
1440 | } else {
1441 | rect.setAttribute('fill', options.background);
1442 | }
1443 | svg.appendChild(rect);
1444 | }
1445 | }
1446 |
1447 | // create image
1448 | if (options.image) {
1449 | let img = document.createElementNS('http://www.w3.org/2000/svg', 'image');
1450 | img.setAttributeNS('http://www.w3.org/1999/xlink', 'href', options.image);
1451 | img.setAttribute('x', ((count - options.imageSize * scale) / 2).toFixed(2));
1452 | img.setAttribute('y', ((count - options.imageSize * scale) / 2).toFixed(2));
1453 | img.setAttribute('width', options.imageSize * scale);
1454 | img.setAttribute('height', options.imageSize * scale);
1455 | svg.appendChild(img);
1456 | }
1457 |
1458 | return svg;
1459 | }
1460 | });
1461 |
1462 | window.QRCode = qrcode;
1463 | })();
1464 |
--------------------------------------------------------------------------------
/public/qrcode.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/scripts/checkDep.js:
--------------------------------------------------------------------------------
1 | require('../lib/checkDep')(function(errors){
2 | console.log(errors);
3 | },'lib');
4 |
--------------------------------------------------------------------------------
/scripts/debugJestPreprocessor.js:
--------------------------------------------------------------------------------
1 | const preProcessor = require('./jestPreprocessor');
2 |
3 | module.exports = {
4 | ...preProcessor,
5 | process(...args) {
6 | const filePath = args[1];
7 | console.log('process:', filePath);
8 | return preProcessor.process(...args);
9 | },
10 | };
11 |
--------------------------------------------------------------------------------
/scripts/jestPreprocessor.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 | const chalk = require('chalk');
3 | const { createTransformer: babelTransFormer } = require('babel-jest');
4 | const { createTransformer: tsTransFormer } = require('ts-jest');
5 | const getBabelCommonConfig = require('../lib/getBabelCommonConfig');
6 |
7 | const tsJest = tsTransFormer({
8 | tsConfig: path.join(__dirname, '../lib/tests/tsconfig.test.json'),
9 | });
10 | const babelJest = babelTransFormer(getBabelCommonConfig());
11 |
12 | module.exports = {
13 | process(src, filePath) {
14 | const isTypeScript = filePath.endsWith('.ts') || filePath.endsWith('.tsx');
15 | const isJavaScript = filePath.endsWith('.js') || filePath.endsWith('.jsx');
16 |
17 | if (isTypeScript) {
18 | src = tsJest.process(src, filePath, { moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx'] });
19 | } else if (isJavaScript) {
20 | src = babelJest.process(src, filePath, { moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx'] });
21 | } else {
22 | console.log(
23 | chalk.red('File not match type:'),
24 | filePath
25 | );
26 | throw new Error(`File not match type: ${filePath}`);
27 | }
28 |
29 | return src;
30 | },
31 | };
32 |
--------------------------------------------------------------------------------
/scripts/update.sh:
--------------------------------------------------------------------------------
1 | tnpm i karma --save
2 |
3 | tnpm i karma-cli --save
4 |
5 | tnpm i karma-chrome-launcher
--save
6 |
7 | tnpm i karma-coverage --save
8 |
9 | tnpm i karma-coveralls --save
10 |
11 | tnpm i karma-firefox-launcher --save
12 |
13 | tnpm i karma-ie-launcher --save
14 |
15 | tnpm i karma-mocha --save
16 |
17 | tnpm i karma-mocha-reporter --save
18 |
19 | tnpm i karma-phantomjs-launcher --save
20 |
21 | tnpm i karma-safari-launcher --save
22 |
23 | tnpm i karma-sauce-launcher --save
24 |
25 | tnpm i karma-sourcemap-loader --save
26 |
27 | tnpm i karma-webpack --save
--------------------------------------------------------------------------------
/views/js2html.xtpl:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | {{pkg.name}}-{{name}}
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 | {{#if(hasCss)}}
19 | {{/if}}
20 |
25 |
157 |
158 |
159 |
160 |
163 |
178 |
179 |
180 | {{{content}}}
181 |
182 |
183 |
184 |
237 |
238 |
239 |
--------------------------------------------------------------------------------