MinsoftK

4

Showing 1000 changed files with 0 additions and 4769 deletions

Too many changes to show.

To preserve performance only 1000 of 1000+ files are displayed.

Copyright 2017 Smooth Code
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# @svgr/babel-preset
## Install
```
npm install --save-dev @svgr/babel-preset
```
## Usage
**.babelrc**
```json
{
"presets": [["@svgr/babel-preset", { "svgProps": { "width": 200 } }]]
}
```
## License
MIT
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _babelPluginAddJsxAttribute = _interopRequireDefault(require("@svgr/babel-plugin-add-jsx-attribute"));
var _babelPluginRemoveJsxAttribute = _interopRequireDefault(require("@svgr/babel-plugin-remove-jsx-attribute"));
var _babelPluginRemoveJsxEmptyExpression = _interopRequireDefault(require("@svgr/babel-plugin-remove-jsx-empty-expression"));
var _babelPluginReplaceJsxAttributeValue = _interopRequireDefault(require("@svgr/babel-plugin-replace-jsx-attribute-value"));
var _babelPluginSvgDynamicTitle = _interopRequireDefault(require("@svgr/babel-plugin-svg-dynamic-title"));
var _babelPluginSvgEmDimensions = _interopRequireDefault(require("@svgr/babel-plugin-svg-em-dimensions"));
var _babelPluginTransformReactNativeSvg = _interopRequireDefault(require("@svgr/babel-plugin-transform-react-native-svg"));
var _babelPluginTransformSvgComponent = _interopRequireDefault(require("@svgr/babel-plugin-transform-svg-component"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function getAttributeValue(value) {
const literal = typeof value === 'string' && value.startsWith('{') && value.endsWith('}');
return {
value: literal ? value.slice(1, -1) : value,
literal
};
}
function propsToAttributes(props) {
return Object.keys(props).map(name => {
const {
literal,
value
} = getAttributeValue(props[name]);
return {
name,
literal,
value
};
});
}
function replaceMapToValues(replaceMap) {
return Object.keys(replaceMap).map(value => {
const {
literal,
value: newValue
} = getAttributeValue(replaceMap[value]);
return {
value,
newValue,
literal
};
});
}
const plugin = (api, opts) => {
let toRemoveAttributes = ['version'];
let toAddAttributes = [];
if (opts.svgProps) {
toAddAttributes = [...toAddAttributes, ...propsToAttributes(opts.svgProps)];
}
if (opts.ref) {
toAddAttributes = [...toAddAttributes, {
name: 'ref',
value: 'svgRef',
literal: true
}];
}
if (opts.titleProp) {
toAddAttributes = [...toAddAttributes, {
name: 'aria-labelledby',
value: 'titleId',
literal: true
}];
}
if (opts.expandProps) {
toAddAttributes = [...toAddAttributes, {
name: 'props',
spread: true,
position: opts.expandProps
}];
}
if (!opts.dimensions) {
toRemoveAttributes = [...toRemoveAttributes, 'width', 'height'];
}
const plugins = [[_babelPluginTransformSvgComponent.default, opts], ...(opts.icon && opts.dimensions ? [_babelPluginSvgEmDimensions.default] : []), [_babelPluginRemoveJsxAttribute.default, {
elements: ['svg', 'Svg'],
attributes: toRemoveAttributes
}], [_babelPluginAddJsxAttribute.default, {
elements: ['svg', 'Svg'],
attributes: toAddAttributes
}], _babelPluginRemoveJsxEmptyExpression.default];
if (opts.replaceAttrValues) {
plugins.push([_babelPluginReplaceJsxAttributeValue.default, {
values: replaceMapToValues(opts.replaceAttrValues)
}]);
}
if (opts.titleProp) {
plugins.push(_babelPluginSvgDynamicTitle.default);
}
if (opts.native) {
if (opts.native.expo) {
plugins.push([_babelPluginTransformReactNativeSvg.default, opts.native]);
} else {
plugins.push(_babelPluginTransformReactNativeSvg.default);
}
}
return {
plugins
};
};
var _default = plugin;
exports.default = _default;
\ No newline at end of file
{
"_from": "@svgr/babel-preset@^5.5.0",
"_id": "@svgr/babel-preset@5.5.0",
"_inBundle": false,
"_integrity": "sha512-4FiXBjvQ+z2j7yASeGPEi8VD/5rrGQk4Xrq3EdJmoZgz/tpqChpo5hgXDvmEauwtvOc52q8ghhZK4Oy7qph4ig==",
"_location": "/@svgr/babel-preset",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@svgr/babel-preset@^5.5.0",
"name": "@svgr/babel-preset",
"escapedName": "@svgr%2fbabel-preset",
"scope": "@svgr",
"rawSpec": "^5.5.0",
"saveSpec": null,
"fetchSpec": "^5.5.0"
},
"_requiredBy": [
"/@svgr/plugin-jsx"
],
"_resolved": "https://registry.npmjs.org/@svgr/babel-preset/-/babel-preset-5.5.0.tgz",
"_shasum": "8af54f3e0a8add7b1e2b0fcd5a882c55393df327",
"_spec": "@svgr/babel-preset@^5.5.0",
"_where": "C:\\Users\\kkwan_000\\Desktop\\git\\2017110269\\minsung\\node_modules\\@svgr\\plugin-jsx",
"author": {
"name": "Greg Bergé",
"email": "berge.greg@gmail.com"
},
"bundleDependencies": false,
"dependencies": {
"@svgr/babel-plugin-add-jsx-attribute": "^5.4.0",
"@svgr/babel-plugin-remove-jsx-attribute": "^5.4.0",
"@svgr/babel-plugin-remove-jsx-empty-expression": "^5.0.1",
"@svgr/babel-plugin-replace-jsx-attribute-value": "^5.0.1",
"@svgr/babel-plugin-svg-dynamic-title": "^5.4.0",
"@svgr/babel-plugin-svg-em-dimensions": "^5.4.0",
"@svgr/babel-plugin-transform-react-native-svg": "^5.4.0",
"@svgr/babel-plugin-transform-svg-component": "^5.5.0"
},
"deprecated": false,
"description": "SVGR preset that apply transformations from config",
"engines": {
"node": ">=10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/gregberge"
},
"gitHead": "b5920550bd966f876cb65c5e23af180461e5aa23",
"homepage": "https://react-svgr.com",
"keywords": [
"babel-plugin",
"babel-preset"
],
"license": "MIT",
"main": "lib/index.js",
"name": "@svgr/babel-preset",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/gregberge/svgr/tree/master/packages/babel-preset"
},
"scripts": {
"build": "babel --config-file ../../babel.config.js -d lib --ignore \"**/*.test.js\" src",
"prebuild": "rm -rf lib/",
"prepublishOnly": "yarn run build"
},
"version": "5.5.0"
}
This diff is collapsed. Click to expand it.
Copyright 2017 Smooth Code
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# @svgr/core
[![Build Status][build-badge]][build]
[![version][version-badge]][package]
[![MIT License][license-badge]][license]
Node API of SVGR.
```
npm install @svgr/core
```
## Usage
```js
import svgr from '@svgr/core'
const svgCode = `
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<rect x="10" y="10" height="100" width="100"
style="stroke:#ff0000; fill: #0000ff"/>
</svg>
`
svgr(svgCode, { icon: true }, { componentName: 'MyComponent' }).then(
(jsCode) => {
console.log(jsCode)
},
)
```
Use `svgr.sync(code, config, state)` if you would like to use sync version.
### Plugins
By default `@svgr/core` doesn't include `svgo` and `prettier` plugins, if you want them, you have to install them and include them in config.
```js
svgr(svgCode, {
plugins: ['@svgr/plugin-svgo', '@svgr/plugin-jsx', '@svgr/plugin-prettier'],
}).then((jsCode) => {
console.log(jsCode)
})
```
## License
MIT
[build-badge]: https://img.shields.io/travis/smooth-code/svgr.svg?style=flat-square
[build]: https://travis-ci.org/smooth-code/svgr
[version-badge]: https://img.shields.io/npm/v/@svgr/core.svg?style=flat-square
[package]: https://www.npmjs.com/package/@svgr/core
[license-badge]: https://img.shields.io/npm/l/@svgr/core.svg?style=flat-square
[license]: https://github.com/smooth-code/svgr/blob/master/LICENSE
```
```
"use strict";
exports.__esModule = true;
exports.resolveConfig = resolveConfig;
exports.resolveConfigFile = resolveConfigFile;
exports.loadConfig = loadConfig;
exports.DEFAULT_CONFIG = void 0;
var _cosmiconfig = require("cosmiconfig");
const DEFAULT_CONFIG = {
dimensions: true,
expandProps: 'end',
icon: false,
native: false,
typescript: false,
prettier: true,
prettierConfig: null,
memo: false,
ref: false,
replaceAttrValues: null,
svgProps: null,
svgo: true,
svgoConfig: null,
template: null,
titleProp: false,
runtimeConfig: true,
plugins: null,
namedExport: 'ReactComponent'
};
exports.DEFAULT_CONFIG = DEFAULT_CONFIG;
const explorer = (0, _cosmiconfig.cosmiconfig)('svgr', {
sync: true,
cache: true,
rcExtensions: true
});
const explorerSync = (0, _cosmiconfig.cosmiconfigSync)('svgr', {
sync: true,
cache: true,
rcExtensions: true
});
async function resolveConfig(searchFrom, configFile) {
if (configFile == null) {
const result = await explorer.search(searchFrom);
return result ? result.config : null;
}
const result = await explorer.load(configFile);
return result ? result.config : null;
}
resolveConfig.sync = (searchFrom, configFile) => {
if (configFile == null) {
const result = explorerSync.search(searchFrom);
return result ? result.config : null;
}
const result = explorerSync.load(configFile);
return result ? result.config : null;
};
async function resolveConfigFile(filePath) {
const result = await explorer.search(filePath);
return result ? result.filepath : null;
}
resolveConfigFile.sync = filePath => {
const result = explorerSync.search(filePath);
return result ? result.filepath : null;
};
async function loadConfig({
configFile,
...baseConfig
}, state = {}) {
const rcConfig = state.filePath && baseConfig.runtimeConfig !== false ? await resolveConfig(state.filePath, configFile) : {};
return { ...DEFAULT_CONFIG,
...rcConfig,
...baseConfig
};
}
loadConfig.sync = ({
configFile,
...baseConfig
}, state = {}) => {
const rcConfig = state.filePath && baseConfig.runtimeConfig !== false ? resolveConfig.sync(state.filePath, configFile) : {};
return { ...DEFAULT_CONFIG,
...rcConfig,
...baseConfig
};
};
\ No newline at end of file
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _state = require("./state");
var _config = require("./config");
var _plugins = require("./plugins");
function run(code, config, state) {
const expandedState = (0, _state.expandState)(state);
const plugins = (0, _plugins.getPlugins)(config, state).map(_plugins.resolvePlugin);
let nextCode = String(code).replace('\0', ''); // eslint-disable-next-line no-restricted-syntax
for (const plugin of plugins) {
nextCode = plugin(nextCode, config, expandedState);
}
return nextCode;
}
async function convert(code, config = {}, state = {}) {
config = await (0, _config.loadConfig)(config, state);
return run(code, config, state);
}
convert.sync = (code, config = {}, state = {}) => {
config = _config.loadConfig.sync(config, state);
return run(code, config, state);
};
var _default = convert;
exports.default = _default;
\ No newline at end of file
"use strict";
exports.__esModule = true;
var _exportNames = {};
exports.default = void 0;
var _convert = _interopRequireDefault(require("./convert"));
exports.default = _convert.default;
var _config = require("./config");
Object.keys(_config).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _config[key]) return;
exports[key] = _config[key];
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
\ No newline at end of file
"use strict";
exports.__esModule = true;
exports.getPlugins = getPlugins;
exports.resolvePlugin = resolvePlugin;
exports.loadPlugin = loadPlugin;
var _pluginJsx = _interopRequireDefault(require("@svgr/plugin-jsx"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const DEFAULT_PLUGINS = [_pluginJsx.default];
function getPlugins(config, state) {
if (config.plugins) {
return config.plugins;
}
if (state.caller && state.caller.defaultPlugins) {
return state.caller.defaultPlugins;
}
return DEFAULT_PLUGINS;
}
function resolvePlugin(plugin) {
if (typeof plugin === 'function') {
return plugin;
}
if (typeof plugin === 'string') {
return loadPlugin(plugin);
}
throw new Error(`Invalid plugin "${plugin}"`);
}
const pluginCache = {};
function loadPlugin(moduleName) {
if (pluginCache[moduleName]) {
return pluginCache[moduleName];
}
try {
// eslint-disable-next-line
const plugin = require(moduleName);
if (!plugin.default || !plugin) {
throw new Error(`Invalid plugin "${moduleName}"`);
}
pluginCache[moduleName] = plugin.default || plugin;
return pluginCache[moduleName];
} catch (error) {
throw new Error(`Module "${moduleName}" missing. Maybe \`npm install ${moduleName}\` could help!`);
}
}
\ No newline at end of file
"use strict";
exports.__esModule = true;
exports.expandState = expandState;
var _path = _interopRequireDefault(require("path"));
var _camelcase = _interopRequireDefault(require("camelcase"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const validCharacters = /[^a-zA-Z0-9_-]/g;
function getComponentName(state) {
if (!state.filePath) return 'SvgComponent';
const pascalCaseFileName = (0, _camelcase.default)(_path.default.parse(state.filePath).name.replace(validCharacters, ''), {
pascalCase: true
});
return `Svg${pascalCaseFileName}`;
}
function expandState(state) {
return {
componentName: state.componentName || getComponentName(state),
...state
};
}
\ No newline at end of file
{
"_from": "@svgr/core@^5.4.0",
"_id": "@svgr/core@5.5.0",
"_inBundle": false,
"_integrity": "sha512-q52VOcsJPvV3jO1wkPtzTuKlvX7Y3xIcWRpCMtBF3MrteZJtBfQw/+u0B1BHy5ColpQc1/YVTrPEtSYIMNZlrQ==",
"_location": "/@svgr/core",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@svgr/core@^5.4.0",
"name": "@svgr/core",
"escapedName": "@svgr%2fcore",
"scope": "@svgr",
"rawSpec": "^5.4.0",
"saveSpec": null,
"fetchSpec": "^5.4.0"
},
"_requiredBy": [
"/@svgr/webpack"
],
"_resolved": "https://registry.npmjs.org/@svgr/core/-/core-5.5.0.tgz",
"_shasum": "82e826b8715d71083120fe8f2492ec7d7874a579",
"_spec": "@svgr/core@^5.4.0",
"_where": "C:\\Users\\kkwan_000\\Desktop\\git\\2017110269\\minsung\\node_modules\\@svgr\\webpack",
"author": {
"name": "Greg Bergé",
"email": "berge.greg@gmail.com"
},
"bundleDependencies": false,
"dependencies": {
"@svgr/plugin-jsx": "^5.5.0",
"camelcase": "^6.2.0",
"cosmiconfig": "^7.0.0"
},
"deprecated": false,
"description": "Transform SVG into React Components.",
"engines": {
"node": ">=10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/gregberge"
},
"gitHead": "b5920550bd966f876cb65c5e23af180461e5aa23",
"homepage": "https://react-svgr.com",
"keywords": [
"svgr",
"svg",
"react",
"core",
"api"
],
"license": "MIT",
"main": "lib/index.js",
"name": "@svgr/core",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/gregberge/svgr/tree/master/packages/core"
},
"scripts": {
"build": "babel --config-file ../../babel.config.js -d lib --ignore \"**/*.test.js\" src",
"prebuild": "rm -rf lib/",
"prepublishOnly": "yarn run build"
},
"version": "5.5.0"
}
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
# [5.5.0](https://github.com/gregberge/svgr/tree/master/packages/hast-util-to-babel-ast/compare/v5.4.0...v5.5.0) (2020-11-15)
**Note:** Version bump only for package @svgr/hast-util-to-babel-ast
# [5.4.0](https://github.com/gregberge/svgr/tree/master/packages/hast-util-to-babel-ast/compare/v5.3.1...v5.4.0) (2020-04-27)
**Note:** Version bump only for package @svgr/hast-util-to-babel-ast
## [5.0.1](https://github.com/gregberge/svgr/tree/master/packages/hast-util-to-babel-ast/compare/v5.0.0...v5.0.1) (2019-12-29)
### Bug Fixes
* fix engines in package.json ([a45d6fc](https://github.com/gregberge/svgr/tree/master/packages/hast-util-to-babel-ast/commit/a45d6fc8b43402bec60ed4e9273f90fdc65a23a7))
## [4.3.2](https://github.com/gregberge/svgr/tree/master/packages/hast-util-to-babel-ast/compare/v4.3.1...v4.3.2) (2019-07-15)
### Performance Improvements
* replace rehype with svg-parser ([#321](https://github.com/gregberge/svgr/tree/master/packages/hast-util-to-babel-ast/issues/321)) ([7eb5ef6](https://github.com/gregberge/svgr/tree/master/packages/hast-util-to-babel-ast/commit/7eb5ef6))
## [4.3.1](https://github.com/gregberge/svgr/tree/master/packages/hast-util-to-babel-ast/compare/v4.3.0...v4.3.1) (2019-07-01)
**Note:** Version bump only for package @svgr/hast-util-to-babel-ast
# [4.2.0](https://github.com/gregberge/svgr/tree/master/packages/hast-util-to-babel-ast/compare/v4.1.0...v4.2.0) (2019-04-11)
### Bug Fixes
* **hast-util-to-babel-ast:** correctly handle aria attributes ([23d12aa](https://github.com/gregberge/svgr/tree/master/packages/hast-util-to-babel-ast/commit/23d12aa)), closes [#279](https://github.com/gregberge/svgr/tree/master/packages/hast-util-to-babel-ast/issues/279)
# [4.1.0](https://github.com/gregberge/svgr/compare/v4.0.4...v4.1.0) (2018-11-24)
**Note:** Version bump only for package @svgr/hast-util-to-babel-ast
## [4.0.3](https://github.com/gregberge/svgr/compare/v4.0.2...v4.0.3) (2018-11-13)
### Bug Fixes
* upgrade dependencies ([7e2195f](https://github.com/gregberge/svgr/commit/7e2195f))
## [4.0.2](https://github.com/gregberge/svgr/compare/v4.0.1...v4.0.2) (2018-11-08)
### Bug Fixes
* **hast-util-to-babel-ast:** replace tabs by spaces in attributes ([b0f3d19](https://github.com/gregberge/svgr/commit/b0f3d19)), closes [#219](https://github.com/gregberge/svgr/issues/219)
## [4.0.1](https://github.com/gregberge/svgr/compare/v4.0.0...v4.0.1) (2018-11-08)
### Bug Fixes
* **hast-util-to-babel-ast:** correctly transforms data & aria attributes ([99711c4](https://github.com/gregberge/svgr/commit/99711c4)), closes [#221](https://github.com/gregberge/svgr/issues/221)
* **hast-util-to-babel-ast:** replace line-breaks in attributes ([00a2625](https://github.com/gregberge/svgr/commit/00a2625)), closes [#219](https://github.com/gregberge/svgr/issues/219)
# [4.0.0](https://github.com/gregberge/svgr/compare/v3.1.0...v4.0.0) (2018-11-04)
### Features
* **v4:** new architecture ([ac8b8ca](https://github.com/gregberge/svgr/commit/ac8b8ca))
### BREAKING CHANGES
* **v4:** - `template` option must now returns a Babel AST
- `@svgr/core` does not include svgo & prettier by default
Copyright 2017 Smooth Code
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# @svgr/hast-util-to-babel-ast
[![Build Status](https://img.shields.io/travis/smooth-code/svgr.svg)](https://travis-ci.org/smooth-code/svgr)
[![Version](https://img.shields.io/npm/v/@svgr/hast-util-to-babel-ast.svg)](https://www.npmjs.com/package/@svgr/hast-util-to-babel-ast)
[![MIT License](https://img.shields.io/npm/l/@svgr/hast-util-to-babel-ast.svg)](https://github.com/smooth-code/svgr/blob/master/LICENSE)
Transforms HAST into Babel AST.
## Install
```
npm install --save-dev @svgr/hast-util-to-babel-ast
```
## Usage
```js
import { parse } from 'svg-parser'
import toBabelAST from '@svgr/hast-util-to-babel-ast'
const hastTree = parse(`<svg></svg>`)
const babelTree = hastToBabelAst(hastTree)
```
## License
MIT
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _one = _interopRequireDefault(require("./one"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* Transform the children of `parent`. */
function all(h, parent) {
const nodes = parent.children || [];
const {
length
} = nodes;
const values = [];
let index = -1;
while (++index < length) {
const result = (0, _one.default)(h, nodes[index], parent);
values.push(result);
}
return values.filter(node => node);
}
var _default = all;
exports.default = _default;
\ No newline at end of file
"use strict";
exports.__esModule = true;
exports.default = void 0;
var t = _interopRequireWildcard(require("@babel/types"));
var _util = require("./util");
var _stringToObjectStyle = _interopRequireDefault(require("./stringToObjectStyle"));
var _mappings = require("./mappings");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function convertAriaAttribute(kebabKey) {
const [aria, ...parts] = kebabKey.split('-');
return `${aria}-${parts.join('').toLowerCase()}`;
}
function getKey(key, value, node) {
const lowerCaseKey = key.toLowerCase();
const mappedElementAttribute = _mappings.ELEMENT_ATTRIBUTE_MAPPING[node.name] && _mappings.ELEMENT_ATTRIBUTE_MAPPING[node.name][lowerCaseKey];
const mappedAttribute = _mappings.ATTRIBUTE_MAPPING[lowerCaseKey];
if (mappedElementAttribute || mappedAttribute) {
return t.jsxIdentifier(mappedElementAttribute || mappedAttribute);
}
const kebabKey = (0, _util.kebabCase)(key);
if (kebabKey.startsWith('aria-')) {
return t.jsxIdentifier(convertAriaAttribute(kebabKey));
}
if (kebabKey.startsWith('data-')) {
return t.jsxIdentifier(kebabKey);
}
return t.jsxIdentifier(key);
}
function getValue(key, value) {
// Handle className
if (Array.isArray(value)) {
return t.stringLiteral((0, _util.replaceSpaces)(value.join(' ')));
}
if (key === 'style') {
return t.jsxExpressionContainer((0, _stringToObjectStyle.default)(value));
}
if ((0, _util.isNumeric)(value)) {
return t.jsxExpressionContainer(t.numericLiteral(Number(value)));
}
return t.stringLiteral((0, _util.replaceSpaces)(value));
}
const getAttributes = node => {
const keys = Object.keys(node.properties);
const attributes = [];
let index = -1;
while (++index < keys.length) {
const key = keys[index];
const value = node.properties[key];
const attribute = t.jsxAttribute(getKey(key, value, node), getValue(key, value, node));
attributes.push(attribute);
}
return attributes;
};
var _default = getAttributes;
exports.default = _default;
\ No newline at end of file
"use strict";
exports.__esModule = true;
exports.element = exports.text = exports.comment = exports.root = void 0;
var t = _interopRequireWildcard(require("@babel/types"));
var _all = _interopRequireDefault(require("./all"));
var _getAttributes = _interopRequireDefault(require("./getAttributes"));
var _mappings = require("./mappings");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const root = (h, node) => t.program((0, _all.default)(h, node));
exports.root = root;
const comment = (h, node, parent) => {
if (parent.type === 'root') {
return null;
}
const expression = t.jsxEmptyExpression();
t.addComment(expression, 'inner', node.value);
return t.jsxExpressionContainer(expression);
};
exports.comment = comment;
const text = (h, node, parent) => {
if (parent.type === 'root') {
return null;
}
if (node.value.match(/^\s+$/)) {
return null;
}
return t.jsxExpressionContainer(t.stringLiteral(node.value));
};
exports.text = text;
const element = (h, node, parent) => {
const children = (0, _all.default)(h, node);
const selfClosing = children.length === 0;
const name = _mappings.ELEMENT_TAG_NAME_MAPPING[node.tagName] || node.tagName;
const openingElement = t.jsxOpeningElement(t.jsxIdentifier(name), (0, _getAttributes.default)(node), selfClosing);
const closingElement = !selfClosing ? t.jsxClosingElement(t.jsxIdentifier(name)) : null;
const jsxElement = t.jsxElement(openingElement, closingElement, children);
if (parent.type === 'root') {
return t.expressionStatement(jsxElement);
}
return jsxElement;
};
exports.element = element;
\ No newline at end of file
"use strict";
exports.__esModule = true;
exports.default = void 0;
var handlers = _interopRequireWildcard(require("./handlers"));
var _one = _interopRequireDefault(require("./one"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const h = {
handlers
};
function toBabelAST(tree) {
return (0, _one.default)(h, tree);
}
var _default = toBabelAST;
exports.default = _default;
\ No newline at end of file
"use strict";
exports.__esModule = true;
exports.default = void 0;
function one(h, node, parent) {
const type = node && node.type;
const fn = h.handlers[type];
/* Fail on non-nodes. */
if (!type) {
throw new Error(`Expected node, got \`${node}\``);
}
if (!fn) {
throw new Error(`Node of type ${type} is unknown`);
}
return fn(h, node, parent);
}
var _default = one;
exports.default = _default;
\ No newline at end of file
"use strict";
exports.__esModule = true;
exports.default = void 0;
var t = _interopRequireWildcard(require("@babel/types"));
var _util = require("./util");
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
// Inspired by https://github.com/reactjs/react-magic/blob/master/src/htmltojsx.js
/**
* Determines if the CSS value can be converted from a
* 'px' suffixed string to a numeric value.
*
* @param {string} value CSS property value
* @return {boolean}
*/
function isConvertiblePixelValue(value) {
return /^\d+px$/.test(value);
}
/**
* Format style key into JSX style object key.
*
* @param {string} key
* @return {string}
*/
function formatKey(key) {
key = key.toLowerCase(); // Don't capitalize -ms- prefix
if (/^-ms-/.test(key)) key = key.substr(1);
return t.identifier((0, _util.hyphenToCamelCase)(key));
}
/**
* Format style value into JSX style object value.
*
* @param {string} key
* @return {string}
*/
function formatValue(value) {
if ((0, _util.isNumeric)(value)) return t.numericLiteral(Number(value));
if (isConvertiblePixelValue(value)) return t.numericLiteral(Number((0, _util.trimEnd)(value, 'px')));
return t.stringLiteral(value);
}
/**
* Handle parsing of inline styles.
*
* @param {string} rawStyle
* @returns {object}
*/
function stringToObjectStyle(rawStyle) {
const entries = rawStyle.split(';');
const properties = [];
let index = -1;
while (++index < entries.length) {
const entry = entries[index];
const style = entry.trim();
const firstColon = style.indexOf(':');
const value = style.substr(firstColon + 1).trim();
const key = style.substr(0, firstColon);
if (key !== '') {
const property = t.objectProperty(formatKey(key), formatValue(value));
properties.push(property);
}
}
return t.objectExpression(properties);
}
var _default = stringToObjectStyle;
exports.default = _default;
\ No newline at end of file
"use strict";
exports.__esModule = true;
exports.isNumeric = isNumeric;
exports.hyphenToCamelCase = hyphenToCamelCase;
exports.trimEnd = trimEnd;
exports.kebabCase = kebabCase;
exports.replaceSpaces = replaceSpaces;
/**
* Determines if the specified string consists entirely of numeric characters.
*
* @param {*} [value]
* @returns {boolean}
*/
function isNumeric(value) {
return !Number.isNaN(value - parseFloat(value));
}
/**
* Convert a hyphenated string to camelCase.
*
* @param {string} string
* @returns {string}
*/
function hyphenToCamelCase(string) {
return string.replace(/-(.)/g, (match, chr) => chr.toUpperCase());
}
/**
* Trim the specified substring off the string. If the string does not end
* with the specified substring, this is a no-op.
*
* @param {string} haystack String to search in
* @param {string} needle String to search for
* @return {string}
*/
function trimEnd(haystack, needle) {
return haystack.endsWith(needle) ? haystack.slice(0, -needle.length) : haystack;
}
const KEBAB_REGEX = /[A-Z\u00C0-\u00D6\u00D8-\u00DE]/g;
function kebabCase(str) {
return str.replace(KEBAB_REGEX, match => `-${match.toLowerCase()}`);
}
const SPACES_REGEXP = /[\t\r\n\u0085\u2028\u2029]+/g;
function replaceSpaces(str) {
return str.replace(SPACES_REGEXP, ' ');
}
\ No newline at end of file
{
"_from": "@svgr/hast-util-to-babel-ast@^5.5.0",
"_id": "@svgr/hast-util-to-babel-ast@5.5.0",
"_inBundle": false,
"_integrity": "sha512-cAaR/CAiZRB8GP32N+1jocovUtvlj0+e65TB50/6Lcime+EA49m/8l+P2ko+XPJ4dw3xaPS3jOL4F2X4KWxoeQ==",
"_location": "/@svgr/hast-util-to-babel-ast",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@svgr/hast-util-to-babel-ast@^5.5.0",
"name": "@svgr/hast-util-to-babel-ast",
"escapedName": "@svgr%2fhast-util-to-babel-ast",
"scope": "@svgr",
"rawSpec": "^5.5.0",
"saveSpec": null,
"fetchSpec": "^5.5.0"
},
"_requiredBy": [
"/@svgr/plugin-jsx"
],
"_resolved": "https://registry.npmjs.org/@svgr/hast-util-to-babel-ast/-/hast-util-to-babel-ast-5.5.0.tgz",
"_shasum": "5ee52a9c2533f73e63f8f22b779f93cd432a5461",
"_spec": "@svgr/hast-util-to-babel-ast@^5.5.0",
"_where": "C:\\Users\\kkwan_000\\Desktop\\git\\2017110269\\minsung\\node_modules\\@svgr\\plugin-jsx",
"author": {
"name": "Greg Bergé",
"email": "berge.greg@gmail.com"
},
"bundleDependencies": false,
"dependencies": {
"@babel/types": "^7.12.6"
},
"deprecated": false,
"description": "Transform HAST to Babel AST (JSX)",
"engines": {
"node": ">=10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/gregberge"
},
"gitHead": "b5920550bd966f876cb65c5e23af180461e5aa23",
"homepage": "https://react-svgr.com",
"keywords": [
"html",
"hast",
"babel",
"hast-util",
"unist-util",
"unist"
],
"license": "MIT",
"main": "lib/index.js",
"name": "@svgr/hast-util-to-babel-ast",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/gregberge/svgr/tree/master/packages/hast-util-to-babel-ast"
},
"scripts": {
"build": "babel --config-file ../../babel.config.js -d lib --ignore \"**/*.test.js\" src",
"prebuild": "rm -rf lib/",
"prepublishOnly": "yarn run build"
},
"version": "5.5.0"
}
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
# [5.5.0](https://github.com/gregberge/svgr/tree/master/packages/plugin-jsx/compare/v5.4.0...v5.5.0) (2020-11-15)
### Bug Fixes
* prevent removing the namespace by svgr ([[#475](https://github.com/gregberge/svgr/tree/master/packages/plugin-jsx/issues/475)](https://github.com/gregberge/svgr/issues/475) ([#498](https://github.com/gregberge/svgr/tree/master/packages/plugin-jsx/issues/498)) ([00e84ea](https://github.com/gregberge/svgr/tree/master/packages/plugin-jsx/commit/00e84ead96d89bcbd072b9585b4db1365e392d33))
# [5.4.0](https://github.com/gregberge/svgr/tree/master/packages/plugin-jsx/compare/v5.3.1...v5.4.0) (2020-04-27)
**Note:** Version bump only for package @svgr/plugin-jsx
## [5.3.1](https://github.com/gregberge/svgr/tree/master/packages/plugin-jsx/compare/v5.3.0...v5.3.1) (2020-04-05)
**Note:** Version bump only for package @svgr/plugin-jsx
# [5.3.0](https://github.com/gregberge/svgr/tree/master/packages/plugin-jsx/compare/v5.2.0...v5.3.0) (2020-03-22)
**Note:** Version bump only for package @svgr/plugin-jsx
# [5.2.0](https://github.com/gregberge/svgr/tree/master/packages/plugin-jsx/compare/v5.1.0...v5.2.0) (2020-02-23)
**Note:** Version bump only for package @svgr/plugin-jsx
## [5.0.1](https://github.com/gregberge/svgr/tree/master/packages/plugin-jsx/compare/v5.0.0...v5.0.1) (2019-12-29)
### Bug Fixes
* fix engines in package.json ([a45d6fc](https://github.com/gregberge/svgr/tree/master/packages/plugin-jsx/commit/a45d6fc8b43402bec60ed4e9273f90fdc65a23a7))
## [4.3.3](https://github.com/gregberge/svgr/tree/master/packages/plugin-jsx/compare/v4.3.2...v4.3.3) (2019-09-24)
**Note:** Version bump only for package @svgr/plugin-jsx
## [4.3.2](https://github.com/gregberge/svgr/tree/master/packages/plugin-jsx/compare/v4.3.1...v4.3.2) (2019-07-15)
### Performance Improvements
* replace rehype with svg-parser ([#321](https://github.com/gregberge/svgr/tree/master/packages/plugin-jsx/issues/321)) ([7eb5ef6](https://github.com/gregberge/svgr/tree/master/packages/plugin-jsx/commit/7eb5ef6))
## [4.3.1](https://github.com/gregberge/svgr/tree/master/packages/plugin-jsx/compare/v4.3.0...v4.3.1) (2019-07-01)
**Note:** Version bump only for package @svgr/plugin-jsx
# [4.3.0](https://github.com/gregberge/svgr/tree/master/packages/plugin-jsx/compare/v4.2.0...v4.3.0) (2019-05-28)
**Note:** Version bump only for package @svgr/plugin-jsx
# [4.2.0](https://github.com/gregberge/svgr/tree/master/packages/plugin-jsx/compare/v4.1.0...v4.2.0) (2019-04-11)
**Note:** Version bump only for package @svgr/plugin-jsx
# [4.1.0](https://github.com/gregberge/svgr/compare/v4.0.4...v4.1.0) (2018-11-24)
**Note:** Version bump only for package @svgr/plugin-jsx
## [4.0.3](https://github.com/gregberge/svgr/compare/v4.0.2...v4.0.3) (2018-11-13)
### Bug Fixes
* upgrade dependencies ([7e2195f](https://github.com/gregberge/svgr/commit/7e2195f))
## [4.0.2](https://github.com/gregberge/svgr/compare/v4.0.1...v4.0.2) (2018-11-08)
**Note:** Version bump only for package @svgr/plugin-jsx
## [4.0.1](https://github.com/gregberge/svgr/compare/v4.0.0...v4.0.1) (2018-11-08)
**Note:** Version bump only for package @svgr/plugin-jsx
# [4.0.0](https://github.com/gregberge/svgr/compare/v3.1.0...v4.0.0) (2018-11-04)
### Features
* **svgo:** prefix ids by default ([06c338d](https://github.com/gregberge/svgr/commit/06c338d)), closes [#210](https://github.com/gregberge/svgr/issues/210)
* **v4:** new architecture ([ac8b8ca](https://github.com/gregberge/svgr/commit/ac8b8ca))
### BREAKING CHANGES
* **v4:** - `template` option must now returns a Babel AST
- `@svgr/core` does not include svgo & prettier by default
Copyright 2017 Smooth Code
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# @svgr/plugin-jsx
[![Build Status](https://img.shields.io/travis/smooth-code/svgr.svg)](https://travis-ci.org/smooth-code/svgr)
[![Version](https://img.shields.io/npm/v/@svgr/plugin-jsx.svg)](https://www.npmjs.com/package/@svgr/plugin-jsx)
[![MIT License](https://img.shields.io/npm/l/@svgr/plugin-jsx.svg)](https://github.com/smooth-code/svgr/blob/master/LICENSE)
Transforms SVG into JSX.
## Install
```
npm install --save-dev @svgr/plugin-jsx
```
## Usage
**.svgrrc**
```json
{
"plugins": ["@svgr/plugin-jsx"]
}
```
## How does it work?
`@svgr/plugin-jsx` consists in three phases:
- Parsing the SVG code using [svg-parser](https://github.com/Rich-Harris/svg-parser)
- Converting the [HAST](https://github.com/syntax-tree/hast) into a [Babel AST](https://github.com/babel/babel/blob/master/packages/babel-parser/ast/spec.md)
- Applying [`@svgr/babel-preset`](../babel-preset/README.md) transformations
## Applying custom transformations
You can extend the Babel config applied in this plugin using `jsx.babelConfig` config path:
```js
// .svgrrc.js
module.exports = {
jsx: {
babelConfig: {
plugins: [
// For an example, this plugin will remove "id" attribute from "svg" tag
[
'@svgr/babel-plugin-remove-jsx-attribute',
{
elements: ['svg'],
attributes: ['id'],
},
],
],
},
},
}
```
Several Babel plugins are available:
- [`@svgr/babel-plugin-add-jsx-attribute`](../babel-plugin-add-jsx-attribute/README.md)
- [`@svgr/babel-plugin-remove-jsx-attribute`](../babel-plugin-remove-jsx-attribute/README.md)
- [`@svgr/babel-plugin-remove-jsx-empty-expression`](../babel-plugin-remove-jsx-empty-expression/README.md)
- [`@svgr/babel-plugin-replace-jsx-attribute-value`](../babel-plugin-replace-jsx-attribute-value/README.md)
- [`@svgr/babel-plugin-svg-dynamic-title`](../babel-plugin-svg-dynamic-title/README.md)
- [`@svgr/babel-plugin-svg-em-dimensions`](../babel-plugin-svg-em-dimensions/README.md)
- [`@svgr/babel-plugin-transform-react-native-svg`](../babel-plugin-transform-react-native-svg/README.md)
- [`@svgr/babel-plugin-transform-svg-component`](../babel-plugin-transform-svg-component/README.md)
If you want to create your own, reading [Babel Handbook](https://github.com/jamiebuilds/babel-handbook/blob/master/translations/en/plugin-handbook.md) is a good start!
## License
MIT
"use strict";
exports.__esModule = true;
exports.default = jsxPlugin;
var _svgParser = require("svg-parser");
var _hastUtilToBabelAst = _interopRequireDefault(require("@svgr/hast-util-to-babel-ast"));
var _core = require("@babel/core");
var _babelPreset = _interopRequireDefault(require("@svgr/babel-preset"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function jsxPlugin(code, config, state) {
const filePath = state.filePath || 'unknown';
const hastTree = (0, _svgParser.parse)(code);
const babelTree = (0, _hastUtilToBabelAst.default)(hastTree);
const {
code: generatedCode
} = (0, _core.transformFromAstSync)(babelTree, code, {
caller: {
name: 'svgr'
},
presets: [(0, _core.createConfigItem)([_babelPreset.default, { ...config,
state
}], {
type: 'preset'
})],
filename: filePath,
babelrc: false,
configFile: false,
code: true,
ast: false,
inputSourceMap: false,
...(config.jsx && config.jsx.babelConfig)
});
return generatedCode;
}
\ No newline at end of file
{
"_from": "@svgr/plugin-jsx@^5.4.0",
"_id": "@svgr/plugin-jsx@5.5.0",
"_inBundle": false,
"_integrity": "sha512-V/wVh33j12hGh05IDg8GpIUXbjAPnTdPTKuP4VNLggnwaHMPNQNae2pRnyTAILWCQdz5GyMqtO488g7CKM8CBA==",
"_location": "/@svgr/plugin-jsx",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@svgr/plugin-jsx@^5.4.0",
"name": "@svgr/plugin-jsx",
"escapedName": "@svgr%2fplugin-jsx",
"scope": "@svgr",
"rawSpec": "^5.4.0",
"saveSpec": null,
"fetchSpec": "^5.4.0"
},
"_requiredBy": [
"/@svgr/core",
"/@svgr/webpack"
],
"_resolved": "https://registry.npmjs.org/@svgr/plugin-jsx/-/plugin-jsx-5.5.0.tgz",
"_shasum": "1aa8cd798a1db7173ac043466d7b52236b369000",
"_spec": "@svgr/plugin-jsx@^5.4.0",
"_where": "C:\\Users\\kkwan_000\\Desktop\\git\\2017110269\\minsung\\node_modules\\@svgr\\webpack",
"author": {
"name": "Greg Bergé",
"email": "berge.greg@gmail.com"
},
"bundleDependencies": false,
"dependencies": {
"@babel/core": "^7.12.3",
"@svgr/babel-preset": "^5.5.0",
"@svgr/hast-util-to-babel-ast": "^5.5.0",
"svg-parser": "^2.0.2"
},
"deprecated": false,
"description": "Transform SVG into JSX",
"engines": {
"node": ">=10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/gregberge"
},
"gitHead": "b5920550bd966f876cb65c5e23af180461e5aa23",
"homepage": "https://react-svgr.com",
"keywords": [
"svgr-plugin"
],
"license": "MIT",
"main": "lib/index.js",
"name": "@svgr/plugin-jsx",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/gregberge/svgr/tree/master/packages/plugin-jsx"
},
"scripts": {
"build": "babel --config-file ../../babel.config.js -d lib --ignore \"**/*.test.js\" src",
"prebuild": "rm -rf lib/",
"prepublishOnly": "yarn run build"
},
"version": "5.5.0"
}
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
# [5.5.0](https://github.com/gregberge/svgr/tree/master/packages/plugin-svgo/compare/v5.4.0...v5.5.0) (2020-11-15)
### Features
* **svgo:** add .svgorc.js config file support ([#451](https://github.com/gregberge/svgr/tree/master/packages/plugin-svgo/issues/451)) ([8049b1a](https://github.com/gregberge/svgr/tree/master/packages/plugin-svgo/commit/8049b1a63603672096892b6ab3d303580c2f303f)), closes [#412](https://github.com/gregberge/svgr/tree/master/packages/plugin-svgo/issues/412)
### Performance Improvements
* replace merge-deep with smaller deepmerge ([#463](https://github.com/gregberge/svgr/tree/master/packages/plugin-svgo/issues/463)) ([1f015eb](https://github.com/gregberge/svgr/tree/master/packages/plugin-svgo/commit/1f015eb16fca093a08b012236dc83623f7bcce55))
# [5.4.0](https://github.com/gregberge/svgr/tree/master/packages/plugin-svgo/compare/v5.3.1...v5.4.0) (2020-04-27)
**Note:** Version bump only for package @svgr/plugin-svgo
# [5.3.0](https://github.com/gregberge/svgr/tree/master/packages/plugin-svgo/compare/v5.2.0...v5.3.0) (2020-03-22)
### Bug Fixes
* **svgo:** support any SVGO config format ([#412](https://github.com/gregberge/svgr/tree/master/packages/plugin-svgo/issues/412)) ([f2b2367](https://github.com/gregberge/svgr/tree/master/packages/plugin-svgo/commit/f2b2367389fda20baba6e0a5e884e7f7fe29a3ed)), closes [#400](https://github.com/gregberge/svgr/tree/master/packages/plugin-svgo/issues/400)
# [5.2.0](https://github.com/gregberge/svgr/tree/master/packages/plugin-svgo/compare/v5.1.0...v5.2.0) (2020-02-23)
### Bug Fixes
* verify that `svgoConfig.plugins` is an array ([#397](https://github.com/gregberge/svgr/tree/master/packages/plugin-svgo/issues/397)) ([88110b6](https://github.com/gregberge/svgr/tree/master/packages/plugin-svgo/commit/88110b6eb4d93ded68ca2de05cc82654dfac977d))
# [5.1.0](https://github.com/gregberge/svgr/tree/master/packages/plugin-svgo/compare/v5.0.1...v5.1.0) (2020-01-20)
### Bug Fixes
* fix merging svgo plugins in config ([#384](https://github.com/gregberge/svgr/tree/master/packages/plugin-svgo/issues/384)) ([c9d2dfc](https://github.com/gregberge/svgr/tree/master/packages/plugin-svgo/commit/c9d2dfcb8d4da55eb21a13507c87d9e549a86e7e))
## [5.0.1](https://github.com/gregberge/svgr/tree/master/packages/plugin-svgo/compare/v5.0.0...v5.0.1) (2019-12-29)
### Bug Fixes
* fix engines in package.json ([a45d6fc](https://github.com/gregberge/svgr/tree/master/packages/plugin-svgo/commit/a45d6fc8b43402bec60ed4e9273f90fdc65a23a7))
## [4.3.1](https://github.com/gregberge/svgr/tree/master/packages/plugin-svgo/compare/v4.3.0...v4.3.1) (2019-07-01)
**Note:** Version bump only for package @svgr/plugin-svgo
# [4.2.0](https://github.com/gregberge/svgr/tree/master/packages/plugin-svgo/compare/v4.1.0...v4.2.0) (2019-04-11)
### Bug Fixes
* keep viewBox when dimensions are removed ([#281](https://github.com/gregberge/svgr/tree/master/packages/plugin-svgo/issues/281)) ([f476c8e](https://github.com/gregberge/svgr/tree/master/packages/plugin-svgo/commit/f476c8e))
## [4.0.3](https://github.com/gregberge/svgr/compare/v4.0.2...v4.0.3) (2018-11-13)
### Bug Fixes
* upgrade dependencies ([7e2195f](https://github.com/gregberge/svgr/commit/7e2195f))
# [4.0.0](https://github.com/gregberge/svgr/compare/v3.1.0...v4.0.0) (2018-11-04)
### Features
* **svgo:** prefix ids by default ([06c338d](https://github.com/gregberge/svgr/commit/06c338d)), closes [#210](https://github.com/gregberge/svgr/issues/210)
* **v4:** new architecture ([ac8b8ca](https://github.com/gregberge/svgr/commit/ac8b8ca))
### BREAKING CHANGES
* **v4:** - `template` option must now returns a Babel AST
- `@svgr/core` does not include svgo & prettier by default
Copyright 2017 Smooth Code
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# @svgr/plugin-svgo
[![Build Status](https://img.shields.io/travis/smooth-code/svgr.svg)](https://travis-ci.org/smooth-code/svgr)
[![Version](https://img.shields.io/npm/v/@svgr/plugin-svgo.svg)](https://www.npmjs.com/package/@svgr/plugin-svgo)
[![MIT License](https://img.shields.io/npm/l/@svgr/plugin-svgo.svg)](https://github.com/smooth-code/svgr/blob/master/LICENSE)
Optimize SVG using SVGO.
## Install
```
npm install --save-dev @svgr/plugin-svgo
```
## Usage
**.svgrrc**
```json
{
"plugins": ["@svgr/plugin-svgo"]
}
```
## License
MIT
"use strict";
exports.__esModule = true;
exports.getFilePath = getFilePath;
exports.getBaseSvgoConfig = getBaseSvgoConfig;
exports.getPlugins = getPlugins;
exports.mergeSvgoConfig = mergeSvgoConfig;
var _deepmerge = _interopRequireDefault(require("deepmerge"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function getFilePath(state) {
return state.filePath || process.cwd();
}
function getBaseSvgoConfig(config) {
const baseSvgoConfig = {
plugins: [{
prefixIds: true
}]
};
if (config.icon || config.dimensions === false) {
baseSvgoConfig.plugins.push({
removeViewBox: false
});
}
return baseSvgoConfig;
}
function getPlugins(config) {
if (!config || !config.plugins) {
return [];
}
if (!Array.isArray(config.plugins)) {
throw Error('`svgoConfig.plugins` must be an array');
}
return config.plugins;
}
function extractPlugins(config) {
if (!config) return [];
if (!config.plugins) return [];
if (!Array.isArray(config.plugins)) return [config.plugins];
return config.plugins;
}
function mergePlugins(configs) {
const plugins = configs.reduce((merged, config) => _deepmerge.default.all([merged, ...extractPlugins(config)]), {});
return Object.keys(plugins).reduce((array, key) => {
array.push({
[key]: plugins[key]
});
return array;
}, []);
}
function mergeSvgoConfig(...configs) {
const plugins = mergePlugins(configs);
return { ..._deepmerge.default.all(configs.filter(Boolean)),
plugins
};
}
\ No newline at end of file
"use strict";
exports.__esModule = true;
exports.default = svgoPlugin;
var _svgo = _interopRequireDefault(require("svgo"));
var _cosmiconfig = require("cosmiconfig");
var _config = require("./config");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable no-underscore-dangle */
const explorer = (0, _cosmiconfig.cosmiconfigSync)('svgo', {
searchPlaces: ['package.json', '.svgorc', '.svgorc.js', '.svgorc.json', '.svgorc.yaml', '.svgorc.yml', 'svgo.config.js', '.svgo.yml'],
transform: result => result && result.config,
cache: true
});
function encodeSVGDatauri(str, type) {
let prefix = 'data:image/svg+xml'; // base64
if (!type || type === 'base64') {
prefix += ';base64,';
if (Buffer.from) {
str = prefix + Buffer.from(str).toString('base64');
} else {
// eslint-disable-next-line
str = prefix + new Buffer(str).toString('base64');
} // URI encoded
} else if (type === 'enc') {
str = `${prefix},${encodeURIComponent(str)}`; // unencoded
} else if (type === 'unenc') {
str = `${prefix},${str}`;
}
return str;
} // See https://github.com/svg/svgo/blob/master/lib/svgo.js#L24
// _optimizeOnce is synchronous internally
function optimizeSync(svgstr, info) {
const {
config
} = this;
if (config.error) {
throw config.error;
}
const maxPassCount = config.multipass ? 10 : 1;
let counter = 0;
let prevResultSize = Number.POSITIVE_INFINITY;
let result;
const optimizeOnceCallback = svgjs => {
if (svgjs.error) {
throw svgjs.error;
} // eslint-disable-next-line no-plusplus
if (++counter < maxPassCount && svgjs.data.length < prevResultSize) {
prevResultSize = svgjs.data.length;
this._optimizeOnce(svgjs.data, info, optimizeOnceCallback);
} else {
if (config.datauri) {
svgjs.data = encodeSVGDatauri(svgjs.data, config.datauri);
}
if (info.path) {
svgjs.path = info.path;
}
result = svgjs;
}
};
this._optimizeOnce(svgstr, info, optimizeOnceCallback);
return result;
}
function createSvgo(config, rcConfig) {
const baseSvgoConfig = (0, _config.getBaseSvgoConfig)(config);
const mergedConfig = (0, _config.mergeSvgoConfig)(baseSvgoConfig, rcConfig, config.svgoConfig);
return new _svgo.default(mergedConfig);
}
function getInfo(state) {
return state.filePath ? {
input: 'file',
path: state.filePath
} : {
input: 'string'
};
}
function svgoPlugin(code, config, state) {
if (!config.svgo) return code;
const filePath = (0, _config.getFilePath)(state);
const svgoRcConfig = config.runtimeConfig ? explorer.search(filePath) : {};
const svgo = createSvgo(config, svgoRcConfig);
const {
data
} = optimizeSync.call(svgo, code, getInfo(state));
return data;
}
\ No newline at end of file
{
"_from": "@svgr/plugin-svgo@^5.4.0",
"_id": "@svgr/plugin-svgo@5.5.0",
"_inBundle": false,
"_integrity": "sha512-r5swKk46GuQl4RrVejVwpeeJaydoxkdwkM1mBKOgJLBUJPGaLci6ylg/IjhrRsREKDkr4kbMWdgOtbXEh0fyLQ==",
"_location": "/@svgr/plugin-svgo",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@svgr/plugin-svgo@^5.4.0",
"name": "@svgr/plugin-svgo",
"escapedName": "@svgr%2fplugin-svgo",
"scope": "@svgr",
"rawSpec": "^5.4.0",
"saveSpec": null,
"fetchSpec": "^5.4.0"
},
"_requiredBy": [
"/@svgr/webpack"
],
"_resolved": "https://registry.npmjs.org/@svgr/plugin-svgo/-/plugin-svgo-5.5.0.tgz",
"_shasum": "02da55d85320549324e201c7b2e53bf431fcc246",
"_spec": "@svgr/plugin-svgo@^5.4.0",
"_where": "C:\\Users\\kkwan_000\\Desktop\\git\\2017110269\\minsung\\node_modules\\@svgr\\webpack",
"author": {
"name": "Greg Bergé",
"email": "berge.greg@gmail.com"
},
"bundleDependencies": false,
"dependencies": {
"cosmiconfig": "^7.0.0",
"deepmerge": "^4.2.2",
"svgo": "^1.2.2"
},
"deprecated": false,
"description": "Optimize SVG",
"engines": {
"node": ">=10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/gregberge"
},
"gitHead": "b5920550bd966f876cb65c5e23af180461e5aa23",
"homepage": "https://react-svgr.com",
"keywords": [
"svgr-plugin"
],
"license": "MIT",
"main": "lib/index.js",
"name": "@svgr/plugin-svgo",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/gregberge/svgr/tree/master/packages/plugin-svgo"
},
"scripts": {
"build": "babel --config-file ../../babel.config.js -d lib --ignore \"**/*.test.js\" src",
"prebuild": "rm -rf lib/",
"prepublishOnly": "yarn run build"
},
"version": "5.5.0"
}
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
# [5.4.0](https://github.com/gregberge/svgr/tree/master/packages/webpack/compare/v5.3.1...v5.4.0) (2020-04-27)
**Note:** Version bump only for package @svgr/webpack
## [5.3.1](https://github.com/gregberge/svgr/tree/master/packages/webpack/compare/v5.3.0...v5.3.1) (2020-04-05)
**Note:** Version bump only for package @svgr/webpack
# [5.3.0](https://github.com/gregberge/svgr/tree/master/packages/webpack/compare/v5.2.0...v5.3.0) (2020-03-22)
**Note:** Version bump only for package @svgr/webpack
# [5.2.0](https://github.com/gregberge/svgr/tree/master/packages/webpack/compare/v5.1.0...v5.2.0) (2020-02-23)
**Note:** Version bump only for package @svgr/webpack
# [5.1.0](https://github.com/gregberge/svgr/tree/master/packages/webpack/compare/v5.0.1...v5.1.0) (2020-01-20)
**Note:** Version bump only for package @svgr/webpack
## [5.0.1](https://github.com/gregberge/svgr/tree/master/packages/webpack/compare/v5.0.0...v5.0.1) (2019-12-29)
### Bug Fixes
* fix engines in package.json ([a45d6fc](https://github.com/gregberge/svgr/tree/master/packages/webpack/commit/a45d6fc8b43402bec60ed4e9273f90fdc65a23a7))
## [4.3.3](https://github.com/gregberge/svgr/tree/master/packages/webpack/compare/v4.3.2...v4.3.3) (2019-09-24)
**Note:** Version bump only for package @svgr/webpack
## [4.3.2](https://github.com/gregberge/svgr/tree/master/packages/webpack/compare/v4.3.1...v4.3.2) (2019-07-15)
**Note:** Version bump only for package @svgr/webpack
## [4.3.1](https://github.com/gregberge/svgr/tree/master/packages/webpack/compare/v4.3.0...v4.3.1) (2019-07-01)
**Note:** Version bump only for package @svgr/webpack
# [4.3.0](https://github.com/gregberge/svgr/tree/master/packages/webpack/compare/v4.2.0...v4.3.0) (2019-05-28)
**Note:** Version bump only for package @svgr/webpack
# [4.2.0](https://github.com/gregberge/svgr/tree/master/packages/webpack/compare/v4.1.0...v4.2.0) (2019-04-11)
**Note:** Version bump only for package @svgr/webpack
# [4.1.0](https://github.com/gregberge/svgr/compare/v4.0.4...v4.1.0) (2018-11-24)
### Features
* add parcel plugin ([#235](https://github.com/gregberge/svgr/issues/235)) ([144dbe3](https://github.com/gregberge/svgr/commit/144dbe3)), closes [#215](https://github.com/gregberge/svgr/issues/215)
## [4.0.4](https://github.com/gregberge/svgr/compare/v4.0.3...v4.0.4) (2018-11-24)
### Bug Fixes
* **webpack:** use static babel config ([#240](https://github.com/gregberge/svgr/issues/240)) ([d67af31](https://github.com/gregberge/svgr/commit/d67af31)), closes [#232](https://github.com/gregberge/svgr/issues/232)
## [4.0.3](https://github.com/gregberge/svgr/compare/v4.0.2...v4.0.3) (2018-11-13)
### Bug Fixes
* upgrade dependencies ([7e2195f](https://github.com/gregberge/svgr/commit/7e2195f))
## [4.0.2](https://github.com/gregberge/svgr/compare/v4.0.1...v4.0.2) (2018-11-08)
**Note:** Version bump only for package @svgr/webpack
## [4.0.1](https://github.com/gregberge/svgr/compare/v4.0.0...v4.0.1) (2018-11-08)
**Note:** Version bump only for package @svgr/webpack
# [4.0.0](https://github.com/gregberge/svgr/compare/v3.1.0...v4.0.0) (2018-11-04)
### Bug Fixes
* prevent babel read babel.config.js ([#206](https://github.com/gregberge/svgr/issues/206)) ([514d43d](https://github.com/gregberge/svgr/commit/514d43d))
### Features
* **svgo:** prefix ids by default ([06c338d](https://github.com/gregberge/svgr/commit/06c338d)), closes [#210](https://github.com/gregberge/svgr/issues/210)
* **v4:** new architecture ([ac8b8ca](https://github.com/gregberge/svgr/commit/ac8b8ca))
### BREAKING CHANGES
* **v4:** - `template` option must now returns a Babel AST
- `@svgr/core` does not include svgo & prettier by default
# [3.1.0](https://github.com/gregberge/svgr/compare/v3.0.0...v3.1.0) (2018-10-05)
**Note:** Version bump only for package @svgr/webpack
<a name="3.0.0"></a>
# [3.0.0](https://github.com/gregberge/svgr/compare/v2.4.1...v3.0.0) (2018-10-01)
### Bug Fixes
* **webpack:** forward filePath in webpack loader ([b7a108e](https://github.com/gregberge/svgr/commit/b7a108e)), closes [#177](https://github.com/gregberge/svgr/issues/177) [#188](https://github.com/gregberge/svgr/issues/188)
### Features
* always prefix component name with "Svg" ([f71aa7a](https://github.com/gregberge/svgr/commit/f71aa7a)), closes [#190](https://github.com/gregberge/svgr/issues/190)
### BREAKING CHANGES
* **webpack:** runtime configuration is now loaded using webpack
loader.
<a name="2.4.1"></a>
## [2.4.1](https://github.com/gregberge/svgr/compare/v2.4.0...v2.4.1) (2018-09-16)
**Note:** Version bump only for package @svgr/webpack
<a name="2.4.0"></a>
# [2.4.0](https://github.com/gregberge/svgr/compare/v2.3.0...v2.4.0) (2018-09-16)
### Features
* **upgrade:** h2x@1.1.0 (jsdom@12.0.0) & others ([2d9b7bd](https://github.com/gregberge/svgr/commit/2d9b7bd))
<a name="2.3.0"></a>
# [2.3.0](https://github.com/gregberge/svgr/compare/v2.2.1...v2.3.0) (2018-09-03)
### Features
* upgrade to Babel v7 ([7bc908d](https://github.com/gregberge/svgr/commit/7bc908d))
<a name="2.2.1"></a>
## [2.2.1](https://github.com/gregberge/svgr/compare/v2.2.0...v2.2.1) (2018-08-16)
**Note:** Version bump only for package @svgr/webpack
<a name="2.2.0"></a>
# [2.2.0](https://github.com/gregberge/svgr/compare/v2.1.1...v2.2.0) (2018-08-13)
### Bug Fixes
* **webpack:** use source when possible ([#139](https://github.com/gregberge/svgr/issues/139)) ([ae9965d](https://github.com/gregberge/svgr/commit/ae9965d))
<a name="2.1.1"></a>
## [2.1.1](https://github.com/gregberge/svgr/compare/v2.1.0...v2.1.1) (2018-07-11)
**Note:** Version bump only for package @svgr/webpack
<a name="2.1.0"></a>
# [2.1.0](https://github.com/gregberge/svgr/compare/v2.0.0...v2.1.0) (2018-07-08)
**Note:** Version bump only for package @svgr/webpack
Copyright 2017 Smooth Code
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# @svgr/webpack
[![Build Status](https://img.shields.io/travis/gregberge/svgr.svg)](https://travis-ci.org/gregberge/svgr)
[![Version](https://img.shields.io/npm/v/@svgr/webpack.svg)](https://www.npmjs.com/package/@svgr/webpack)
[![MIT License](https://img.shields.io/npm/l/@svgr/webpack.svg)](https://github.com/gregberge/svgr/blob/master/LICENSE)
Webpack loader for SVGR.
```
npm install @svgr/webpack --save-dev
```
## Usage
In your `webpack.config.js`:
```js
{
test: /\.svg$/,
use: ['@svgr/webpack'],
}
```
In your code:
```js
import Star from './star.svg'
const App = () => (
<div>
<Star />
</div>
)
```
### Passing options
```js
{
test: /\.svg$/,
use: [
{
loader: '@svgr/webpack',
options: {
native: true,
},
},
],
}
```
### Using with `url-loader` or `file-loader`
It is possible to use it with [`url-loader`](https://github.com/webpack-contrib/url-loader) or [`file-loader`](https://github.com/webpack-contrib/file-loader).
In your `webpack.config.js`:
```js
{
test: /\.svg$/,
use: ['@svgr/webpack', 'url-loader'],
}
```
In your code:
```js
import starUrl, { ReactComponent as Star } from './star.svg'
const App = () => (
<div>
<img src={starUrl} alt="star" />
<Star />
</div>
)
```
### Use your own Babel configuration
By default, `@svgr/webpack` includes a `babel-loader` with [an optimized configuration](https://github.com/gregberge/svgr/blob/master/packages/webpack/src/index.js). In some case you may want to apply a custom one (if you are using Preact for an example). You can turn off Babel transformation by specifying `babel: false` in options.
```js
// Example using preact
{
test: /\.svg$/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['preact', 'env'],
},
},
{
loader: '@svgr/webpack',
options: { babel: false },
}
],
}
```
### Handle SVG in CSS, Sass or Less
It is possible to detect the module that requires your SVG using [`Rule.issuer`](https://webpack.js.org/configuration/module/#rule-issuer) in Webpack. Using it you can specify two different configurations for JavaScript and the rest of your files.
```js
{
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
issuer: {
test: /\.jsx?$/
},
use: ['babel-loader', '@svgr/webpack', 'url-loader']
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader'
},
}
```
## License
MIT
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _loaderUtils = require("loader-utils");
var _core = require("@babel/core");
var _core2 = _interopRequireDefault(require("@svgr/core"));
var _pluginSvgo = _interopRequireDefault(require("@svgr/plugin-svgo"));
var _pluginJsx = _interopRequireDefault(require("@svgr/plugin-jsx"));
var _presetReact = _interopRequireDefault(require("@babel/preset-react"));
var _presetEnv = _interopRequireDefault(require("@babel/preset-env"));
var _pluginTransformReactConstantElements = _interopRequireDefault(require("@babel/plugin-transform-react-constant-elements"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
const babelOptions = {
babelrc: false,
configFile: false,
presets: [(0, _core.createConfigItem)(_presetReact.default, {
type: 'preset'
}), (0, _core.createConfigItem)([_presetEnv.default, {
modules: false
}], {
type: 'preset'
})],
plugins: [(0, _core.createConfigItem)(_pluginTransformReactConstantElements.default)]
};
function svgrLoader(source) {
const callback = this.async();
const _ref = (0, _loaderUtils.getOptions)(this) || {},
{
babel = true
} = _ref,
options = _objectWithoutPropertiesLoose(_ref, ["babel"]);
const readSvg = () => new Promise((resolve, reject) => {
this.fs.readFile(this.resourcePath, (err, result) => {
if (err) reject(err);
resolve(result);
});
});
const previousExport = (() => {
if (source.toString('utf-8').startsWith('export ')) {
return source;
}
const exportMatches = source.toString('utf-8').match(/^module.exports\s*=\s*(.*)/);
return exportMatches ? `export default ${exportMatches[1]}` : null;
})();
const tranformSvg = svg => (0, _core2.default)(svg, options, {
caller: {
name: '@svgr/webpack',
previousExport,
defaultPlugins: [_pluginSvgo.default, _pluginJsx.default]
},
filePath: this.resourcePath
}).then(jsCode => {
if (!babel) return jsCode;
return (0, _core.transformAsync)(jsCode, babelOptions).then(({
code
}) => code);
}).then(result => callback(null, result)).catch(err => callback(err));
if (previousExport) {
readSvg().then(tranformSvg);
} else {
tranformSvg(source);
}
}
var _default = svgrLoader;
exports.default = _default;
\ No newline at end of file
{
"_from": "@svgr/webpack@5.4.0",
"_id": "@svgr/webpack@5.4.0",
"_inBundle": false,
"_integrity": "sha512-LjepnS/BSAvelnOnnzr6Gg0GcpLmnZ9ThGFK5WJtm1xOqdBE/1IACZU7MMdVzjyUkfFqGz87eRE4hFaSLiUwYg==",
"_location": "/@svgr/webpack",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "@svgr/webpack@5.4.0",
"name": "@svgr/webpack",
"escapedName": "@svgr%2fwebpack",
"scope": "@svgr",
"rawSpec": "5.4.0",
"saveSpec": null,
"fetchSpec": "5.4.0"
},
"_requiredBy": [
"/react-scripts"
],
"_resolved": "https://registry.npmjs.org/@svgr/webpack/-/webpack-5.4.0.tgz",
"_shasum": "b68bc86e29cf007292b96ced65f80971175632e0",
"_spec": "@svgr/webpack@5.4.0",
"_where": "C:\\Users\\kkwan_000\\Desktop\\git\\2017110269\\minsung\\node_modules\\react-scripts",
"author": {
"name": "Greg Bergé",
"email": "berge.greg@gmail.com"
},
"bundleDependencies": false,
"dependencies": {
"@babel/core": "^7.9.0",
"@babel/plugin-transform-react-constant-elements": "^7.9.0",
"@babel/preset-env": "^7.9.5",
"@babel/preset-react": "^7.9.4",
"@svgr/core": "^5.4.0",
"@svgr/plugin-jsx": "^5.4.0",
"@svgr/plugin-svgo": "^5.4.0",
"loader-utils": "^2.0.0"
},
"deprecated": false,
"description": "SVGR webpack loader.",
"devDependencies": {
"babel-loader": "^8.0.6",
"memory-fs": "^0.5.0",
"url-loader": "^4.1.0",
"webpack": "^4.43.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/gregberge"
},
"gitHead": "e9c9d2fbfbce7a6879c90cd8522101caf2406d42",
"homepage": "https://react-svgr.com",
"keywords": [
"svgr",
"svg",
"react",
"webpack",
"webpack-loader"
],
"license": "MIT",
"main": "lib/index.js",
"name": "@svgr/webpack",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/gregberge/svgr/tree/master/packages/webpack"
},
"scripts": {
"build": "babel --config-file ../../babel.config.js -d lib --ignore \"**/*.test.js\" src",
"prebuild": "rm -rf lib/",
"prepublishOnly": "yarn run build"
},
"version": "5.4.0"
}
# CHANGELOG
The changelog is automatically updated using
[semantic-release](https://github.com/semantic-release/semantic-release). You
can see it on the [releases page](../../releases).
The MIT License (MIT)
Copyright (c) 2017 Kent C. Dodds
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.runWithExpensiveErrorDiagnosticsDisabled = runWithExpensiveErrorDiagnosticsDisabled;
exports.configure = configure;
exports.getConfig = getConfig;
exports.DEFAULT_IGNORE_TAGS = void 0;
var _prettyDom = require("./pretty-dom");
// It would be cleaner for this to live inside './queries', but
// other parts of the code assume that all exports from
// './queries' are query functions.
let config = {
testIdAttribute: 'data-testid',
asyncUtilTimeout: 1000,
// this is to support React's async `act` function.
// forcing react-testing-library to wrap all async functions would've been
// a total nightmare (consider wrapping every findBy* query and then also
// updating `within` so those would be wrapped too. Total nightmare).
// so we have this config option that's really only intended for
// react-testing-library to use. For that reason, this feature will remain
// undocumented.
asyncWrapper: cb => cb(),
eventWrapper: cb => cb(),
// default value for the `hidden` option in `ByRole` queries
defaultHidden: false,
// showOriginalStackTrace flag to show the full error stack traces for async errors
showOriginalStackTrace: false,
// throw errors w/ suggestions for better queries. Opt in so off by default.
throwSuggestions: false,
// called when getBy* queries fail. (message, container) => Error
getElementError(message, container) {
const error = new Error([message, (0, _prettyDom.prettyDOM)(container)].filter(Boolean).join('\n\n'));
error.name = 'TestingLibraryElementError';
return error;
},
_disableExpensiveErrorDiagnostics: false,
computedStyleSupportsPseudoElements: false
};
const DEFAULT_IGNORE_TAGS = 'script, style';
exports.DEFAULT_IGNORE_TAGS = DEFAULT_IGNORE_TAGS;
function runWithExpensiveErrorDiagnosticsDisabled(callback) {
try {
config._disableExpensiveErrorDiagnostics = true;
return callback();
} finally {
config._disableExpensiveErrorDiagnostics = false;
}
}
function configure(newConfig) {
if (typeof newConfig === 'function') {
// Pass the existing config out to the provided function
// and accept a delta in return
newConfig = newConfig(config);
} // Merge the incoming config delta
config = { ...config,
...newConfig
};
}
function getConfig() {
return config;
}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.fireEvent = fireEvent;
exports.createEvent = createEvent;
var _config = require("./config");
var _helpers = require("./helpers");
var _eventMap = require("./event-map");
function fireEvent(element, event) {
return (0, _config.getConfig)().eventWrapper(() => {
if (!event) {
throw new Error(`Unable to fire an event - please provide an event object.`);
}
if (!element) {
throw new Error(`Unable to fire a "${event.type}" event - please provide a DOM element.`);
}
return element.dispatchEvent(event);
});
}
function createEvent(eventName, node, init, {
EventType = 'Event',
defaultInit = {}
} = {}) {
if (!node) {
throw new Error(`Unable to fire a "${eventName}" event - please provide a DOM element.`);
}
const eventInit = { ...defaultInit,
...init
};
const {
target: {
value,
files,
...targetProperties
} = {}
} = eventInit;
if (value !== undefined) {
setNativeValue(node, value);
}
if (files !== undefined) {
// input.files is a read-only property so this is not allowed:
// input.files = [file]
// so we have to use this workaround to set the property
Object.defineProperty(node, 'files', {
configurable: true,
enumerable: true,
writable: true,
value: files
});
}
Object.assign(node, targetProperties);
const window = (0, _helpers.getWindowFromNode)(node);
const EventConstructor = window[EventType] || window.Event;
let event;
/* istanbul ignore else */
if (typeof EventConstructor === 'function') {
event = new EventConstructor(eventName, eventInit);
} else {
// IE11 polyfill from https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent#Polyfill
event = window.document.createEvent(EventType);
const {
bubbles,
cancelable,
detail,
...otherInit
} = eventInit;
event.initEvent(eventName, bubbles, cancelable, detail);
Object.keys(otherInit).forEach(eventKey => {
event[eventKey] = otherInit[eventKey];
});
} // DataTransfer is not supported in jsdom: https://github.com/jsdom/jsdom/issues/1568
['dataTransfer', 'clipboardData'].forEach(dataTransferKey => {
const dataTransferValue = eventInit[dataTransferKey];
if (typeof dataTransferValue === 'object') {
/* istanbul ignore if */
if (typeof window.DataTransfer === 'function') {
Object.defineProperty(event, dataTransferKey, {
value: Object.getOwnPropertyNames(dataTransferValue).reduce((acc, propName) => {
Object.defineProperty(acc, propName, {
value: dataTransferValue[propName]
});
return acc;
}, new window.DataTransfer())
});
} else {
Object.defineProperty(event, dataTransferKey, {
value: dataTransferValue
});
}
}
});
return event;
}
Object.keys(_eventMap.eventMap).forEach(key => {
const {
EventType,
defaultInit
} = _eventMap.eventMap[key];
const eventName = key.toLowerCase();
createEvent[key] = (node, init) => createEvent(eventName, node, init, {
EventType,
defaultInit
});
fireEvent[key] = (node, init) => fireEvent(node, createEvent[key](node, init));
}); // function written after some investigation here:
// https://github.com/facebook/react/issues/10135#issuecomment-401496776
function setNativeValue(element, value) {
const {
set: valueSetter
} = Object.getOwnPropertyDescriptor(element, 'value') || {};
const prototype = Object.getPrototypeOf(element);
const {
set: prototypeValueSetter
} = Object.getOwnPropertyDescriptor(prototype, 'value') || {};
if (prototypeValueSetter && valueSetter !== prototypeValueSetter) {
prototypeValueSetter.call(element, value);
}
/* istanbul ignore next (I don't want to bother) */
else if (valueSetter) {
valueSetter.call(element, value);
} else {
throw new Error('The given element does not have a value setter');
}
}
Object.keys(_eventMap.eventAliasMap).forEach(aliasKey => {
const key = _eventMap.eventAliasMap[aliasKey];
fireEvent[aliasKey] = (...args) => fireEvent[key](...args);
});
/* eslint complexity:["error", 9] */
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getNodeText = getNodeText;
var _helpers = require("./helpers");
function getNodeText(node) {
if (node.matches('input[type=submit], input[type=button]')) {
return node.value;
}
return Array.from(node.childNodes).filter(child => child.nodeType === _helpers.TEXT_NODE && Boolean(child.textContent)).map(c => c.textContent).join('');
}
\ No newline at end of file
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getQueriesForElement = getQueriesForElement;
var defaultQueries = _interopRequireWildcard(require("./queries"));
/**
* @typedef {{[key: string]: Function}} FuncMap
*/
/**
* @param {HTMLElement} element container
* @param {FuncMap} queries object of functions
* @param {Object} initialValue for reducer
* @returns {FuncMap} returns object of functions bound to container
*/
function getQueriesForElement(element, queries = defaultQueries, initialValue = {}) {
return Object.keys(queries).reduce((helpers, key) => {
const fn = queries[key];
helpers[key] = fn.bind(null, element);
return helpers;
}, initialValue);
}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getUserCodeFrame = getUserCodeFrame;
// We try to load node dependencies
let chalk = null;
let readFileSync = null;
let codeFrameColumns = null;
try {
const nodeRequire = module && module.require;
readFileSync = nodeRequire.call(module, 'fs').readFileSync;
codeFrameColumns = nodeRequire.call(module, '@babel/code-frame').codeFrameColumns;
chalk = nodeRequire.call(module, 'chalk');
} catch {// We're in a browser environment
} // frame has the form "at myMethod (location/to/my/file.js:10:2)"
function getCodeFrame(frame) {
const locationStart = frame.indexOf('(') + 1;
const locationEnd = frame.indexOf(')');
const frameLocation = frame.slice(locationStart, locationEnd);
const frameLocationElements = frameLocation.split(':');
const [filename, line, column] = [frameLocationElements[0], parseInt(frameLocationElements[1], 10), parseInt(frameLocationElements[2], 10)];
let rawFileContents = '';
try {
rawFileContents = readFileSync(filename, 'utf-8');
} catch {
return '';
}
const codeFrame = codeFrameColumns(rawFileContents, {
start: {
line,
column
}
}, {
highlightCode: true,
linesBelow: 0
});
return `${chalk.dim(frameLocation)}\n${codeFrame}\n`;
}
function getUserCodeFrame() {
// If we couldn't load dependencies, we can't generate the user trace
/* istanbul ignore next */
if (!readFileSync || !codeFrameColumns) {
return '';
}
const err = new Error();
const firstClientCodeFrame = err.stack.split('\n').slice(1) // Remove first line which has the form "Error: TypeError"
.find(frame => !frame.includes('node_modules/')); // Ignore frames from 3rd party libraries
return getCodeFrame(firstClientCodeFrame);
}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getWindowFromNode = getWindowFromNode;
exports.getDocument = getDocument;
exports.runWithRealTimers = runWithRealTimers;
exports.checkContainerType = checkContainerType;
exports.TEXT_NODE = exports.jestFakeTimersAreEnabled = exports.setTimeout = exports.setImmediate = exports.clearTimeout = void 0;
const globalObj = typeof window === 'undefined' ? global : window; // Constant node.nodeType for text nodes, see:
// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType#Node_type_constants
const TEXT_NODE = 3; // Currently this fn only supports jest timers, but it could support other test runners in the future.
exports.TEXT_NODE = TEXT_NODE;
function runWithRealTimers(callback) {
const fakeTimersType = getJestFakeTimersType();
if (fakeTimersType) {
jest.useRealTimers();
}
const callbackReturnValue = callback();
if (fakeTimersType) {
jest.useFakeTimers(fakeTimersType);
}
return callbackReturnValue;
}
function getJestFakeTimersType() {
// istanbul ignore if
if (typeof jest === 'undefined' || typeof globalObj.setTimeout === 'undefined') {
return null;
}
if (typeof globalObj.setTimeout._isMockFunction !== 'undefined' && globalObj.setTimeout._isMockFunction) {
return 'legacy';
}
if (typeof globalObj.setTimeout.clock !== 'undefined' && typeof jest.getRealSystemTime !== 'undefined') {
try {
// jest.getRealSystemTime is only supported for Jest's `modern` fake timers and otherwise throws
jest.getRealSystemTime();
return 'modern';
} catch {// not using Jest's modern fake timers
}
}
return null;
}
const jestFakeTimersAreEnabled = () => Boolean(getJestFakeTimersType()); // we only run our tests in node, and setImmediate is supported in node.
// istanbul ignore next
exports.jestFakeTimersAreEnabled = jestFakeTimersAreEnabled;
function setImmediatePolyfill(fn) {
return globalObj.setTimeout(fn, 0);
}
function getTimeFunctions() {
// istanbul ignore next
return {
clearTimeoutFn: globalObj.clearTimeout,
setImmediateFn: globalObj.setImmediate || setImmediatePolyfill,
setTimeoutFn: globalObj.setTimeout
};
}
const {
clearTimeoutFn,
setImmediateFn,
setTimeoutFn
} = runWithRealTimers(getTimeFunctions);
exports.setTimeout = setTimeoutFn;
exports.setImmediate = setImmediateFn;
exports.clearTimeout = clearTimeoutFn;
function getDocument() {
/* istanbul ignore if */
if (typeof window === 'undefined') {
throw new Error('Could not find default container');
}
return window.document;
}
function getWindowFromNode(node) {
if (node.defaultView) {
// node is document
return node.defaultView;
} else if (node.ownerDocument && node.ownerDocument.defaultView) {
// node is a DOM node
return node.ownerDocument.defaultView;
} else if (node.window) {
// node is window
return node.window;
} else if (node.then instanceof Function) {
throw new Error(`It looks like you passed a Promise object instead of a DOM node. Did you do something like \`fireEvent.click(screen.findBy...\` when you meant to use a \`getBy\` query \`fireEvent.click(screen.getBy...\`, or await the findBy query \`fireEvent.click(await screen.findBy...\`?`);
} else {
// The user passed something unusual to a calling function
throw new Error(`Unable to find the "window" object for the given node. Please file an issue with the code that's causing you to see this error: https://github.com/testing-library/dom-testing-library/issues/new`);
}
}
function checkContainerType(container) {
if (!container || !(typeof container.querySelector === 'function') || !(typeof container.querySelectorAll === 'function')) {
throw new TypeError(`Expected container to be an Element, a Document or a DocumentFragment but got ${getTypeName(container)}.`);
}
function getTypeName(object) {
if (typeof object === 'object') {
return object === null ? 'null' : object.constructor.name;
}
return typeof object;
}
}
\ No newline at end of file
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
Object.defineProperty(exports, "__esModule", {
value: true
});
var _exportNames = {
within: true,
queries: true,
queryHelpers: true,
getDefaultNormalizer: true,
getRoles: true,
logRoles: true,
isInaccessible: true,
configure: true,
getConfig: true
};
Object.defineProperty(exports, "within", {
enumerable: true,
get: function () {
return _getQueriesForElement.getQueriesForElement;
}
});
Object.defineProperty(exports, "getDefaultNormalizer", {
enumerable: true,
get: function () {
return _matches.getDefaultNormalizer;
}
});
Object.defineProperty(exports, "getRoles", {
enumerable: true,
get: function () {
return _roleHelpers.getRoles;
}
});
Object.defineProperty(exports, "logRoles", {
enumerable: true,
get: function () {
return _roleHelpers.logRoles;
}
});
Object.defineProperty(exports, "isInaccessible", {
enumerable: true,
get: function () {
return _roleHelpers.isInaccessible;
}
});
Object.defineProperty(exports, "configure", {
enumerable: true,
get: function () {
return _config.configure;
}
});
Object.defineProperty(exports, "getConfig", {
enumerable: true,
get: function () {
return _config.getConfig;
}
});
exports.queryHelpers = exports.queries = void 0;
var _getQueriesForElement = require("./get-queries-for-element");
Object.keys(_getQueriesForElement).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _getQueriesForElement[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _getQueriesForElement[key];
}
});
});
var queries = _interopRequireWildcard(require("./queries"));
exports.queries = queries;
Object.keys(queries).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === queries[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return queries[key];
}
});
});
var queryHelpers = _interopRequireWildcard(require("./query-helpers"));
exports.queryHelpers = queryHelpers;
Object.keys(queryHelpers).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === queryHelpers[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return queryHelpers[key];
}
});
});
var _waitFor = require("./wait-for");
Object.keys(_waitFor).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _waitFor[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _waitFor[key];
}
});
});
var _waitForElement = require("./wait-for-element");
Object.keys(_waitForElement).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _waitForElement[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _waitForElement[key];
}
});
});
var _waitForElementToBeRemoved = require("./wait-for-element-to-be-removed");
Object.keys(_waitForElementToBeRemoved).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _waitForElementToBeRemoved[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _waitForElementToBeRemoved[key];
}
});
});
var _waitForDomChange = require("./wait-for-dom-change");
Object.keys(_waitForDomChange).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _waitForDomChange[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _waitForDomChange[key];
}
});
});
var _matches = require("./matches");
var _getNodeText = require("./get-node-text");
Object.keys(_getNodeText).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _getNodeText[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _getNodeText[key];
}
});
});
var _events = require("./events");
Object.keys(_events).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _events[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _events[key];
}
});
});
var _screen = require("./screen");
Object.keys(_screen).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _screen[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _screen[key];
}
});
});
var _roleHelpers = require("./role-helpers");
var _prettyDom = require("./pretty-dom");
Object.keys(_prettyDom).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _prettyDom[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _prettyDom[key];
}
});
});
var _config = require("./config");
var _suggestions = require("./suggestions");
Object.keys(_suggestions).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _suggestions[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _suggestions[key];
}
});
});
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getLabels = getLabels;
exports.getRealLabels = getRealLabels;
exports.getLabelContent = getLabelContent;
var _helpers = require("./helpers");
const labelledNodeNames = ['button', 'meter', 'output', 'progress', 'select', 'textarea', 'input'];
function getTextContent(node) {
if (labelledNodeNames.includes(node.nodeName.toLowerCase())) {
return '';
}
if (node.nodeType === _helpers.TEXT_NODE) return node.textContent;
return Array.from(node.childNodes).map(childNode => getTextContent(childNode)).join('');
}
function getLabelContent(element) {
let textContent;
if (element.tagName.toLowerCase() === 'label') {
textContent = getTextContent(element);
} else {
textContent = element.value || element.textContent;
}
return textContent;
} // Based on https://github.com/eps1lon/dom-accessibility-api/pull/352
function getRealLabels(element) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- types are not aware of older browsers that don't implement `labels`
if (element.labels !== undefined) {
var _labels;
return (_labels = element.labels) != null ? _labels : [];
}
if (!isLabelable(element)) return [];
const labels = element.ownerDocument.querySelectorAll('label');
return Array.from(labels).filter(label => label.control === element);
}
function isLabelable(element) {
return /BUTTON|METER|OUTPUT|PROGRESS|SELECT|TEXTAREA/.test(element.tagName) || element.tagName === 'INPUT' && element.getAttribute('type') !== 'hidden';
}
function getLabels(container, element, {
selector = '*'
} = {}) {
const ariaLabelledBy = element.getAttribute('aria-labelledby');
const labelsId = ariaLabelledBy ? ariaLabelledBy.split(' ') : [];
return labelsId.length ? labelsId.map(labelId => {
const labellingElement = container.querySelector(`[id="${labelId}"]`);
return labellingElement ? {
content: getLabelContent(labellingElement),
formControl: null
} : {
content: '',
formControl: null
};
}) : Array.from(getRealLabels(element)).map(label => {
const textToMatch = getLabelContent(label);
const labelledFormControl = Array.from(label.querySelectorAll('button, input, meter, output, progress, select, textarea')).filter(formControlElement => formControlElement.matches(selector))[0];
return {
content: textToMatch,
formControl: labelledFormControl
};
});
}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.fuzzyMatches = fuzzyMatches;
exports.matches = matches;
exports.getDefaultNormalizer = getDefaultNormalizer;
exports.makeNormalizer = makeNormalizer;
function assertNotNullOrUndefined(matcher) {
if (matcher === null || matcher === undefined) {
throw new Error( // eslint-disable-next-line @typescript-eslint/restrict-template-expressions -- implicitly converting `T` to `string`
`It looks like ${matcher} was passed instead of a matcher. Did you do something like getByText(${matcher})?`);
}
}
function fuzzyMatches(textToMatch, node, matcher, normalizer) {
if (typeof textToMatch !== 'string') {
return false;
}
assertNotNullOrUndefined(matcher);
const normalizedText = normalizer(textToMatch);
if (typeof matcher === 'string') {
return normalizedText.toLowerCase().includes(matcher.toLowerCase());
} else if (typeof matcher === 'function') {
return matcher(normalizedText, node);
} else {
return matcher.test(normalizedText);
}
}
function matches(textToMatch, node, matcher, normalizer) {
if (typeof textToMatch !== 'string') {
return false;
}
assertNotNullOrUndefined(matcher);
const normalizedText = normalizer(textToMatch);
if (matcher instanceof Function) {
return matcher(normalizedText, node);
} else if (matcher instanceof RegExp) {
return matcher.test(normalizedText);
} else {
return normalizedText === String(matcher);
}
}
function getDefaultNormalizer({
trim = true,
collapseWhitespace = true
} = {}) {
return text => {
let normalizedText = text;
normalizedText = trim ? normalizedText.trim() : normalizedText;
normalizedText = collapseWhitespace ? normalizedText.replace(/\s+/g, ' ') : normalizedText;
return normalizedText;
};
}
/**
* Constructs a normalizer to pass to functions in matches.js
* @param {boolean|undefined} trim The user-specified value for `trim`, without
* any defaulting having been applied
* @param {boolean|undefined} collapseWhitespace The user-specified value for
* `collapseWhitespace`, without any defaulting having been applied
* @param {Function|undefined} normalizer The user-specified normalizer
* @returns {Function} A normalizer
*/
function makeNormalizer({
trim,
collapseWhitespace,
normalizer
}) {
if (normalizer) {
// User has specified a custom normalizer
if (typeof trim !== 'undefined' || typeof collapseWhitespace !== 'undefined') {
// They've also specified a value for trim or collapseWhitespace
throw new Error('trim and collapseWhitespace are not supported with a normalizer. ' + 'If you want to use the default trim and collapseWhitespace logic in your normalizer, ' + 'use "getDefaultNormalizer({trim, collapseWhitespace})" and compose that into your normalizer');
}
return normalizer;
} else {
// No custom normalizer specified. Just use default.
return getDefaultNormalizer({
trim,
collapseWhitespace
});
}
}
\ No newline at end of file
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.prettyDOM = prettyDOM;
Object.defineProperty(exports, "prettyFormat", {
enumerable: true,
get: function () {
return _prettyFormat.default;
}
});
exports.logDOM = void 0;
var _prettyFormat = _interopRequireDefault(require("pretty-format"));
var _getUserCodeFrame = require("./get-user-code-frame");
var _helpers = require("./helpers");
function inCypress(dom) {
const window = dom.ownerDocument && dom.ownerDocument.defaultView || undefined;
return typeof global !== 'undefined' && global.Cypress || typeof window !== 'undefined' && window.Cypress;
}
const inNode = () => typeof process !== 'undefined' && process.versions !== undefined && process.versions.node !== undefined;
const getMaxLength = dom => inCypress(dom) ? 0 : typeof process !== 'undefined' && process.env.DEBUG_PRINT_LIMIT || 7000;
const {
DOMElement,
DOMCollection
} = _prettyFormat.default.plugins;
function prettyDOM(dom, maxLength, options) {
if (!dom) {
dom = (0, _helpers.getDocument)().body;
}
if (typeof maxLength !== 'number') {
maxLength = getMaxLength(dom);
}
if (maxLength === 0) {
return '';
}
if (dom.documentElement) {
dom = dom.documentElement;
}
let domTypeName = typeof dom;
if (domTypeName === 'object') {
domTypeName = dom.constructor.name;
} else {
// To don't fall with `in` operator
dom = {};
}
if (!('outerHTML' in dom)) {
throw new TypeError(`Expected an element or document but got ${domTypeName}`);
}
const debugContent = (0, _prettyFormat.default)(dom, {
plugins: [DOMElement, DOMCollection],
printFunctionName: false,
highlight: inNode(),
...options
});
return maxLength !== undefined && dom.outerHTML.length > maxLength ? `${debugContent.slice(0, maxLength)}...` : debugContent;
}
const logDOM = (...args) => {
const userCodeFrame = (0, _getUserCodeFrame.getUserCodeFrame)();
if (userCodeFrame) {
console.log(`${prettyDOM(...args)}\n\n${userCodeFrame}`);
} else {
console.log(prettyDOM(...args));
}
};
exports.logDOM = logDOM;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _matches = require("../matches");
Object.keys(_matches).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _matches[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _matches[key];
}
});
});
var _getNodeText = require("../get-node-text");
Object.keys(_getNodeText).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _getNodeText[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _getNodeText[key];
}
});
});
var _queryHelpers = require("../query-helpers");
Object.keys(_queryHelpers).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _queryHelpers[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _queryHelpers[key];
}
});
});
var _config = require("../config");
Object.keys(_config).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _config[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _config[key];
}
});
});
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.findByAltText = exports.findAllByAltText = exports.getAllByAltText = exports.getByAltText = exports.queryAllByAltText = exports.queryByAltText = void 0;
var _queryHelpers = require("../query-helpers");
var _helpers = require("../helpers");
var _allUtils = require("./all-utils");
function queryAllByAltText(container, alt, {
exact = true,
collapseWhitespace,
trim,
normalizer
} = {}) {
(0, _helpers.checkContainerType)(container);
const matcher = exact ? _allUtils.matches : _allUtils.fuzzyMatches;
const matchNormalizer = (0, _allUtils.makeNormalizer)({
collapseWhitespace,
trim,
normalizer
});
return Array.from(container.querySelectorAll('img,input,area')).filter(node => matcher(node.getAttribute('alt'), node, alt, matchNormalizer));
}
const getMultipleError = (c, alt) => `Found multiple elements with the alt text: ${alt}`;
const getMissingError = (c, alt) => `Unable to find an element with the alt text: ${alt}`;
const queryAllByAltTextWithSuggestions = (0, _queryHelpers.wrapAllByQueryWithSuggestion)(queryAllByAltText, queryAllByAltText.name, 'queryAll');
exports.queryAllByAltText = queryAllByAltTextWithSuggestions;
const [queryByAltText, getAllByAltText, getByAltText, findAllByAltText, findByAltText] = (0, _allUtils.buildQueries)(queryAllByAltText, getMultipleError, getMissingError);
exports.findByAltText = findByAltText;
exports.findAllByAltText = findAllByAltText;
exports.getByAltText = getByAltText;
exports.getAllByAltText = getAllByAltText;
exports.queryByAltText = queryByAltText;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.findByDisplayValue = exports.findAllByDisplayValue = exports.getAllByDisplayValue = exports.getByDisplayValue = exports.queryAllByDisplayValue = exports.queryByDisplayValue = void 0;
var _queryHelpers = require("../query-helpers");
var _helpers = require("../helpers");
var _allUtils = require("./all-utils");
function queryAllByDisplayValue(container, value, {
exact = true,
collapseWhitespace,
trim,
normalizer
} = {}) {
(0, _helpers.checkContainerType)(container);
const matcher = exact ? _allUtils.matches : _allUtils.fuzzyMatches;
const matchNormalizer = (0, _allUtils.makeNormalizer)({
collapseWhitespace,
trim,
normalizer
});
return Array.from(container.querySelectorAll(`input,textarea,select`)).filter(node => {
if (node.tagName === 'SELECT') {
const selectedOptions = Array.from(node.options).filter(option => option.selected);
return selectedOptions.some(optionNode => matcher((0, _allUtils.getNodeText)(optionNode), optionNode, value, matchNormalizer));
} else {
return matcher(node.value, node, value, matchNormalizer);
}
});
}
const getMultipleError = (c, value) => `Found multiple elements with the display value: ${value}.`;
const getMissingError = (c, value) => `Unable to find an element with the display value: ${value}.`;
const queryAllByDisplayValueWithSuggestions = (0, _queryHelpers.wrapAllByQueryWithSuggestion)(queryAllByDisplayValue, queryAllByDisplayValue.name, 'queryAll');
exports.queryAllByDisplayValue = queryAllByDisplayValueWithSuggestions;
const [queryByDisplayValue, getAllByDisplayValue, getByDisplayValue, findAllByDisplayValue, findByDisplayValue] = (0, _allUtils.buildQueries)(queryAllByDisplayValue, getMultipleError, getMissingError);
exports.findByDisplayValue = findByDisplayValue;
exports.findAllByDisplayValue = findAllByDisplayValue;
exports.getByDisplayValue = getByDisplayValue;
exports.getAllByDisplayValue = getAllByDisplayValue;
exports.queryByDisplayValue = queryByDisplayValue;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _labelText = require("./label-text");
Object.keys(_labelText).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _labelText[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _labelText[key];
}
});
});
var _placeholderText = require("./placeholder-text");
Object.keys(_placeholderText).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _placeholderText[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _placeholderText[key];
}
});
});
var _text = require("./text");
Object.keys(_text).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _text[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _text[key];
}
});
});
var _displayValue = require("./display-value");
Object.keys(_displayValue).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _displayValue[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _displayValue[key];
}
});
});
var _altText = require("./alt-text");
Object.keys(_altText).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _altText[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _altText[key];
}
});
});
var _title = require("./title");
Object.keys(_title).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _title[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _title[key];
}
});
});
var _role = require("./role");
Object.keys(_role).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _role[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _role[key];
}
});
});
var _testId = require("./test-id");
Object.keys(_testId).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _testId[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _testId[key];
}
});
});
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.findByLabelText = exports.findAllByLabelText = exports.getByLabelText = exports.getAllByLabelText = exports.queryByLabelText = exports.queryAllByLabelText = void 0;
var _config = require("../config");
var _helpers = require("../helpers");
var _labelHelpers = require("../label-helpers");
var _allUtils = require("./all-utils");
function queryAllLabels(container) {
return Array.from(container.querySelectorAll('label,input')).map(node => {
return {
node,
textToMatch: (0, _labelHelpers.getLabelContent)(node)
};
}).filter(({
textToMatch
}) => textToMatch !== null);
}
function queryAllLabelsByText(container, text, {
exact = true,
trim,
collapseWhitespace,
normalizer
} = {}) {
const matcher = exact ? _allUtils.matches : _allUtils.fuzzyMatches;
const matchNormalizer = (0, _allUtils.makeNormalizer)({
collapseWhitespace,
trim,
normalizer
});
const textToMatchByLabels = queryAllLabels(container);
return textToMatchByLabels.filter(({
node,
textToMatch
}) => matcher(textToMatch, node, text, matchNormalizer)).map(({
node
}) => node);
}
function queryAllByLabelText(container, text, {
selector = '*',
exact = true,
collapseWhitespace,
trim,
normalizer
} = {}) {
(0, _helpers.checkContainerType)(container);
const matcher = exact ? _allUtils.matches : _allUtils.fuzzyMatches;
const matchNormalizer = (0, _allUtils.makeNormalizer)({
collapseWhitespace,
trim,
normalizer
});
const matchingLabelledElements = Array.from(container.querySelectorAll('*')).filter(element => {
return (0, _labelHelpers.getRealLabels)(element).length || element.hasAttribute('aria-labelledby');
}).reduce((labelledElements, labelledElement) => {
const labelList = (0, _labelHelpers.getLabels)(container, labelledElement, {
selector
});
labelList.filter(label => Boolean(label.formControl)).forEach(label => {
if (matcher(label.content, label.formControl, text, matchNormalizer)) labelledElements.push(label.formControl);
});
const labelsValue = labelList.filter(label => Boolean(label.content)).map(label => label.content);
if (matcher(labelsValue.join(' '), labelledElement, text, matchNormalizer)) labelledElements.push(labelledElement);
if (labelsValue.length > 1) {
labelsValue.forEach((labelValue, index) => {
if (matcher(labelValue, labelledElement, text, matchNormalizer)) labelledElements.push(labelledElement);
const labelsFiltered = [...labelsValue];
labelsFiltered.splice(index, 1);
if (labelsFiltered.length > 1) {
if (matcher(labelsFiltered.join(' '), labelledElement, text, matchNormalizer)) labelledElements.push(labelledElement);
}
});
}
return labelledElements;
}, []).concat((0, _allUtils.queryAllByAttribute)('aria-label', container, text, {
exact
}));
return Array.from(new Set(matchingLabelledElements)).filter(element => element.matches(selector));
} // the getAll* query would normally look like this:
// const getAllByLabelText = makeGetAllQuery(
// queryAllByLabelText,
// (c, text) => `Unable to find a label with the text of: ${text}`,
// )
// however, we can give a more helpful error message than the generic one,
// so we're writing this one out by hand.
const getAllByLabelText = (container, text, ...rest) => {
const els = queryAllByLabelText(container, text, ...rest);
if (!els.length) {
const labels = queryAllLabelsByText(container, text, ...rest);
if (labels.length) {
const tagNames = labels.map(label => getTagNameOfElementAssociatedWithLabelViaFor(container, label)).filter(tagName => !!tagName);
if (tagNames.length) {
throw (0, _config.getConfig)().getElementError(tagNames.map(tagName => `Found a label with the text of: ${text}, however the element associated with this label (<${tagName} />) is non-labellable [https://html.spec.whatwg.org/multipage/forms.html#category-label]. If you really need to label a <${tagName} />, you can use aria-label or aria-labelledby instead.`).join('\n\n'), container);
} else {
throw (0, _config.getConfig)().getElementError(`Found a label with the text of: ${text}, however no form control was found associated to that label. Make sure you're using the "for" attribute or "aria-labelledby" attribute correctly.`, container);
}
} else {
throw (0, _config.getConfig)().getElementError(`Unable to find a label with the text of: ${text}`, container);
}
}
return els;
};
function getTagNameOfElementAssociatedWithLabelViaFor(container, label) {
const htmlFor = label.getAttribute('for');
if (!htmlFor) {
return null;
}
const element = container.querySelector(`[id="${htmlFor}"]`);
return element ? element.tagName.toLowerCase() : null;
} // the reason mentioned above is the same reason we're not using buildQueries
const getMultipleError = (c, text) => `Found multiple elements with the text of: ${text}`;
const queryByLabelText = (0, _allUtils.wrapSingleQueryWithSuggestion)((0, _allUtils.makeSingleQuery)(queryAllByLabelText, getMultipleError), queryAllByLabelText.name, 'query');
exports.queryByLabelText = queryByLabelText;
const getByLabelText = (0, _allUtils.makeSingleQuery)(getAllByLabelText, getMultipleError);
const findAllByLabelText = (0, _allUtils.makeFindQuery)((0, _allUtils.wrapAllByQueryWithSuggestion)(getAllByLabelText, getAllByLabelText.name, 'findAll'));
exports.findAllByLabelText = findAllByLabelText;
const findByLabelText = (0, _allUtils.makeFindQuery)((0, _allUtils.wrapSingleQueryWithSuggestion)(getByLabelText, getAllByLabelText.name, 'find'));
exports.findByLabelText = findByLabelText;
const getAllByLabelTextWithSuggestions = (0, _allUtils.wrapAllByQueryWithSuggestion)(getAllByLabelText, getAllByLabelText.name, 'getAll');
exports.getAllByLabelText = getAllByLabelTextWithSuggestions;
const getByLabelTextWithSuggestions = (0, _allUtils.wrapSingleQueryWithSuggestion)(getByLabelText, getAllByLabelText.name, 'get');
exports.getByLabelText = getByLabelTextWithSuggestions;
const queryAllByLabelTextWithSuggestions = (0, _allUtils.wrapAllByQueryWithSuggestion)(queryAllByLabelText, queryAllByLabelText.name, 'queryAll');
exports.queryAllByLabelText = queryAllByLabelTextWithSuggestions;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.findByPlaceholderText = exports.findAllByPlaceholderText = exports.getAllByPlaceholderText = exports.getByPlaceholderText = exports.queryAllByPlaceholderText = exports.queryByPlaceholderText = void 0;
var _queryHelpers = require("../query-helpers");
var _helpers = require("../helpers");
var _allUtils = require("./all-utils");
function queryAllByPlaceholderText(...args) {
(0, _helpers.checkContainerType)(...args);
return (0, _allUtils.queryAllByAttribute)('placeholder', ...args);
}
const getMultipleError = (c, text) => `Found multiple elements with the placeholder text of: ${text}`;
const getMissingError = (c, text) => `Unable to find an element with the placeholder text of: ${text}`;
const queryAllByPlaceholderTextWithSuggestions = (0, _queryHelpers.wrapAllByQueryWithSuggestion)(queryAllByPlaceholderText, queryAllByPlaceholderText.name, 'queryAll');
exports.queryAllByPlaceholderText = queryAllByPlaceholderTextWithSuggestions;
const [queryByPlaceholderText, getAllByPlaceholderText, getByPlaceholderText, findAllByPlaceholderText, findByPlaceholderText] = (0, _allUtils.buildQueries)(queryAllByPlaceholderText, getMultipleError, getMissingError);
exports.findByPlaceholderText = findByPlaceholderText;
exports.findAllByPlaceholderText = findAllByPlaceholderText;
exports.getByPlaceholderText = getByPlaceholderText;
exports.getAllByPlaceholderText = getAllByPlaceholderText;
exports.queryByPlaceholderText = queryByPlaceholderText;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.findByRole = exports.findAllByRole = exports.getByRole = exports.getAllByRole = exports.queryAllByRole = exports.queryByRole = void 0;
var _domAccessibilityApi = require("dom-accessibility-api");
var _ariaQuery = require("aria-query");
var _roleHelpers = require("../role-helpers");
var _queryHelpers = require("../query-helpers");
var _helpers = require("../helpers");
var _allUtils = require("./all-utils");
function queryAllByRole(container, role, {
exact = true,
collapseWhitespace,
hidden = (0, _allUtils.getConfig)().defaultHidden,
name,
trim,
normalizer,
queryFallbacks = false,
selected,
checked,
pressed,
level,
expanded
} = {}) {
(0, _helpers.checkContainerType)(container);
const matcher = exact ? _allUtils.matches : _allUtils.fuzzyMatches;
const matchNormalizer = (0, _allUtils.makeNormalizer)({
collapseWhitespace,
trim,
normalizer
});
if (selected !== undefined) {
var _allRoles$get;
// guard against unknown roles
if (((_allRoles$get = _ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get.props['aria-selected']) === undefined) {
throw new Error(`"aria-selected" is not supported on role "${role}".`);
}
}
if (checked !== undefined) {
var _allRoles$get2;
// guard against unknown roles
if (((_allRoles$get2 = _ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get2.props['aria-checked']) === undefined) {
throw new Error(`"aria-checked" is not supported on role "${role}".`);
}
}
if (pressed !== undefined) {
var _allRoles$get3;
// guard against unknown roles
if (((_allRoles$get3 = _ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get3.props['aria-pressed']) === undefined) {
throw new Error(`"aria-pressed" is not supported on role "${role}".`);
}
}
if (level !== undefined) {
// guard against using `level` option with any role other than `heading`
if (role !== 'heading') {
throw new Error(`Role "${role}" cannot have "level" property.`);
}
}
if (expanded !== undefined) {
var _allRoles$get4;
// guard against unknown roles
if (((_allRoles$get4 = _ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get4.props['aria-expanded']) === undefined) {
throw new Error(`"aria-expanded" is not supported on role "${role}".`);
}
}
const subtreeIsInaccessibleCache = new WeakMap();
function cachedIsSubtreeInaccessible(element) {
if (!subtreeIsInaccessibleCache.has(element)) {
subtreeIsInaccessibleCache.set(element, (0, _roleHelpers.isSubtreeInaccessible)(element));
}
return subtreeIsInaccessibleCache.get(element);
}
return Array.from(container.querySelectorAll('*')).filter(node => {
const isRoleSpecifiedExplicitly = node.hasAttribute('role');
if (isRoleSpecifiedExplicitly) {
const roleValue = node.getAttribute('role');
if (queryFallbacks) {
return roleValue.split(' ').filter(Boolean).some(text => matcher(text, node, role, matchNormalizer));
} // if a custom normalizer is passed then let normalizer handle the role value
if (normalizer) {
return matcher(roleValue, node, role, matchNormalizer);
} // other wise only send the first word to match
const [firstWord] = roleValue.split(' ');
return matcher(firstWord, node, role, matchNormalizer);
}
const implicitRoles = (0, _roleHelpers.getImplicitAriaRoles)(node);
return implicitRoles.some(implicitRole => matcher(implicitRole, node, role, matchNormalizer));
}).filter(element => {
if (selected !== undefined) {
return selected === (0, _roleHelpers.computeAriaSelected)(element);
}
if (checked !== undefined) {
return checked === (0, _roleHelpers.computeAriaChecked)(element);
}
if (pressed !== undefined) {
return pressed === (0, _roleHelpers.computeAriaPressed)(element);
}
if (expanded !== undefined) {
return expanded === (0, _roleHelpers.computeAriaExpanded)(element);
}
if (level !== undefined) {
return level === (0, _roleHelpers.computeHeadingLevel)(element);
} // don't care if aria attributes are unspecified
return true;
}).filter(element => {
return hidden === false ? (0, _roleHelpers.isInaccessible)(element, {
isSubtreeInaccessible: cachedIsSubtreeInaccessible
}) === false : true;
}).filter(element => {
if (name === undefined) {
// Don't care
return true;
}
return (0, _allUtils.matches)((0, _domAccessibilityApi.computeAccessibleName)(element, {
computedStyleSupportsPseudoElements: (0, _allUtils.getConfig)().computedStyleSupportsPseudoElements
}), element, name, text => text);
});
}
const getMultipleError = (c, role, {
name
} = {}) => {
let nameHint = '';
if (name === undefined) {
nameHint = '';
} else if (typeof name === 'string') {
nameHint = ` and name "${name}"`;
} else {
nameHint = ` and name \`${name}\``;
}
return `Found multiple elements with the role "${role}"${nameHint}`;
};
const getMissingError = (container, role, {
hidden = (0, _allUtils.getConfig)().defaultHidden,
name
} = {}) => {
if ((0, _allUtils.getConfig)()._disableExpensiveErrorDiagnostics) {
return `Unable to find role="${role}"`;
}
let roles = '';
Array.from(container.children).forEach(childElement => {
roles += (0, _roleHelpers.prettyRoles)(childElement, {
hidden,
includeName: name !== undefined
});
});
let roleMessage;
if (roles.length === 0) {
if (hidden === false) {
roleMessage = 'There are no accessible roles. But there might be some inaccessible roles. ' + 'If you wish to access them, then set the `hidden` option to `true`. ' + 'Learn more about this here: https://testing-library.com/docs/dom-testing-library/api-queries#byrole';
} else {
roleMessage = 'There are no available roles.';
}
} else {
roleMessage = `
Here are the ${hidden === false ? 'accessible' : 'available'} roles:
${roles.replace(/\n/g, '\n ').replace(/\n\s\s\n/g, '\n\n')}
`.trim();
}
let nameHint = '';
if (name === undefined) {
nameHint = '';
} else if (typeof name === 'string') {
nameHint = ` and name "${name}"`;
} else {
nameHint = ` and name \`${name}\``;
}
return `
Unable to find an ${hidden === false ? 'accessible ' : ''}element with the role "${role}"${nameHint}
${roleMessage}`.trim();
};
const queryAllByRoleWithSuggestions = (0, _queryHelpers.wrapAllByQueryWithSuggestion)(queryAllByRole, queryAllByRole.name, 'queryAll');
exports.queryAllByRole = queryAllByRoleWithSuggestions;
const [queryByRole, getAllByRole, getByRole, findAllByRole, findByRole] = (0, _allUtils.buildQueries)(queryAllByRole, getMultipleError, getMissingError);
exports.findByRole = findByRole;
exports.findAllByRole = findAllByRole;
exports.getByRole = getByRole;
exports.getAllByRole = getAllByRole;
exports.queryByRole = queryByRole;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.findByTestId = exports.findAllByTestId = exports.getAllByTestId = exports.getByTestId = exports.queryAllByTestId = exports.queryByTestId = void 0;
var _helpers = require("../helpers");
var _queryHelpers = require("../query-helpers");
var _allUtils = require("./all-utils");
const getTestIdAttribute = () => (0, _allUtils.getConfig)().testIdAttribute;
function queryAllByTestId(...args) {
(0, _helpers.checkContainerType)(...args);
return (0, _allUtils.queryAllByAttribute)(getTestIdAttribute(), ...args);
}
const getMultipleError = (c, id) => `Found multiple elements by: [${getTestIdAttribute()}="${id}"]`;
const getMissingError = (c, id) => `Unable to find an element by: [${getTestIdAttribute()}="${id}"]`;
const queryAllByTestIdWithSuggestions = (0, _queryHelpers.wrapAllByQueryWithSuggestion)(queryAllByTestId, queryAllByTestId.name, 'queryAll');
exports.queryAllByTestId = queryAllByTestIdWithSuggestions;
const [queryByTestId, getAllByTestId, getByTestId, findAllByTestId, findByTestId] = (0, _allUtils.buildQueries)(queryAllByTestId, getMultipleError, getMissingError);
exports.findByTestId = findByTestId;
exports.findAllByTestId = findAllByTestId;
exports.getByTestId = getByTestId;
exports.getAllByTestId = getAllByTestId;
exports.queryByTestId = queryByTestId;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.findByText = exports.findAllByText = exports.getAllByText = exports.getByText = exports.queryAllByText = exports.queryByText = void 0;
var _queryHelpers = require("../query-helpers");
var _helpers = require("../helpers");
var _config = require("../config");
var _allUtils = require("./all-utils");
function queryAllByText(container, text, {
selector = '*',
exact = true,
collapseWhitespace,
trim,
ignore = _config.DEFAULT_IGNORE_TAGS,
normalizer
} = {}) {
(0, _helpers.checkContainerType)(container);
const matcher = exact ? _allUtils.matches : _allUtils.fuzzyMatches;
const matchNormalizer = (0, _allUtils.makeNormalizer)({
collapseWhitespace,
trim,
normalizer
});
let baseArray = [];
if (typeof container.matches === 'function' && container.matches(selector)) {
baseArray = [container];
}
return [...baseArray, ...Array.from(container.querySelectorAll(selector))].filter(node => !ignore || !node.matches(ignore)).filter(node => matcher((0, _allUtils.getNodeText)(node), node, text, matchNormalizer));
}
const getMultipleError = (c, text) => `Found multiple elements with the text: ${text}`;
const getMissingError = (c, text) => `Unable to find an element with the text: ${text}. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.`;
const queryAllByTextWithSuggestions = (0, _queryHelpers.wrapAllByQueryWithSuggestion)(queryAllByText, queryAllByText.name, 'queryAll');
exports.queryAllByText = queryAllByTextWithSuggestions;
const [queryByText, getAllByText, getByText, findAllByText, findByText] = (0, _allUtils.buildQueries)(queryAllByText, getMultipleError, getMissingError);
exports.findByText = findByText;
exports.findAllByText = findAllByText;
exports.getByText = getByText;
exports.getAllByText = getAllByText;
exports.queryByText = queryByText;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.findByTitle = exports.findAllByTitle = exports.getAllByTitle = exports.getByTitle = exports.queryAllByTitle = exports.queryByTitle = void 0;
var _queryHelpers = require("../query-helpers");
var _helpers = require("../helpers");
var _allUtils = require("./all-utils");
const isSvgTitle = node => {
var _node$parentElement;
return node.tagName.toLowerCase() === 'title' && ((_node$parentElement = node.parentElement) == null ? void 0 : _node$parentElement.tagName.toLowerCase()) === 'svg';
};
function queryAllByTitle(container, text, {
exact = true,
collapseWhitespace,
trim,
normalizer
} = {}) {
(0, _helpers.checkContainerType)(container);
const matcher = exact ? _allUtils.matches : _allUtils.fuzzyMatches;
const matchNormalizer = (0, _allUtils.makeNormalizer)({
collapseWhitespace,
trim,
normalizer
});
return Array.from(container.querySelectorAll('[title], svg > title')).filter(node => matcher(node.getAttribute('title'), node, text, matchNormalizer) || isSvgTitle(node) && matcher((0, _allUtils.getNodeText)(node), node, text, matchNormalizer));
}
const getMultipleError = (c, title) => `Found multiple elements with the title: ${title}.`;
const getMissingError = (c, title) => `Unable to find an element with the title: ${title}.`;
const queryAllByTitleWithSuggestions = (0, _queryHelpers.wrapAllByQueryWithSuggestion)(queryAllByTitle, queryAllByTitle.name, 'queryAll');
exports.queryAllByTitle = queryAllByTitleWithSuggestions;
const [queryByTitle, getAllByTitle, getByTitle, findAllByTitle, findByTitle] = (0, _allUtils.buildQueries)(queryAllByTitle, getMultipleError, getMissingError);
exports.findByTitle = findByTitle;
exports.findAllByTitle = findAllByTitle;
exports.getByTitle = getByTitle;
exports.getAllByTitle = getAllByTitle;
exports.queryByTitle = queryByTitle;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getElementError = getElementError;
exports.getMultipleElementsFoundError = getMultipleElementsFoundError;
exports.queryAllByAttribute = queryAllByAttribute;
exports.queryByAttribute = queryByAttribute;
exports.makeSingleQuery = makeSingleQuery;
exports.makeGetAllQuery = makeGetAllQuery;
exports.makeFindQuery = makeFindQuery;
exports.buildQueries = buildQueries;
exports.wrapSingleQueryWithSuggestion = exports.wrapAllByQueryWithSuggestion = void 0;
var _suggestions = require("./suggestions");
var _matches = require("./matches");
var _waitFor = require("./wait-for");
var _config = require("./config");
function getElementError(message, container) {
return (0, _config.getConfig)().getElementError(message, container);
}
function getMultipleElementsFoundError(message, container) {
return getElementError(`${message}\n\n(If this is intentional, then use the \`*AllBy*\` variant of the query (like \`queryAllByText\`, \`getAllByText\`, or \`findAllByText\`)).`, container);
}
function queryAllByAttribute(attribute, container, text, {
exact = true,
collapseWhitespace,
trim,
normalizer
} = {}) {
const matcher = exact ? _matches.matches : _matches.fuzzyMatches;
const matchNormalizer = (0, _matches.makeNormalizer)({
collapseWhitespace,
trim,
normalizer
});
return Array.from(container.querySelectorAll(`[${attribute}]`)).filter(node => matcher(node.getAttribute(attribute), node, text, matchNormalizer));
}
function queryByAttribute(attribute, container, text, ...args) {
const els = queryAllByAttribute(attribute, container, text, ...args);
if (els.length > 1) {
throw getMultipleElementsFoundError(`Found multiple elements by [${attribute}=${text}]`, container);
}
return els[0] || null;
} // this accepts a query function and returns a function which throws an error
// if more than one elements is returned, otherwise it returns the first
// element or null
function makeSingleQuery(allQuery, getMultipleError) {
return (container, ...args) => {
const els = allQuery(container, ...args);
if (els.length > 1) {
const elementStrings = els.map(element => getElementError(null, element).message).join('\n\n');
throw getMultipleElementsFoundError(`${getMultipleError(container, ...args)}
Here are the matching elements:
${elementStrings}`, container);
}
return els[0] || null;
};
}
function getSuggestionError(suggestion, container) {
return (0, _config.getConfig)().getElementError(`A better query is available, try this:
${suggestion.toString()}
`, container);
} // this accepts a query function and returns a function which throws an error
// if an empty list of elements is returned
function makeGetAllQuery(allQuery, getMissingError) {
return (container, ...args) => {
const els = allQuery(container, ...args);
if (!els.length) {
throw (0, _config.getConfig)().getElementError(getMissingError(container, ...args), container);
}
return els;
};
} // this accepts a getter query function and returns a function which calls
// waitFor and passing a function which invokes the getter.
function makeFindQuery(getter) {
return (container, text, options, waitForOptions) => (0, _waitFor.waitFor)(() => {
return getter(container, text, options);
}, waitForOptions);
}
const wrapSingleQueryWithSuggestion = (query, queryAllByName, variant) => (container, ...args) => {
const element = query(container, ...args);
const [{
suggest = (0, _config.getConfig)().throwSuggestions
} = {}] = args.slice(-1);
if (element && suggest) {
const suggestion = (0, _suggestions.getSuggestedQuery)(element, variant);
if (suggestion && !queryAllByName.endsWith(suggestion.queryName)) {
throw getSuggestionError(suggestion.toString(), container);
}
}
return element;
};
exports.wrapSingleQueryWithSuggestion = wrapSingleQueryWithSuggestion;
const wrapAllByQueryWithSuggestion = (query, queryAllByName, variant) => (container, ...args) => {
const els = query(container, ...args);
const [{
suggest = (0, _config.getConfig)().throwSuggestions
} = {}] = args.slice(-1);
if (els.length && suggest) {
// get a unique list of all suggestion messages. We are only going to make a suggestion if
// all the suggestions are the same
const uniqueSuggestionMessages = [...new Set(els.map(element => {
var _getSuggestedQuery;
return (_getSuggestedQuery = (0, _suggestions.getSuggestedQuery)(element, variant)) == null ? void 0 : _getSuggestedQuery.toString();
}))];
if ( // only want to suggest if all the els have the same suggestion.
uniqueSuggestionMessages.length === 1 && !queryAllByName.endsWith((0, _suggestions.getSuggestedQuery)(els[0], variant).queryName)) {
throw getSuggestionError(uniqueSuggestionMessages[0], container);
}
}
return els;
};
exports.wrapAllByQueryWithSuggestion = wrapAllByQueryWithSuggestion;
function buildQueries(queryAllBy, getMultipleError, getMissingError) {
const queryBy = wrapSingleQueryWithSuggestion(makeSingleQuery(queryAllBy, getMultipleError), queryAllBy.name, 'query');
const getAllBy = makeGetAllQuery(queryAllBy, getMissingError);
const getBy = makeSingleQuery(getAllBy, getMultipleError);
const getByWithSuggestions = wrapSingleQueryWithSuggestion(getBy, queryAllBy.name, 'get');
const getAllWithSuggestions = wrapAllByQueryWithSuggestion(getAllBy, queryAllBy.name.replace('query', 'get'), 'getAll');
const findAllBy = makeFindQuery(wrapAllByQueryWithSuggestion(getAllBy, queryAllBy.name, 'findAll'));
const findBy = makeFindQuery(wrapSingleQueryWithSuggestion(getBy, queryAllBy.name, 'find'));
return [queryBy, getAllWithSuggestions, getByWithSuggestions, findAllBy, findBy];
}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getRoles = getRoles;
exports.getImplicitAriaRoles = getImplicitAriaRoles;
exports.isSubtreeInaccessible = isSubtreeInaccessible;
exports.prettyRoles = prettyRoles;
exports.isInaccessible = isInaccessible;
exports.computeAriaSelected = computeAriaSelected;
exports.computeAriaChecked = computeAriaChecked;
exports.computeAriaPressed = computeAriaPressed;
exports.computeAriaExpanded = computeAriaExpanded;
exports.computeHeadingLevel = computeHeadingLevel;
exports.logRoles = void 0;
var _ariaQuery = require("aria-query");
var _domAccessibilityApi = require("dom-accessibility-api");
var _prettyDom = require("./pretty-dom");
var _config = require("./config");
const elementRoleList = buildElementRoleList(_ariaQuery.elementRoles);
/**
* @param {Element} element -
* @returns {boolean} - `true` if `element` and its subtree are inaccessible
*/
function isSubtreeInaccessible(element) {
if (element.hidden === true) {
return true;
}
if (element.getAttribute('aria-hidden') === 'true') {
return true;
}
const window = element.ownerDocument.defaultView;
if (window.getComputedStyle(element).display === 'none') {
return true;
}
return false;
}
/**
* Partial implementation https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion
* which should only be used for elements with a non-presentational role i.e.
* `role="none"` and `role="presentation"` will not be excluded.
*
* Implements aria-hidden semantics (i.e. parent overrides child)
* Ignores "Child Presentational: True" characteristics
*
* @param {Element} element -
* @param {object} [options] -
* @param {function (element: Element): boolean} options.isSubtreeInaccessible -
* can be used to return cached results from previous isSubtreeInaccessible calls
* @returns {boolean} true if excluded, otherwise false
*/
function isInaccessible(element, options = {}) {
const {
isSubtreeInaccessible: isSubtreeInaccessibleImpl = isSubtreeInaccessible
} = options;
const window = element.ownerDocument.defaultView; // since visibility is inherited we can exit early
if (window.getComputedStyle(element).visibility === 'hidden') {
return true;
}
let currentElement = element;
while (currentElement) {
if (isSubtreeInaccessibleImpl(currentElement)) {
return true;
}
currentElement = currentElement.parentElement;
}
return false;
}
function getImplicitAriaRoles(currentNode) {
// eslint bug here:
// eslint-disable-next-line no-unused-vars
for (const {
match,
roles
} of elementRoleList) {
if (match(currentNode)) {
return [...roles];
}
}
return [];
}
function buildElementRoleList(elementRolesMap) {
function makeElementSelector({
name,
attributes
}) {
return `${name}${attributes.map(({
name: attributeName,
value,
constraints = []
}) => {
const shouldNotExist = constraints.indexOf('undefined') !== -1;
if (shouldNotExist) {
return `:not([${attributeName}])`;
} else if (value) {
return `[${attributeName}="${value}"]`;
} else {
return `[${attributeName}]`;
}
}).join('')}`;
}
function getSelectorSpecificity({
attributes = []
}) {
return attributes.length;
}
function match(element) {
return node => {
let {
attributes = []
} = element; // https://github.com/testing-library/dom-testing-library/issues/814
const typeTextIndex = attributes.findIndex(attribute => attribute.value && attribute.name === 'type' && attribute.value === 'text');
if (typeTextIndex >= 0) {
// not using splice to not mutate the attributes array
attributes = [...attributes.slice(0, typeTextIndex), ...attributes.slice(typeTextIndex + 1)];
if (node.type !== 'text') {
return false;
}
}
return node.matches(makeElementSelector({ ...element,
attributes
}));
};
}
let result = []; // eslint bug here:
// eslint-disable-next-line no-unused-vars
for (const [element, roles] of elementRolesMap.entries()) {
result = [...result, {
match: match(element),
roles: Array.from(roles),
specificity: getSelectorSpecificity(element)
}];
}
return result.sort(function ({
specificity: leftSpecificity
}, {
specificity: rightSpecificity
}) {
return rightSpecificity - leftSpecificity;
});
}
function getRoles(container, {
hidden = false
} = {}) {
function flattenDOM(node) {
return [node, ...Array.from(node.children).reduce((acc, child) => [...acc, ...flattenDOM(child)], [])];
}
return flattenDOM(container).filter(element => {
return hidden === false ? isInaccessible(element) === false : true;
}).reduce((acc, node) => {
let roles = []; // TODO: This violates html-aria which does not allow any role on every element
if (node.hasAttribute('role')) {
roles = node.getAttribute('role').split(' ').slice(0, 1);
} else {
roles = getImplicitAriaRoles(node);
}
return roles.reduce((rolesAcc, role) => Array.isArray(rolesAcc[role]) ? { ...rolesAcc,
[role]: [...rolesAcc[role], node]
} : { ...rolesAcc,
[role]: [node]
}, acc);
}, {});
}
function prettyRoles(dom, {
hidden
}) {
const roles = getRoles(dom, {
hidden
}); // We prefer to skip generic role, we don't recommend it
return Object.entries(roles).filter(([role]) => role !== 'generic').map(([role, elements]) => {
const delimiterBar = '-'.repeat(50);
const elementsString = elements.map(el => {
const nameString = `Name "${(0, _domAccessibilityApi.computeAccessibleName)(el, {
computedStyleSupportsPseudoElements: (0, _config.getConfig)().computedStyleSupportsPseudoElements
})}":\n`;
const domString = (0, _prettyDom.prettyDOM)(el.cloneNode(false));
return `${nameString}${domString}`;
}).join('\n\n');
return `${role}:\n\n${elementsString}\n\n${delimiterBar}`;
}).join('\n');
}
const logRoles = (dom, {
hidden = false
} = {}) => console.log(prettyRoles(dom, {
hidden
}));
/**
* @param {Element} element -
* @returns {boolean | undefined} - false/true if (not)selected, undefined if not selectable
*/
exports.logRoles = logRoles;
function computeAriaSelected(element) {
// implicit value from html-aam mappings: https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings
// https://www.w3.org/TR/html-aam-1.0/#details-id-97
if (element.tagName === 'OPTION') {
return element.selected;
} // explicit value
return checkBooleanAttribute(element, 'aria-selected');
}
/**
* @param {Element} element -
* @returns {boolean | undefined} - false/true if (not)checked, undefined if not checked-able
*/
function computeAriaChecked(element) {
// implicit value from html-aam mappings: https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings
// https://www.w3.org/TR/html-aam-1.0/#details-id-56
// https://www.w3.org/TR/html-aam-1.0/#details-id-67
if ('indeterminate' in element && element.indeterminate) {
return undefined;
}
if ('checked' in element) {
return element.checked;
} // explicit value
return checkBooleanAttribute(element, 'aria-checked');
}
/**
* @param {Element} element -
* @returns {boolean | undefined} - false/true if (not)pressed, undefined if not press-able
*/
function computeAriaPressed(element) {
// https://www.w3.org/TR/wai-aria-1.1/#aria-pressed
return checkBooleanAttribute(element, 'aria-pressed');
}
/**
* @param {Element} element -
* @returns {boolean | undefined} - false/true if (not)expanded, undefined if not expand-able
*/
function computeAriaExpanded(element) {
// https://www.w3.org/TR/wai-aria-1.1/#aria-expanded
return checkBooleanAttribute(element, 'aria-expanded');
}
function checkBooleanAttribute(element, attribute) {
const attributeValue = element.getAttribute(attribute);
if (attributeValue === 'true') {
return true;
}
if (attributeValue === 'false') {
return false;
}
return undefined;
}
/**
* @param {Element} element -
* @returns {number | undefined} - number if implicit heading or aria-level present, otherwise undefined
*/
function computeHeadingLevel(element) {
// https://w3c.github.io/html-aam/#el-h1-h6
// https://w3c.github.io/html-aam/#el-h1-h6
// explicit aria-level value
// https://www.w3.org/TR/wai-aria-1.2/#aria-level
const ariaLevelAttribute = element.getAttribute('aria-level') && Number(element.getAttribute('aria-level'));
return ariaLevelAttribute || {
H1: 1,
H2: 2,
H3: 3,
H4: 4,
H5: 5,
H6: 6
}[element.tagName];
}
\ No newline at end of file
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.screen = void 0;
var _lzString = require("lz-string");
var queries = _interopRequireWildcard(require("./queries"));
var _getQueriesForElement = require("./get-queries-for-element");
var _prettyDom = require("./pretty-dom");
var _helpers = require("./helpers");
function unindent(string) {
// remove white spaces first, to save a few bytes.
// testing-playground will reformat on load any ways.
return string.replace(/[ \t]*[\n][ \t]*/g, '\n');
}
function encode(value) {
return (0, _lzString.compressToEncodedURIComponent)(unindent(value));
}
function getPlaygroundUrl(markup) {
return `https://testing-playground.com/#markup=${encode(markup)}`;
}
const debug = (element, maxLength, options) => Array.isArray(element) ? element.forEach(el => (0, _prettyDom.logDOM)(el, maxLength, options)) : (0, _prettyDom.logDOM)(element, maxLength, options);
const logTestingPlaygroundURL = (element = (0, _helpers.getDocument)().body) => {
if (!element || !('innerHTML' in element)) {
console.log(`The element you're providing isn't a valid DOM element.`);
return;
}
if (!element.innerHTML) {
console.log(`The provided element doesn't have any children.`);
return;
}
console.log(`Open this URL in your browser\n\n${getPlaygroundUrl(element.innerHTML)}`);
};
const initialValue = {
debug,
logTestingPlaygroundURL
};
const screen = typeof document !== 'undefined' && document.body ? (0, _getQueriesForElement.getQueriesForElement)(document.body, queries, initialValue) : Object.keys(queries).reduce((helpers, key) => {
helpers[key] = () => {
throw new TypeError('For queries bound to document.body a global document has to be available... Learn more: https://testing-library.com/s/screen-global-error');
};
return helpers;
}, initialValue);
exports.screen = screen;
\ No newline at end of file
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.