2
0
mirror of https://github.com/iconify/iconify.git synced 2024-09-19 08:49:02 +00:00

Remove archived packages because they are no longer updated for new code

This commit is contained in:
Vjacheslav Trushkin 2021-09-30 09:36:47 +03:00
parent 818f78eda4
commit c1773e2554
59 changed files with 5 additions and 102870 deletions

View File

@ -54,24 +54,19 @@ Other packages:
- [Iconify types](./packages/types/) - TypeScript types.
- [Iconify utils](./packages/utils/) - common files used by various Iconify projects (including tools, API, etc...).
- [Iconify core](./packages/core/) - common files used by various components.
- [API redundancy](./packages/api-redundancy/) - library for managing redundancies for loading data from API: handling timeouts, rotating hosts.
- [Library builder](./packages/library-builder/) - build scripts for packages that do not require bundling, similar to `tsup`, but without bundler. Used by Utils, Core and API Redundancy packages. Builds ES and CommonJS modules, type definition files and updates exports in `package.json`.
- [React demo](./packages/react-demo/) - demo for React component. Run `npm start` to start demo.
- [Next.js demo](./packages/nextjs-demo/) - demo for React component with Next.js. Run `npm run build` to build it and `npm start` to start demo.
- [Vue 3 demo](./packages/vue-demo/) - demo for Vue component. Run `npm run dev` to start demo.
- [Vue 2 demo](./packages/vue2-demo/) - demo for Vue component. Run `npm run dev` to start demo.
- [Svelte demo](./packages/svelte-demo/) - demo for Svelte component. Run `npm run dev` to start demo.
- [Sapper demo](./packages/sapper-demo/) - demo for Sapper, using Svelte component on the server and in the browser. Run `npm run dev` to start the demo.
- [Svelte demo with Vite](./packages/svelte-demo-vite/) - demo for Svelte component using Vite. Run `npm run dev` to start demo.
- [Sapper demo](./packages/sapper-demo/) - demo for Sapper, using Svelte component on the server and in the browser. Run `npm run dev` to start the demo (deprecated, use SvelteKit instead of Sapper).
- [SvelteKit demo](./packages/sveltekit-demo/) - demo for SvelteKit, using Svelte component on the server and in the browser. Run `npm run dev` to start the demo.
- [Ember demo](./packages/ember-demo/) - demo for Ember component. Run `npm run start` to start demo.
- [Browser tests](./packages/browser-tests/) - unit tests for SVG framework. Run `npm run build` to build it. Open test.html in browser (requires HTTP server).
### Legacy packages
Unfortunately Lerna does not support several versions of the same package. Because of that, some packages were moved from "packages" to "archive". This applies only to packages that were replaced by newer packages that aren't backwards compatible (and packages that rely on those packages).
Legacy packages:
- [React with API](./archive/react-with-api/) - React component with API support. It has been merged with [`react` package](./packages/react/) in newer version.
- [React](./archive/react/) - React component without API support. Component without API support does not make sense, there are plenty of other icon components already, so this component has been archived and replaced with new component that supports Iconify API.
## Installation
This monorepo uses Lerna to manage packages.

View File

@ -1,162 +0,0 @@
// Archived from: packages/core/src/api/modules/axios.ts
import axios from 'axios';
import { RedundancyPendingItem } from '@cyberalien/redundancy';
import {
APIQueryParams,
IconifyAPIPrepareQuery,
IconifyAPISendQuery,
IconifyAPIModule,
GetIconifyAPIModule,
} from '../modules';
import { GetAPIConfig } from '../config';
/**
* Endpoint
*/
const endPoint = '{prefix}.json?icons={icons}';
/**
* Cache
*/
const maxLengthCache: Record<string, number> = Object.create(null);
const pathCache: Record<string, string> = Object.create(null);
/**
* Return API module
*/
export const getAPIModule: GetIconifyAPIModule = (
getAPIConfig: GetAPIConfig
): IconifyAPIModule => {
/**
* Calculate maximum icons list length for prefix
*/
function calculateMaxLength(provider: string, prefix: string): number {
// Get config and store path
const config = getAPIConfig(provider);
if (!config) {
return 0;
}
// Calculate
let result;
if (!config.maxURL) {
result = 0;
} else {
let maxHostLength = 0;
config.resources.forEach((host) => {
maxHostLength = Math.max(maxHostLength, host.length);
});
// Get available length
result =
config.maxURL -
maxHostLength -
config.path.length -
endPoint
.replace('{provider}', provider)
.replace('{prefix}', prefix)
.replace('{icons}', '').length;
}
// Cache stuff and return result
const cacheKey = provider + ':' + prefix;
pathCache[cacheKey] = config.path;
maxLengthCache[cacheKey] = result;
return result;
}
/**
* Prepare params
*/
const prepare: IconifyAPIPrepareQuery = (
provider: string,
prefix: string,
icons: string[]
): APIQueryParams[] => {
const results: APIQueryParams[] = [];
// Get maximum icons list length
let maxLength = maxLengthCache[prefix];
if (maxLength === void 0) {
maxLength = calculateMaxLength(provider, prefix);
}
// Split icons
let item: APIQueryParams = {
provider,
prefix,
icons: [],
};
let length = 0;
icons.forEach((name, index) => {
length += name.length + 1;
if (length >= maxLength && index > 0) {
// Next set
results.push(item);
item = {
provider,
prefix,
icons: [],
};
length = name.length;
}
item.icons.push(name);
});
results.push(item);
return results;
};
/**
* Load icons
*/
const send: IconifyAPISendQuery = (
host: string,
params: APIQueryParams,
status: RedundancyPendingItem
): void => {
const provider = params.provider;
const prefix = params.prefix;
const icons = params.icons;
const iconsList = icons.join(',');
const cacheKey = provider + ':' + prefix;
const path =
pathCache[cacheKey] +
endPoint
.replace('{provider}', provider)
.replace('{prefix}', prefix)
.replace('{icons}', iconsList);
// console.log('API query:', host + path);
const instance = axios.create({
baseURL: host,
});
instance
.get(path)
.then((response) => {
if (response.status !== 200) {
return;
}
// Copy data. No need to parse it, axios parses JSON data
const data = response.data;
if (typeof data !== 'object' || data === null) {
return;
}
// Store cache and complete
status.done(data);
})
.catch(() => {
// Do nothing
});
};
// Return functions
return {
prepare,
send,
};
};

View File

@ -1,23 +0,0 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

View File

@ -1,68 +0,0 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br />
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.<br />
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.<br />
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.<br />
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
### Analyzing the Bundle Size
This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
### Making a Progressive Web App
This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
### Advanced Configuration
This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
### Deployment
This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
### `npm run build` fails to minify
This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify

File diff suppressed because it is too large Load Diff

View File

@ -1,34 +0,0 @@
{
"name": "@iconify/react-demo-with-api",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "^4.0.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@iconify-icons/mdi-light": "^1.1.0",
"@iconify/react-with-api": "^1.0.0-rc.7"
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

View File

@ -1,43 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.4 KiB

View File

@ -1,25 +0,0 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@ -1,3 +0,0 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

View File

@ -1,132 +0,0 @@
.App {
font-family: Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: left;
color: #2c3e50;
font-size: 16px;
line-height: 1.5;
}
/* Sections */
section {
border-bottom: 1px dotted #ccc;
padding: 16px;
}
section:last-child {
border-bottom-width: 0;
}
section:after {
content: ' ';
display: table;
clear: both;
}
h1 {
margin: 0 0 16px;
padding: 0;
font-size: 24px;
font-weight: normal;
}
p {
margin: 12px 0 4px;
padding: 0;
}
/* 24px icon */
.icon-24 svg {
font-size: 24px;
line-height: 1;
vertical-align: -0.25em;
}
/* Alert demo */
.alert {
position: relative;
margin: 8px;
padding: 16px;
padding-left: 48px;
background: #ba3329;
color: #fff;
border-radius: 5px;
float: left;
}
.alert + div {
clear: both;
}
.alert svg {
position: absolute;
left: 12px;
top: 50%;
font-size: 24px;
line-height: 1em;
margin: -0.5em 0 0;
}
/* Checkbox component */
.checkbox-container {
margin: 8px 0;
}
.checkbox {
cursor: pointer;
/* color: #1769aa; */
color: #626262;
text-decoration: none;
}
.checkbox:hover {
color: #ba3329;
text-decoration: underline;
}
.checkbox svg {
margin-right: 4px;
color: #afafaf;
font-size: 24px;
line-height: 1em;
vertical-align: -0.25em;
}
.checkbox--checked svg {
color: #327335;
}
.checkbox:hover svg {
color: inherit;
}
.checkbox-container small {
margin-left: 4px;
opacity: 0.7;
}
/* Inline demo */
.inline-demo svg {
color: #06a;
margin: 0 8px;
position: relative;
z-index: 2;
background: #fff;
}
.inline-demo div {
position: relative;
font-size: 16px;
line-height: 1.5;
}
.inline-demo div:before,
.inline-demo div:after {
content: '';
position: absolute;
left: 0;
right: 0;
height: 0;
border-top: 1px dashed #506874;
opacity: 0.5;
z-index: -1;
}
.inline-demo div:before {
bottom: 5px;
}
.inline-demo div:after {
bottom: 7px;
border-top-color: #ba3329;
}

View File

@ -1,154 +0,0 @@
import React from 'react';
import { Icon, InlineIcon, disableCache } from '@iconify/react-with-api';
import accountIcon from '@iconify-icons/mdi-light/account';
import homeIcon from '@iconify-icons/mdi-light/home';
import { Checkbox } from './components/Checkbox';
import { InlineDemo } from './components/Inline';
import './App.css';
// Disable cache for test
disableCache('all');
class CheckboxIcon extends React.Component {
constructor(props) {
super();
this.state = {
checked: props.checked,
};
this._check = this._check.bind(this);
}
render() {
const checked = this.state.checked;
const icon = checked ? 'uil:check-circle' : 'uil:circle';
const color = checked ? 'green' : 'red';
return (
<InlineIcon
icon={icon}
onClick={this._check}
style={{ cursor: 'pointer', color }}
/>
);
}
_check(event) {
event.preventDefault();
this.setState({
checked: !this.state.checked,
});
}
}
function App() {
return (
<div className="App">
<section className="icon-24">
<h1>Usage</h1>
<div>
Empty icon: <Icon />
</div>
<div>
Icon referenced by name:{' '}
<Icon icon="mdi-light:presentation-play" />
</div>
<div>
Icon referenced by object: <Icon icon={accountIcon} />
</div>
<div className="alert">
<Icon icon="mdi-light:alert" />
Important notice with alert icon!
</div>
</section>
<section>
<h1>Checkbox</h1>
<div>
<Checkbox
checked={true}
text="Checkbox example"
hint="(click to toggle)"
/>
<Checkbox
checked={false}
text="Another checkbox example"
hint="(click to toggle)"
/>
</div>
</section>
<section>
<h1>Tests</h1>
<p>
<Icon
icon={homeIcon}
style={{
color: '#1769aa',
fontSize: '24px',
lineHeight: '1em',
verticalAlign: '-0.25em',
}}
/>
Home icon! 24px icon in 16px text with 24px line height,
aligned using inline style.
</p>
<p>
Clickable icon (testing events and style): <CheckboxIcon />
</p>
<p>
Colored icons (block, inline, block):
<InlineIcon
icon="mdi-light:alert"
style={{
fontSize: '1.5em',
verticalAlign: 0,
marginLeft: '8px',
}}
color="green"
/>
<InlineIcon
icon="mdi-light:alert"
style={{
fontSize: '1.5em',
color: 'red',
marginLeft: '8px',
}}
/>
<Icon
icon="mdi-light:alert"
style={{
fontSize: '1.5em',
color: 'purple',
marginLeft: '8px',
}}
/>
</p>
<p>
Testing reference by adding border to icon (unfortunately
should not work yet):{' '}
<Icon
icon="mdi-light:alert"
ref={(element) => {
if (element) {
element.style.border = '1px solid red';
}
}}
/>
<Icon
icon={accountIcon}
ref={(element) => {
if (element) {
element.style.border = '1px solid red';
}
}}
/>
</p>
</section>
<InlineDemo />
</div>
);
}
export default App;

View File

@ -1,39 +0,0 @@
import React from 'react';
import { Icon, loadIcons } from '@iconify/react-with-api';
// Load both icons before starting
loadIcons(['uil:check-circle', 'uil:circle']);
export class Checkbox extends React.Component {
constructor(props) {
super();
this.state = {
checked: props.checked,
};
this._check = this._check.bind(this);
}
render() {
const checked = this.state.checked;
const icon = checked ? 'uil:check-circle' : 'uil:circle';
const className =
'checkbox checkbox--' + (checked ? 'checked' : 'unchecked');
return (
<div className="checkbox-container">
<a href="# " className={className} onClick={this._check}>
<Icon icon={icon} />
{this.props.text}
</a>
<small>{this.props.hint}</small>
</div>
);
}
_check(event) {
event.preventDefault();
this.setState({
checked: !this.state.checked,
});
}
}

View File

@ -1,27 +0,0 @@
import React from 'react';
import { Icon } from '@iconify/react-with-api';
export function InlineDemo() {
return (
<section className="inline-demo">
<h1>Inline (components/Inline.jsx)</h1>
<div>
Block icon (behaving like image):
<Icon icon="bi:droplet-half" />
</div>
<div>
Inline icon (behaving line text / icon font):
<Icon icon="bi:droplet-half" inline={true} />
</div>
<div>
Using "vertical-align: 0" to override inline attribute:
<Icon icon="bi:stickies" style={{ verticalAlign: 0 }} />
<Icon
icon="bi:stickies"
style={{ verticalAlign: 0 }}
inline={true}
/>
</div>
</section>
);
}

View File

@ -1,13 +0,0 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}

View File

@ -1,12 +0,0 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

View File

@ -1,141 +0,0 @@
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { 'Service-Worker': 'script' }
})
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready
.then(registration => {
registration.unregister();
})
.catch(error => {
console.error(error.message);
});
}
}

View File

@ -1,23 +0,0 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

View File

@ -1,68 +0,0 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br />
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.<br />
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.<br />
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.<br />
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
### Analyzing the Bundle Size
This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
### Making a Progressive Web App
This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
### Advanced Configuration
This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
### Deployment
This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
### `npm run build` fails to minify
This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify

File diff suppressed because it is too large Load Diff

View File

@ -1,35 +0,0 @@
{
"name": "@iconify/react-demo",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "^4.0.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@iconify-icons/mdi-light": "^1.1.0",
"@iconify-icons/uil": "^1.1.1",
"@iconify/react": "^2.0.0-rc.8"
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

View File

@ -1,43 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.4 KiB

View File

@ -1,25 +0,0 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@ -1,3 +0,0 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

View File

@ -1,132 +0,0 @@
.App {
font-family: Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: left;
color: #2c3e50;
font-size: 16px;
line-height: 1.5;
}
/* Sections */
section {
border-bottom: 1px dotted #ccc;
padding: 16px;
}
section:last-child {
border-bottom-width: 0;
}
section:after {
content: ' ';
display: table;
clear: both;
}
h1 {
margin: 0 0 16px;
padding: 0;
font-size: 24px;
font-weight: normal;
}
p {
margin: 12px 0 4px;
padding: 0;
}
/* 24px icon */
.icon-24 svg {
font-size: 24px;
line-height: 1;
vertical-align: -0.25em;
}
/* Alert demo */
.alert {
position: relative;
margin: 8px;
padding: 16px;
padding-left: 48px;
background: #ba3329;
color: #fff;
border-radius: 5px;
float: left;
}
.alert + div {
clear: both;
}
.alert svg {
position: absolute;
left: 12px;
top: 50%;
font-size: 24px;
line-height: 1em;
margin: -0.5em 0 0;
}
/* Checkbox component */
.checkbox-container {
margin: 8px 0;
}
.checkbox {
cursor: pointer;
/* color: #1769aa; */
color: #626262;
text-decoration: none;
}
.checkbox:hover {
color: #ba3329;
text-decoration: underline;
}
.checkbox svg {
margin-right: 4px;
color: #afafaf;
font-size: 24px;
line-height: 1em;
vertical-align: -0.25em;
}
.checkbox--checked svg {
color: #327335;
}
.checkbox:hover svg {
color: inherit;
}
.checkbox-container small {
margin-left: 4px;
opacity: 0.7;
}
/* Inline demo */
.inline-demo svg {
color: #06a;
margin: 0 8px;
position: relative;
z-index: 2;
background: #fff;
}
.inline-demo div {
position: relative;
font-size: 16px;
line-height: 1.5;
}
.inline-demo div:before,
.inline-demo div:after {
content: '';
position: absolute;
left: 0;
right: 0;
height: 0;
border-top: 1px dashed #506874;
opacity: 0.5;
z-index: -1;
}
.inline-demo div:before {
bottom: 5px;
}
.inline-demo div:after {
bottom: 7px;
border-top-color: #ba3329;
}

View File

@ -1,220 +0,0 @@
import React from 'react';
import { Icon, InlineIcon, addIcon, addCollection } from '@iconify/react';
import accountIcon from '@iconify-icons/mdi-light/account';
import alertIcon from '@iconify-icons/mdi-light/alert';
import homeIcon from '@iconify-icons/mdi-light/home';
import presentationPlay from '@iconify-icons/mdi-light/presentation-play';
import checkedIcon from '@iconify-icons/uil/check-circle';
import uncheckedIcon from '@iconify-icons/uil/circle';
import { Checkbox } from './components/Checkbox';
import { InlineDemo } from './components/Inline';
import './App.css';
// Add 'mdi-light:presentation-play' as 'demo'
addIcon('demo', presentationPlay);
// Add custom icon as 'experiment'
addIcon('experiment2', {
width: 16,
height: 16,
body:
'<circle fill-opacity="0.2" cx="8" cy="8" r="7" fill="currentColor"/><path fill-rule="evenodd" clip-rule="evenodd" d="M8 16C12.4183 16 16 12.4183 16 8C16 3.58172 12.4183 0 8 0C3.58172 0 0 3.58172 0 8C0 12.4183 3.58172 16 8 16ZM8 15C11.866 15 15 11.866 15 8C15 4.13401 11.866 1 8 1C4.13401 1 1 4.13401 1 8C1 11.866 4.13401 15 8 15Z" fill="currentColor"/><path d="M7 9L5 7L3.5 8.5L7 12L13 6L11.5 4.5L7 9Z" fill="currentColor"/>',
});
// Add icon with id: noto:robot
addIcon('noto-robot', {
body:
'<path d="M12.53 53.05c-4.57.01-8.28 3.72-8.28 8.29v38.38a8.297 8.297 0 0 0 8.28 8.28h5.55V53l-5.55.05z" fill="#c62828"/><path d="M115.72 53.05c4.57.01 8.28 3.72 8.28 8.29v38.38c-.01 4.57-3.71 8.28-8.28 8.29h-5.55v-55l5.55.04z" fill="#c62828"/><path d="M113.17 54.41l-.12-10c-.03-4.3-3.53-7.77-7.83-7.75H67.05V23.25c5.11-1.69 7.89-7.2 6.2-12.31c-1.69-5.11-7.2-7.89-12.31-6.2s-7.89 7.2-6.2 12.31a9.743 9.743 0 0 0 6.2 6.2v13.46H22.78c-4.28.01-7.75 3.47-7.78 7.75v71.78c.03 4.28 3.5 7.74 7.78 7.76h82.44c4.3.01 7.8-3.46 7.83-7.76v-7.37h.12V54.41z" fill="#90a4ae"/><path d="M64 18c-2.21 0-4-1.79-4-4s1.79-4 4-4s4 1.79 4 4s-1.79 4-4 4z" fill="#c62828"/><g><linearGradient id="ssvg-id-robota" gradientUnits="userSpaceOnUse" x1="64.005" y1="22.44" x2="64.005" y2="35.55" gradientTransform="matrix(1 0 0 -1 0 130)"><stop offset=".12" stop-color="#e0e0e0"/><stop offset=".52" stop-color="#fff"/><stop offset="1" stop-color="#eaeaea"/></linearGradient><path d="M44.15 94.45h39.71c3.46 0 6.27 2.81 6.27 6.27v.57c0 3.46-2.81 6.27-6.27 6.27H44.15c-3.46 0-6.27-2.81-6.27-6.27v-.57c0-3.46 2.81-6.27 6.27-6.27z" fill="url(#ssvg-id-robota)"/><linearGradient id="ssvg-id-robotb" gradientUnits="userSpaceOnUse" x1="54.85" y1="22.44" x2="54.85" y2="35.53" gradientTransform="matrix(1 0 0 -1 0 130)"><stop offset="0" stop-color="#333"/><stop offset=".55" stop-color="#666"/><stop offset="1" stop-color="#333"/></linearGradient><path fill="url(#ssvg-id-robotb)" d="M53.67 94.47h2.36v13.09h-2.36z"/><linearGradient id="ssvg-id-robotc" gradientUnits="userSpaceOnUse" x1="64.06" y1="22.44" x2="64.06" y2="35.53" gradientTransform="matrix(1 0 0 -1 0 130)"><stop offset="0" stop-color="#333"/><stop offset=".55" stop-color="#666"/><stop offset="1" stop-color="#333"/></linearGradient><path fill="url(#ssvg-id-robotc)" d="M62.88 94.47h2.36v13.09h-2.36z"/><linearGradient id="ssvg-id-robotd" gradientUnits="userSpaceOnUse" x1="73.15" y1="22.44" x2="73.15" y2="35.53" gradientTransform="matrix(1 0 0 -1 0 130)"><stop offset="0" stop-color="#333"/><stop offset=".55" stop-color="#666"/><stop offset="1" stop-color="#333"/></linearGradient><path fill="url(#ssvg-id-robotd)" d="M71.97 94.47h2.36v13.09h-2.36z"/><linearGradient id="ssvg-id-robote" gradientUnits="userSpaceOnUse" x1="82.8" y1="22.44" x2="82.8" y2="35.53" gradientTransform="matrix(1 0 0 -1 0 130)"><stop offset="0" stop-color="#333"/><stop offset=".55" stop-color="#666"/><stop offset="1" stop-color="#333"/></linearGradient><path fill="url(#ssvg-id-robote)" d="M81.62 94.47h2.36v13.09h-2.36z"/><linearGradient id="ssvg-id-robotf" gradientUnits="userSpaceOnUse" x1="45.2" y1="22.46" x2="45.2" y2="35.55" gradientTransform="matrix(1 0 0 -1 0 130)"><stop offset="0" stop-color="#333"/><stop offset=".55" stop-color="#666"/><stop offset="1" stop-color="#333"/></linearGradient><path fill="url(#ssvg-id-robotf)" d="M44.02 94.45h2.36v13.09h-2.36z"/><g><path d="M64 85.33h-5.33c-.55 0-1-.45-1-1c0-.16.04-.31.11-.45l2.74-5.41l2.59-4.78a.996.996 0 0 1 1.76 0l2.61 5l2.71 5.19c.25.49.06 1.09-.43 1.35c-.14.07-.29.11-.45.11L64 85.33z" fill="#c62828"/></g><g><radialGradient id="ssvg-id-robotg" cx="42.64" cy="63.19" r="11.5" gradientTransform="matrix(1 0 0 -1 0 130)" gradientUnits="userSpaceOnUse"><stop offset=".48" stop-color="#fff"/><stop offset=".77" stop-color="#fdfdfd"/><stop offset=".88" stop-color="#f6f6f6"/><stop offset=".96" stop-color="#ebebeb"/><stop offset="1" stop-color="#e0e0e0"/></radialGradient><circle cx="42.64" cy="66.81" r="11.5" fill="url(#ssvg-id-robotg)"/><linearGradient id="ssvg-id-roboth" gradientUnits="userSpaceOnUse" x1="30.14" y1="63.19" x2="55.14" y2="63.19" gradientTransform="matrix(1 0 0 -1 0 130)"><stop offset="0" stop-color="#333"/><stop offset=".55" stop-color="#666"/><stop offset="1" stop-color="#333"/></linearGradient><circle cx="42.64" cy="66.81" r="11.5" fill="none" stroke="url(#ssvg-id-roboth)" stroke-width="2" stroke-miterlimit="10"/><radialGradient id="ssvg-id-roboti" cx="84.95" cy="63.22" r="11.5" gradientTransform="matrix(1 0 0 -1 0 130)" gradientUnits="userSpaceOnUse"><stop offset=".48" stop-color="#fff"/><stop offset=".77" stop-color="#fdfdfd"/><stop offset=".88" stop-color="#f6f6f6"/><stop offset=".96" stop-color="#ebebeb"/><stop offset="1" stop-color="#e0e0e0"/></radialGradient><path d="M85 55.28c-6.35 0-11.5 5.15-11.5 11.5s5.15 11.5 11.5 11.5s11.5-5.15 11.5-11.5c-.01-6.35-5.15-11.49-11.5-11.5z" fill="url(#ssvg-id-roboti)"/><linearGradient id="ssvg-id-robotj" gradientUnits="userSpaceOnUse" x1="72.45" y1="63.22" x2="97.45" y2="63.22" gradientTransform="matrix(1 0 0 -1 0 130)"><stop offset="0" stop-color="#333"/><stop offset=".55" stop-color="#666"/><stop offset="1" stop-color="#333"/></linearGradient><path d="M85 55.28c-6.35 0-11.5 5.15-11.5 11.5s5.15 11.5 11.5 11.5s11.5-5.15 11.5-11.5h0c-.01-6.35-5.15-11.49-11.5-11.5z" fill="none" stroke="url(#ssvg-id-robotj)" stroke-width="2" stroke-miterlimit="10"/></g></g>',
width: 128,
height: 128,
});
// Add few mdi-light: icons
addCollection({
prefix: 'mdi-light',
icons: {
'account-alert': {
body:
'<path d="M10.5 14c4.142 0 7.5 1.567 7.5 3.5V20H3v-2.5c0-1.933 3.358-3.5 7.5-3.5zm6.5 3.5c0-1.38-2.91-2.5-6.5-2.5S4 16.12 4 17.5V19h13v-1.5zM10.5 5a3.5 3.5 0 1 1 0 7a3.5 3.5 0 0 1 0-7zm0 1a2.5 2.5 0 1 0 0 5a2.5 2.5 0 0 0 0-5zM20 16v-1h1v1h-1zm0-3V7h1v6h-1z" fill="currentColor"/>',
},
'link': {
body:
'<path d="M8 13v-1h7v1H8zm7.5-6a5.5 5.5 0 1 1 0 11H13v-1h2.5a4.5 4.5 0 1 0 0-9H13V7h2.5zm-8 11a5.5 5.5 0 1 1 0-11H10v1H7.5a4.5 4.5 0 1 0 0 9H10v1H7.5z" fill="currentColor"/>',
},
},
width: 24,
height: 24,
});
// Component
class CheckboxIcon extends React.Component {
constructor(props) {
super();
this.state = {
checked: props.checked,
};
this._check = this._check.bind(this);
}
render() {
const checked = this.state.checked;
const icon = checked ? checkedIcon : uncheckedIcon;
const color = checked ? 'green' : 'red';
return (
<InlineIcon
icon={icon}
onClick={this._check}
style={{ cursor: 'pointer', color }}
/>
);
}
_check(event) {
event.preventDefault();
this.setState({
checked: !this.state.checked,
});
}
}
function App() {
// Debug logging for testing references, which cannot be reliably tested with unit tests
console.log('References that should be logged: valid icon');
console.log('References that might be logged: missing icon');
console.log('References that should not be logged: missing text icon');
return (
<div className="App">
<section className="icon-24">
<h1>Usage</h1>
<div>
Empty icon: <Icon />
</div>
<div>
Icon referenced by name: <Icon icon="demo" />
</div>
<div>
Icon referenced by object: <Icon icon={accountIcon} />
</div>
<div>
2 icons imported from icon set:{' '}
<Icon icon="mdi-light:account-alert" />
<Icon icon="mdi-light:link" />
</div>
<div className="alert">
<Icon icon={alertIcon} />
Important notice with alert icon!
</div>
</section>
<section>
<h1>Checkbox</h1>
<div>
<Checkbox
checked={true}
text="Checkbox example"
hint="(click to toggle)"
/>
<Checkbox
checked={false}
text="Another checkbox example"
hint="(click to toggle)"
/>
</div>
</section>
<InlineDemo />
<section>
<h1>Tests</h1>
<p>
<Icon
icon={homeIcon}
style={{
color: '#1769aa',
fontSize: '24px',
lineHeight: '1em',
verticalAlign: '-0.25em',
}}
/>
Home icon! 24px icon in 16px text with 24px line height,
aligned using inline style.
</p>
<p>
Empty icon (span): <Icon />
<br />
Empty icon (emoji): <Icon>😀</Icon>
</p>
<p>
Clickable icon (testing events and style): <CheckboxIcon />
</p>
<p>
Colored icons (block, inline, block):
<InlineIcon
icon={alertIcon}
style={{
fontSize: '1.5em',
verticalAlign: 0,
marginLeft: '8px',
}}
color="green"
/>
<InlineIcon
icon={alertIcon}
style={{
fontSize: '1.5em',
color: 'red',
marginLeft: '8px',
}}
/>
<Icon
icon={alertIcon}
style={{
fontSize: '1.5em',
color: 'purple',
marginLeft: '8px',
}}
/>
</p>
<p>
Testing reference by adding border to icon:{' '}
<Icon
icon="demo"
ref={(element) => {
console.log('Ref: valid icon');
element.style.border = '1px solid red';
}}
/>
<br />
Reference to missing icon:{' '}
<Icon
ref={(element) => {
console.log('Ref: missing icon');
element.style.border = '1px solid red';
}}
/>
<br />
Reference to missing icon with fallback text:{' '}
<Icon
ref={(element) => {
console.log('Ref: missing text icon');
element.style.border = '1px solid red';
}}
>
😀
</Icon>
</p>
<p>
Testing replacing ids in icons: <Icon icon="noto-robot" />{' '}
<Icon icon="noto-robot" /> (default handler)
<Icon icon="noto-robot" id="test1" />{' '}
<Icon icon="noto-robot" id="test2" /> (string)
</p>
</section>
</div>
);
}
export default App;

View File

@ -1,38 +0,0 @@
import React from 'react';
import { Icon } from '@iconify/react';
import checkedIcon from '@iconify-icons/uil/check-circle';
import uncheckedIcon from '@iconify-icons/uil/circle';
export class Checkbox extends React.Component {
constructor(props) {
super();
this.state = {
checked: props.checked,
};
this._check = this._check.bind(this);
}
render() {
const checked = this.state.checked;
const icon = checked ? checkedIcon : uncheckedIcon;
const className =
'checkbox checkbox--' + (checked ? 'checked' : 'unchecked');
return (
<div className="checkbox-container">
<a href="# " className={className} onClick={this._check}>
<Icon icon={icon} />
{this.props.text}
</a>
<small>{this.props.hint}</small>
</div>
);
}
_check(event) {
event.preventDefault();
this.setState({
checked: !this.state.checked,
});
}
}

View File

@ -1,27 +0,0 @@
import React from 'react';
import { Icon } from '@iconify/react';
export function InlineDemo() {
return (
<section className="inline-demo">
<h1>Inline (components/Inline.jsx)</h1>
<div>
Block icon (behaving like image):
<Icon icon="experiment2" />
</div>
<div>
Inline icon (behaving line text / icon font):
<Icon icon="experiment2" inline={true} />
</div>
<div>
Using "vertical-align: 0" to override inline attribute:
<Icon icon="experiment2" style={{ verticalAlign: 0 }} />
<Icon
icon="experiment2"
style={{ verticalAlign: 0 }}
inline={true}
/>
</div>
</section>
);
}

View File

@ -1,13 +0,0 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}

View File

@ -1,12 +0,0 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

View File

@ -1,141 +0,0 @@
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { 'Service-Worker': 'script' }
})
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready
.then(registration => {
registration.unregister();
})
.catch(error => {
console.error(error.message);
});
}
}

View File

@ -1,4 +0,0 @@
.DS_Store
node_modules
dist
lib

View File

@ -1,8 +0,0 @@
.DS_Store
api-extractor.json
rollup.config.js
tsconfig.json
build.js
node_modules
src
tests

View File

@ -1,44 +0,0 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
"mainEntryPointFilePath": "lib/icon.d.ts",
"bundledPackages": [
"@iconify/types",
"@iconify/core",
"@iconify/utils",
"@cyberalien/redundancy"
],
"compiler": {},
"apiReport": {
"enabled": false
},
"docModel": {
"enabled": false
},
"dtsRollup": {
"enabled": true,
"untrimmedFilePath": "<projectFolder>/dist/icon.d.ts"
},
"tsdocMetadata": {
"enabled": false
},
"messages": {
"compilerMessageReporting": {
"default": {
"logLevel": "warning"
}
},
"extractorMessageReporting": {
"default": {
"logLevel": "warning"
},
"ae-missing-release-tag": {
"logLevel": "none"
}
},
"tsdocMessageReporting": {
"default": {
"logLevel": "warning"
}
}
}
}

View File

@ -1,114 +0,0 @@
const fs = require('fs');
const path = require('path');
const child_process = require('child_process');
const packagesDir = path.dirname(path.dirname(__dirname)) + '/packages';
// List of commands to run
const commands = [];
// Parse command line
const compile = {
core: false,
lib: true,
dist: true,
api: true,
};
process.argv.slice(2).forEach((cmd) => {
if (cmd.slice(0, 2) !== '--') {
return;
}
const parts = cmd.slice(2).split('-');
if (parts.length === 2) {
// Parse 2 part commands like --with-lib
const key = parts.pop();
if (compile[key] === void 0) {
return;
}
switch (parts.shift()) {
case 'with':
// enable module
compile[key] = true;
break;
case 'without':
// disable module
compile[key] = false;
break;
case 'only':
// disable other modules
Object.keys(compile).forEach((key2) => {
compile[key2] = key2 === key;
});
break;
}
}
});
// Check if required modules in same monorepo are available
const fileExists = (file) => {
try {
fs.statSync(file);
} catch (e) {
return false;
}
return true;
};
if (compile.dist && !fileExists(packagesDir + '/react/lib/icon.js')) {
compile.lib = true;
}
if (compile.api && !fileExists(packagesDir + '/react/lib/icon.d.ts')) {
compile.lib = true;
}
if (compile.lib && !fileExists(packagesDir + '/core/lib/modules.js')) {
compile.core = true;
}
// Compile core before compiling this package
if (compile.core) {
commands.push({
cmd: 'npm',
args: ['run', 'build'],
cwd: packagesDir + '/core',
});
}
// Compile other packages
Object.keys(compile).forEach((key) => {
if (key !== 'core' && compile[key]) {
commands.push({
cmd: 'npm',
args: ['run', 'build:' + key],
});
}
});
/**
* Run next command
*/
const next = () => {
const item = commands.shift();
if (item === void 0) {
process.exit(0);
}
if (item.cwd === void 0) {
item.cwd = __dirname;
}
const result = child_process.spawnSync(item.cmd, item.args, {
cwd: item.cwd,
stdio: 'inherit',
});
if (result.status === 0) {
process.nextTick(next);
} else {
process.exit(result.status);
}
};
next();

File diff suppressed because it is too large Load Diff

View File

@ -1,39 +0,0 @@
{
"name": "@iconify/react-with-api",
"description": "Iconify icon component for React.",
"author": "Vjacheslav Trushkin <cyberalien@gmail.com> (https://iconify.design)",
"version": "1.0.0-rc.7",
"license": "MIT",
"bugs": "https://github.com/iconify/iconify/issues",
"homepage": "https://iconify.design/",
"repository": {
"type": "git",
"url": "https://github.com/iconify/iconify.git",
"directory": "packages/react-with-api"
},
"scripts": {
"build": "node build",
"build:lib": "tsc -b",
"build:dist": "rollup -c rollup.config.js",
"build:api": "api-extractor run --local --verbose"
},
"main": "dist/icon.js",
"module": "dist/icon.esm.js",
"types": "dist/icon.d.ts",
"devDependencies": {
"@babel/core": "^7.13.15",
"@babel/preset-env": "^7.13.15",
"@babel/preset-react": "^7.13.13",
"@iconify/core": "^1.1.0",
"@iconify/react": "^2.0.0-rc.8",
"@iconify/utils": "^1.0.0",
"@microsoft/api-extractor": "^7.13.5",
"@rollup/plugin-commonjs": "^18.0.0",
"@rollup/plugin-node-resolve": "^11.2.1",
"@types/react": "^17.0.3",
"react": "^17.0.2",
"rollup": "^2.45.2",
"rollup-plugin-terser": "^7.0.2",
"typescript": "^4.2.4"
}
}

View File

@ -1,325 +0,0 @@
# Iconify for React with API support
Iconify for React is not yet another icon component! There are many of them already.
Iconify is the most versatile icon framework.
- Unified icon framework that can be used with any icon library.
- Out of the box includes 80+ icon sets with more than 70,000 icons.
- Embed icons in HTML with SVG framework or components for front-end frameworks.
- Embed icons in designs with plug-ins for Figma, Sketch and Adobe XD.
- Add icon search to your applications with Iconify Icon Finder.
For more information visit [https://iconify.design/](https://iconify.design/).
Iconify for React is a part of Iconify framework that makes it easy to use many icon libraries with React.
Iconify for React features:
- Easy to use.
- Bundles only icons that you need.
- Change icon size and colour by changing font size and colour.
- Renders pixel-perfect SVG.
## Installation
If you are using NPM:
```bash
npm install --save-dev @iconify/react-with-api
```
If you are using Yarn:
```bash
yarn add --dev @iconify/react-with-api
```
This package does not include icons. Icons are split into separate packages that available at NPM. See below.
## Usage
Install `@iconify/react-with-api` and packages for selected icon sets. Import `Icon` and/or `InlineIcon` from `@iconify/react-with-api`.
### String syntax
String syntax passes icon name to the component.
```jsx
import React from 'react';
import { Icon, InlineIcon } from '@iconify/react-with-api';
export function MyComponent() {
return (
<div>
<Icon icon="mdi:home" />
</div>
);
}
```
Component will retrieve data for icon from Iconify API and render it.
### Offline usage
If you only want to use component offline, check out [@iconify/react](https://github.com/iconify/iconify/tree/master/packages/react) component.
This component can behave like `@iconify/react` too. Instead of icon names you can use icon data for icon you want to use:
```typescript
import { Icon, InlineIcon } from '@iconify/react-with-api';
import home from '@iconify-icons/mdi-light/home';
import faceWithMonocle from '@iconify-icons/twemoji/face-with-monocle';
```
Then use `Icon` or `InlineIcon` component with icon data as "icon" parameter:
```jsx
<Icon icon={home} />
<p>This is some text with <InlineIcon icon={faceWithMonocle} /></p>
```
## Icon and InlineIcon
Both components are the same, the only difference is `InlineIcon` has a negative vertical alignment, so it behaves like a glyph.
Use `Icon` for decorations, `InlineIcon` if you are migrating from glyph font.
Visual example to show the difference between inline and block modes:
![Inline icon](https://iconify.design/assets/images/inline.png)
## Icon component properties
`icon` property is mandatory. It tells component what icon to render. If the property value is invalid, the component will render an empty icon. The value can be a string containing the icon name (icon must be registered before use by calling `addIcon`, see instructions above) or an object containing the icon data.
The icon component has the following optional properties:
- `inline`. Changes icon behaviour to match icon fonts. See "Icon and InlineIcon" section above.
- `width` and `height`. Icon dimensions. The default values are "1em" for both. See "Dimensions" section below.
- `color`. Icon colour. This is the same as setting colour in style. See "Icon colour" section below.
- `flip`, `hFlip`, `vFlip`. Flip icon horizontally and/or vertically. See "Transformations" section below.
- `rotate`. Rotate icon by 90, 180 or 270 degrees. See "Transformations" section below.
- `align`, `vAlign`, `hAlign`, `slice`. Icon alignment. See "Alignment" section below.
### Other properties and events
In addition to the properties mentioned above, the icon component accepts any other properties and events. All other properties and events will be passed to generated `SVG` element, so you can do stuff like assigning `onClick` event, setting the inline style, add title and so on.
### Dimensions
By default, icon height is "1em". With is dynamic, calculated using the icon's width to height ratio. This makes it easy to change icon size by changing `[attr]font-size` in the stylesheet, just like icon fonts.
There are several ways to change icon dimensions:
- Setting `font-size` in style (or `fontSize` if you are using inline style).
- Setting `width` and/or `height` property.
Values for `width` and `height` can be numbers or strings.
If you set only one dimension, another dimension will be calculated using the icon's width to height ratio. For example, if the icon size is 16 x 24, you set the height to 48, the width will be set to 32. Calculations work not only with numbers, but also with string values.
#### Dimensions as numbers
You can use numbers for `width` and `height`.
```jsx
<Icon icon="mdi:home" height={24} />
```
```jsx
<Icon icon="mdi:home" width={16} height={16} />
```
Number values are treated as pixels. That means in examples above, values are identical to "24px" and "16px".
#### Dimensions as strings without units
If you use strings without units, they are treated the same as numbers in an example above.
```jsx
<Icon icon="mdi:home" height="24" />
```
```jsx
<Icon icon="mdi:home" width="16" height={'16'} />
```
#### Dimensions as strings with units
You can use units in width and height values:
```jsx
<Icon icon="mdi:home" height="2em" />
```
Be careful when using `calc`, view port based units or percentages. In SVG element they might not behave the way you expect them to behave and when using such units, you should consider settings both width and height.
#### Dimensions as 'auto'
Keyword "auto" sets dimensions to the icon's `viewBox` dimensions. For example, for 24 x 24 icon using `height="auto"` sets height to 24 pixels.
```jsx
<Icon icon="mdi:home" height="auto" />
```
### Icon colour
There are two types of icons: icons that do not have a palette and icons that do have a palette.
Icons that do have a palette, such as emojis, cannot be customised. Setting colour to such icons will not change anything.
Icons that do not have a palette can be customised. By default, colour is set to "currentColor", which means the icon's colour matches text colour. To change the colour you can:
- Set `color` style or use stylesheet to target icon. If you are using the stylesheet, target `svg` element.
- Add `color` property.
Examples:
Using `color` property:
```jsx
<Icon icon="mdi-light:alert" color="red" />
<Icon icon="mdi-light:alert" color="#f00" />
```
Using inline style:
```jsx
<Icon icon="mdi-light:alert" style={{color: 'red'}} />
<Icon icon="mdi-light:alert" style={{color: '#f00'}} />
```
Using stylesheet:
```jsx
<Icon icon="mdi-light:alert" className="red-icon" />
```
```css
.red-icon {
color: red;
}
```
### Transformations
You can rotate and flip the icon.
This might seem redundant because icon can also be rotated and flipped using CSS transformations. So why do transformation properties exist? Because it is a different type of transformation.
- CSS transformations transform the entire icon.
- Icon transformations transform the contents of the icon.
If you have a square icon, this makes no difference. However, if you have an icon that has different width and height values, it makes a huge difference.
Rotating 16x24 icon by 90 degrees results in:
- CSS transformation keeps 16x24 bounding box, which might cause the icon to overlap text around it.
- Icon transformation changes bounding box to 24x16, rotating content inside an icon.
_TODO: show visual example_
#### Flipping an icon
There are several properties available to flip an icon:
- `hFlip`: boolean property, flips icon horizontally.
- `vFlip`: boolean property, flips icon vertically.
- `flip`: shorthand string property, can flip icon horizontally and/or vertically.
Examples:
Flip an icon horizontally:
```jsx
<Icon icon="mdi-light:alert" hFlip={true} />
<Icon icon="mdi-light:alert" flip="horizontal" />
```
Flip an icon vertically:
```jsx
<Icon icon="mdi-light:alert" vFlip={true} />
<Icon icon="mdi-light:alert" flip="vertical" />
```
Flip an icon horizontally and vertically (the same as 180 degrees rotation):
```jsx
<Icon icon="mdi-light:alert" hFlip={true} vFlip={true} />
<Icon icon="mdi-light:alert" flip="horizontal,vertical" />
```
#### Rotating an icon
An icon can be rotated by 90, 180 and 270 degrees. Only contents of the icon are rotated.
To rotate an icon, use `rotate` property. Value can be a string (degrees or percentages) or a number.
Number values are 1 for 90 degrees, 2 for 180 degrees, 3 for 270 degrees.
Examples of 90 degrees rotation:
```jsx
<Icon icon="mdi-light:alert" rotate={1} />
<Icon icon="mdi-light:alert" rotate="90deg" />
<Icon icon="mdi-light:alert" rotate="25%" />
```
### Alignment
Alignment matters only if you set the icon's width and height properties that do not match the viewBox with and height.
For example, if the icon is 24x24 and you set the width to 32 and height to 24. You must set both `width` and `height` properties for this to happen or use stylesheet to set both icon's width and height.
#### Stretching SVG
When you use incorrect width/height ratio for other images, browser stretches those images.
Unlike other images, SVG elements do not stretch. Instead, browser either adds space on sides of the icon (this is the default behaviour) or crops part of the icon.
![Stretching image and SVG](https://iconify.design/assets/images/align-img.svg)
#### Alignment properties
You can control the behaviour of SVG when using incorrect width/height ratio by setting alignment properties:
- `hAlign`: string property to set horizontal alignment. Possible values are "left", "center" and "right".
- `vAlign`: string property to set vertical alignment. Possible values are "top", "middle" and "bottom".
- `slice`: boolean property. See below.
- `align`: shorthand string property. Value is the combination of vertical alignment values, horizontal alignment values, "meet" (same as `slice={false}`) and "slice" (same as `slice={true}`) separated by comma.
Example of aligning an icon to the left if icon is not square:
```jsx
<Icon icon="mdi-light:alert" width="1em" height="1em" hAlign="left" />
```
#### Slice
Slice property tells the browser how to deal with extra space.
By default, `slice` is disabled. The browser will scale the icon to fit the bounding box.
Example showing the icon behaviour when `slice` is disabled with various alignment values:
![SVG alignment](https://iconify.design/assets/images/align-meet.svg)
If `slice` is enabled, the browser will scale the icon to fill the bounding box and hide parts that do not fit.
Example showing the icon behaviour when `slice` is enabled with various alignment values:
![SVG alignment](https://iconify.design/assets/images/align-slice.svg)
## Icon Sets
There are over 50 icon sets. This readme shows only a few examples. See [Iconify icon sets](http://iconify.design/icon-sets/) for a full list of available icon sets. Click any icon to see code.
## License
React component is released with MIT license.
© 2020 Iconify OÜ
See [Iconify icon sets page](https://iconify.design/icon-sets/) for list of collections and their licenses.

View File

@ -1,79 +0,0 @@
import { writeFileSync, mkdirSync } from 'fs';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import { terser } from 'rollup-plugin-terser';
const name = 'icon';
// Write main file
const text = `'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./${name}.cjs.production.js')
} else {
module.exports = require('./${name}.cjs.development.js')
}
`;
try {
mkdirSync('dist', 0o755);
} catch (err) {}
writeFileSync(`dist/${name}.js`, text, 'utf8');
// Export configuration
const config = [
// Module
{
input: `lib/${name}.js`,
output: [
{
file: `dist/${name}.esm.js`,
format: 'esm',
},
],
external: ['react', 'axios'],
plugins: [
resolve(),
commonjs({
ignore: ['cross-fetch'],
}),
],
},
// Dev build
{
input: `lib/${name}.js`,
output: [
{
file: `dist/${name}.cjs.development.js`,
format: 'cjs',
},
],
external: ['react', 'axios'],
plugins: [
resolve(),
commonjs({
ignore: ['cross-fetch'],
}),
],
},
// Production
{
input: `lib/${name}.js`,
output: [
{
file: `dist/${name}.cjs.production.js`,
format: 'cjs',
},
],
external: ['react', 'axios'],
plugins: [
resolve(),
commonjs({
ignore: ['cross-fetch'],
}),
terser(),
],
},
];
export default config;

View File

@ -1,401 +0,0 @@
import React from 'react';
import { IconifyJSON } from '@iconify/types';
// Parent component
import {
IconProps,
Icon as ReactIcon,
InlineIcon as ReactInlineIcon,
} from '@iconify/react/lib/icon';
// Core
import { IconifyIconName, stringToIcon } from '@iconify/utils/lib/icon/name';
import {
IconifyIconCustomisations,
IconifyIconSize,
IconifyHorizontalIconAlignment,
IconifyVerticalIconAlignment,
} from '@iconify/utils/lib/customisations';
import {
IconifyStorageFunctions,
storageFunctions,
getIconData,
} from '@iconify/core/lib/storage/functions';
import {
IconifyBuilderFunctions,
builderFunctions,
} from '@iconify/core/lib/builder/functions';
import { IconifyIcon } from '@iconify/utils/lib/icon';
// Modules
import { coreModules } from '@iconify/core/lib/modules';
// API
import { API, IconifyAPIInternalStorage } from '@iconify/core/lib/api/';
import {
IconifyAPIFunctions,
IconifyAPIInternalFunctions,
APIFunctions,
APIInternalFunctions,
} from '@iconify/core/lib/api/functions';
import {
setAPIModule,
IconifyAPIModule,
IconifyAPISendQuery,
IconifyAPIPrepareQuery,
GetIconifyAPIModule,
} from '@iconify/core/lib/api/modules';
import { getAPIModule as getJSONPAPIModule } from '@iconify/core/lib/api/modules/jsonp';
import { getAPIModule as getFetchAPIModule } from '@iconify/core/lib/api/modules/fetch';
import {
setAPIConfig,
PartialIconifyAPIConfig,
IconifyAPIConfig,
getAPIConfig,
GetAPIConfig,
} from '@iconify/core/lib/api/config';
import {
IconifyIconLoaderCallback,
IconifyIconLoaderAbort,
} from '@iconify/core/lib/interfaces/loader';
// Cache
import { storeCache, loadCache } from '@iconify/core/lib/browser-storage';
import {
IconifyBrowserCacheType,
IconifyBrowserCacheFunctions,
toggleBrowserCache,
} from '@iconify/core/lib/browser-storage/functions';
/**
* Export required types
*/
// Function sets
export {
IconifyStorageFunctions,
IconifyBuilderFunctions,
IconifyBrowserCacheFunctions,
IconifyAPIFunctions,
IconifyAPIInternalFunctions,
};
// JSON stuff
export { IconifyIcon, IconifyJSON, IconifyIconName };
// Customisations
export {
IconifyIconCustomisations,
IconifyIconSize,
IconifyHorizontalIconAlignment,
IconifyVerticalIconAlignment,
};
// API
export {
IconifyAPIConfig,
IconifyIconLoaderCallback,
IconifyIconLoaderAbort,
IconifyAPIInternalStorage,
IconifyAPIModule,
GetAPIConfig,
IconifyAPIPrepareQuery,
IconifyAPISendQuery,
};
/* Browser cache */
export { IconifyBrowserCacheType };
/**
* Enable and disable browser cache
*/
export const enableCache = (storage: IconifyBrowserCacheType) =>
toggleBrowserCache(storage, true);
export const disableCache = (storage: IconifyBrowserCacheType) =>
toggleBrowserCache(storage, false);
/* Storage functions */
/**
* Check if icon exists
*/
export const iconExists = storageFunctions.iconExists;
/**
* Get icon data
*/
export const getIcon = storageFunctions.getIcon;
/**
* List available icons
*/
export const listIcons = storageFunctions.listIcons;
/**
* Add one icon
*/
export const addIcon = storageFunctions.addIcon;
/**
* Add icon set
*/
export const addCollection = storageFunctions.addCollection;
/* Builder functions */
/**
* Calculate icon size
*/
export const calculateSize = builderFunctions.calculateSize;
/**
* Replace unique ids in content
*/
export const replaceIDs = builderFunctions.replaceIDs;
/* API functions */
/**
* Load icons
*/
export const loadIcons = APIFunctions.loadIcons;
/**
* Add API provider
*/
export const addAPIProvider = APIFunctions.addAPIProvider;
/**
* Export internal functions that can be used by third party implementations
*/
export const _api = APIInternalFunctions;
/**
* Stateful component
*/
type IconPropsWithoutIcon = Pick<IconProps, Exclude<keyof IconProps, 'icon'>>;
interface StatefulProps extends IconPropsWithoutIcon {
icon: IconifyIconName;
func: typeof ReactIcon;
}
interface StatefulState {
loaded: boolean;
data: IconifyIcon | null;
}
/**
* Dynamic component
*/
class DynamicComponent extends React.Component<StatefulProps, StatefulState> {
protected _abort: IconifyIconLoaderAbort | null;
/**
* Set initial state
*/
constructor(props: StatefulProps) {
super(props);
this.state = {
loaded: false,
data: null,
};
}
/**
* Load icon data on mount
*/
componentDidMount() {
if (!this._loaded()) {
API.loadIcons([this.props.icon], this._loaded.bind(this));
}
}
/**
* Render
*/
render() {
const state = this.state;
if (!state.loaded) {
// Empty
return React.createElement('span');
}
// Replace icon in props with object
const props = this.props;
let newProps: IconProps = {} as IconProps;
Object.assign(newProps, props, {
icon: state.data,
});
delete newProps['func'];
delete newProps.ref;
return React.createElement(this.props.func, newProps);
}
/**
* Loaded
*/
_loaded(): boolean {
if (!this.state.loaded) {
const data = getIconData(this.props.icon);
if (data) {
this._abort = null;
this.setState({
loaded: true,
data,
});
return true;
}
return false;
}
return true;
}
/**
* Abort loading
*/
componentWillUnmount() {
if (this._abort) {
this._abort();
}
}
}
/**
* Render icon
*/
const component = (props: IconProps, func: typeof ReactIcon): JSX.Element => {
let iconData: IconifyIcon;
// Get icon data
if (typeof props.icon === 'string') {
const iconName = stringToIcon(props.icon, true);
if (!iconName) {
return React.createElement('span');
}
iconData = getIconData(iconName);
if (iconData) {
let staticProps: IconProps = {} as IconProps;
Object.assign(staticProps, props);
staticProps.icon = iconData;
return React.createElement(func, staticProps);
}
// Return dynamic component
const dynamicProps: StatefulProps = {} as StatefulProps;
Object.assign(dynamicProps, props, {
icon: iconName,
func,
});
return React.createElement(DynamicComponent, dynamicProps);
} else {
// Passed icon data as object: render @iconify/react component
return React.createElement(func, props);
}
};
/**
* Block icon
*
* @param props - Component properties
*/
export const Icon = (props: IconProps) => component(props, ReactIcon);
/**
* Inline icon (has negative verticalAlign that makes it behave like icon font)
*
* @param props - Component properties
*/
export const InlineIcon = (props: IconProps) =>
component(props, ReactInlineIcon);
/**
* Initialise stuff
*/
// Set API
coreModules.api = API;
let getAPIModule: GetIconifyAPIModule;
try {
getAPIModule =
typeof fetch === 'function' && typeof Promise === 'function'
? getFetchAPIModule
: getJSONPAPIModule;
} catch (err) {
getAPIModule = getJSONPAPIModule;
}
setAPIModule('', getAPIModule(getAPIConfig));
if (typeof document !== 'undefined' && typeof window !== 'undefined') {
// Set cache and load existing cache
coreModules.cache = storeCache;
loadCache();
const _window = window;
// Load icons from global "IconifyPreload"
interface WindowWithIconifyPreload {
IconifyPreload: IconifyJSON[] | IconifyJSON;
}
if (
(_window as unknown as WindowWithIconifyPreload).IconifyPreload !==
void 0
) {
const preload = (_window as unknown as WindowWithIconifyPreload)
.IconifyPreload;
const err = 'Invalid IconifyPreload syntax.';
if (typeof preload === 'object' && preload !== null) {
(preload instanceof Array ? preload : [preload]).forEach((item) => {
try {
if (
// Check if item is an object and not null/array
typeof item !== 'object' ||
item === null ||
item instanceof Array ||
// Check for 'icons' and 'prefix'
typeof item.icons !== 'object' ||
typeof item.prefix !== 'string' ||
// Add icon set
!addCollection(item)
) {
console.error(err);
}
} catch (e) {
console.error(err);
}
});
}
}
// Set API from global "IconifyProviders"
interface WindowWithIconifyProviders {
IconifyProviders: Record<string, PartialIconifyAPIConfig>;
}
if (
(_window as unknown as WindowWithIconifyProviders).IconifyProviders !==
void 0
) {
const providers = (_window as unknown as WindowWithIconifyProviders)
.IconifyProviders;
if (typeof providers === 'object' && providers !== null) {
for (let key in providers) {
const err = 'IconifyProviders[' + key + '] is invalid.';
try {
const value = providers[key];
if (
typeof value !== 'object' ||
!value ||
value.resources === void 0
) {
continue;
}
if (!setAPIConfig(key, value)) {
console.error(err);
}
} catch (e) {
console.error(err);
}
}
}
}
}

View File

@ -1,15 +0,0 @@
{
"compilerOptions": {
"rootDir": "./src",
"outDir": "./lib",
"target": "ES2019",
"module": "ESNext",
"declaration": true,
"sourceMap": false,
"strict": false,
"moduleResolution": "node",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true
}
}

View File

@ -1,3 +0,0 @@
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}

View File

@ -1,4 +0,0 @@
.DS_Store
node_modules
dist
lib

View File

@ -1,8 +0,0 @@
.DS_Store
api-extractor.json
rollup.config.js
tsconfig.json
build.js
node_modules
src
tests

View File

@ -1,44 +0,0 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
"mainEntryPointFilePath": "lib/icon.d.ts",
"bundledPackages": [
"@iconify/types",
"@iconify/core",
"@iconify/utils",
"@cyberalien/redundancy"
],
"compiler": {},
"apiReport": {
"enabled": false
},
"docModel": {
"enabled": false
},
"dtsRollup": {
"enabled": true,
"untrimmedFilePath": "<projectFolder>/dist/icon.d.ts"
},
"tsdocMetadata": {
"enabled": false
},
"messages": {
"compilerMessageReporting": {
"default": {
"logLevel": "warning"
}
},
"extractorMessageReporting": {
"default": {
"logLevel": "warning"
},
"ae-missing-release-tag": {
"logLevel": "none"
}
},
"tsdocMessageReporting": {
"default": {
"logLevel": "warning"
}
}
}
}

View File

@ -1,114 +0,0 @@
const fs = require('fs');
const path = require('path');
const child_process = require('child_process');
const packagesDir = path.dirname(path.dirname(__dirname)) + '/packages';
// List of commands to run
const commands = [];
// Parse command line
const compile = {
core: false,
lib: true,
dist: true,
api: true,
};
process.argv.slice(2).forEach((cmd) => {
if (cmd.slice(0, 2) !== '--') {
return;
}
const parts = cmd.slice(2).split('-');
if (parts.length === 2) {
// Parse 2 part commands like --with-lib
const key = parts.pop();
if (compile[key] === void 0) {
return;
}
switch (parts.shift()) {
case 'with':
// enable module
compile[key] = true;
break;
case 'without':
// disable module
compile[key] = false;
break;
case 'only':
// disable other modules
Object.keys(compile).forEach((key2) => {
compile[key2] = key2 === key;
});
break;
}
}
});
// Check if required modules in same monorepo are available
const fileExists = (file) => {
try {
fs.statSync(file);
} catch (e) {
return false;
}
return true;
};
if (compile.dist && !fileExists(packagesDir + '/react/lib/icon.js')) {
compile.lib = true;
}
if (compile.api && !fileExists(packagesDir + '/react/lib/icon.d.ts')) {
compile.lib = true;
}
if (compile.lib && !fileExists(packagesDir + '/core/lib/modules.js')) {
compile.core = true;
}
// Compile core before compiling this package
if (compile.core) {
commands.push({
cmd: 'npm',
args: ['run', 'build'],
cwd: packagesDir + '/core',
});
}
// Compile other packages
Object.keys(compile).forEach((key) => {
if (key !== 'core' && compile[key]) {
commands.push({
cmd: 'npm',
args: ['run', 'build:' + key],
});
}
});
/**
* Run next command
*/
const next = () => {
const item = commands.shift();
if (item === void 0) {
process.exit(0);
}
if (item.cwd === void 0) {
item.cwd = __dirname;
}
const result = child_process.spawnSync(item.cmd, item.args, {
cwd: item.cwd,
stdio: 'inherit',
});
if (result.status === 0) {
process.nextTick(next);
} else {
process.exit(result.status);
}
};
next();

View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2019, 2020 Vjacheslav Trushkin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

File diff suppressed because it is too large Load Diff

View File

@ -1,42 +0,0 @@
{
"name": "@iconify/react",
"description": "Iconify icon component for React.",
"author": "Vjacheslav Trushkin",
"version": "2.0.0-rc.9",
"license": "MIT",
"bugs": "https://github.com/iconify/iconify/issues",
"homepage": "https://iconify.design/",
"repository": {
"type": "git",
"url": "https://github.com/iconify/iconify.git",
"directory": "packages/react"
},
"scripts": {
"build": "node build",
"build:lib": "tsc -b",
"build:dist": "rollup -c rollup.config.js",
"build:api": "api-extractor run --local --verbose",
"pretest": "npm run build",
"test": "jest"
},
"main": "dist/icon.js",
"module": "dist/icon.esm.js",
"types": "dist/icon.d.ts",
"devDependencies": {
"@babel/preset-env": "^7.13.15",
"@babel/preset-react": "^7.13.13",
"@iconify/core": "^1.1.0",
"@iconify/utils": "^1.0.0",
"@microsoft/api-extractor": "^7.13.5",
"@rollup/plugin-commonjs": "^18.0.0",
"@rollup/plugin-node-resolve": "^11.2.1",
"@types/react": "^17.0.3",
"babel-jest": "^26.6.3",
"jest": "^26.6.3",
"react": "^17.0.2",
"react-test-renderer": "^17.0.2",
"rollup": "^2.45.2",
"rollup-plugin-terser": "^7.0.2",
"typescript": "^4.2.4"
}
}

View File

@ -1,484 +0,0 @@
# Iconify for React
Iconify for React is not yet another icon component! There are many of them already.
Iconify is the most versatile icon framework.
- Unified icon framework that can be used with any icon library.
- Out of the box includes 80+ icon sets with more than 70,000 icons.
- Embed icons in HTML with SVG framework or components for front-end frameworks.
- Embed icons in designs with plug-ins for Figma, Sketch and Adobe XD.
- Add icon search to your applications with Iconify Icon Finder.
For more information visit [https://iconify.design/](https://iconify.design/).
Iconify for React is a part of Iconify framework that makes it easy to use many icon libraries with React.
Iconify for React features:
- Easy to use.
- Bundles only icons that you need.
- Change icon size and colour by changing font size and colour.
- Renders pixel-perfect SVG.
## Installation
If you are using NPM:
```bash
npm install --save-dev @iconify/react
```
If you are using Yarn:
```bash
yarn add --dev @iconify/react
```
This package does not include icons. Icons are split into separate packages that available at NPM. See below.
## Usage
Install `@iconify/react` and packages for selected icon sets. Import `Icon` and/or `InlineIcon` from `@iconify/react` and icon data for icon you want to use:
```typescript
import { Icon, InlineIcon } from '@iconify/react';
import home from '@iconify-icons/mdi-light/home';
import faceWithMonocle from '@iconify-icons/twemoji/face-with-monocle';
```
Then use `Icon` or `InlineIcon` component with icon data as "icon" parameter:
```jsx
<Icon icon={home} />
<p>This is some text with <InlineIcon icon={faceWithMonocle} /></p>
```
### String syntax
String syntax passes icon name to the component.
With this method the icon needs to be added only once. That means if you have multiple components using 'home' icon, you can add it only in your main component. This makes it easy to swap icons for an entire application.
```jsx
import React from 'react';
import { Icon, addIcon } from '@iconify/react';
import homeIcon from '@iconify-icons/mdi-light/home';
addIcon('home', homeIcon);
export function MyComponent() {
return (
<div>
<Icon icon="home" />
</div>
);
}
```
Instead of adding icons one by one using `addIcon` function, you can import an entire icon set using `addCollection` function:
```jsx
import React from 'react';
import { Icon, addCollection } from '@iconify/react';
// Import requires bundler that can import JSON files
import jamIcons from '@iconify/json/json/jam.json';
// Function automatically adds prefix from icon set, which in this case is 'jam', followed by ':', so
// icon names added by function should be called with prefix, such as 'jam:home'
addCollection(jamIcons);
// Example without prefix, all icons will have names as is, such as 'home'
// addCollection(jamIcons, false);
export function MyComponent() {
return (
<div>
<Icon icon="jam:home" />
</div>
);
}
```
Example above imports an entire icon set. To learn how to create smaller bundles, check out Iconify documentation: https://docs.iconify.design/sources/bundles/
### Next.js notice
Code above will currently fail with Next.js. This is because Next.js uses outdated packaging software that does not support ES modules. But do not worry, there is a simple solution: switch to CommonJS icon packages.
To switch to CommonJS package, replace this line in example above:
```js
import homeIcon from '@iconify-icons/mdi-light/home';
```
with
```js
import homeIcon from '@iconify/icons-mdi-light/home';
```
All icons are available as ES modules for modern bundler and as CommonJS modules for outdated bundlers.
For more details, see "Icon packages" section below.
## Icon and InlineIcon
Both components are the same, the only difference is `InlineIcon` has a negative vertical alignment, so it behaves like a glyph.
Use `Icon` for decorations, `InlineIcon` if you are migrating from glyph font.
Visual example to show the difference between inline and block modes:
![Inline icon](https://iconify.design/assets/images/inline.png)
## Icon component properties
`icon` property is mandatory. It tells component what icon to render. If the property value is invalid, the component will render an empty icon. The value can be a string containing the icon name (icon must be registered before use by calling `addIcon` or `addCollection`, see instructions above) or an object containing the icon data.
The icon component has the following optional properties:
- `inline`. Changes icon behaviour to match icon fonts. See "Icon and InlineIcon" section above.
- `width` and `height`. Icon dimensions. The default values are "1em" for both. See "Dimensions" section below.
- `color`. Icon colour. This is the same as setting colour in style. See "Icon colour" section below.
- `flip`, `hFlip`, `vFlip`. Flip icon horizontally and/or vertically. See "Transformations" section below.
- `rotate`. Rotate icon by 90, 180 or 270 degrees. See "Transformations" section below.
- `align`, `vAlign`, `hAlign`, `slice`. Icon alignment. See "Alignment" section below.
### Other properties and events
In addition to the properties mentioned above, the icon component accepts any other properties and events. All other properties and events will be passed to generated `SVG` element, so you can do stuff like assigning `onClick` event, setting the inline style, add title and so on.
### Dimensions
By default, icon height is "1em". With is dynamic, calculated using the icon's width to height ratio. This makes it easy to change icon size by changing `font-size` in the stylesheet, just like icon fonts.
There are several ways to change icon dimensions:
- Setting `font-size` in style (or `fontSize` if you are using inline style).
- Setting `width` and/or `height` property.
Values for `width` and `height` can be numbers or strings.
If you set only one dimension, another dimension will be calculated using the icon's width to height ratio. For example, if the icon size is 16 x 24, you set the height to 48, the width will be set to 32. Calculations work not only with numbers, but also with string values.
#### Dimensions as numbers
You can use numbers for `width` and `height`.
```jsx
<Icon icon={homeIcon} height={24} />
```
```jsx
<Icon icon="experiment" width={16} height={16} />
```
Number values are treated as pixels. That means in examples above, values are identical to "24px" and "16px".
#### Dimensions as strings without units
If you use strings without units, they are treated the same as numbers in an example above.
```jsx
<Icon icon={homeIcon} height="24" />
```
```jsx
<Icon icon="experiment" width="16" height={'16'} />
```
#### Dimensions as strings with units
You can use units in width and height values:
```jsx
<Icon icon={homeIcon} height="2em" />
```
Be careful when using `calc`, view port based units or percentages. In SVG element they might not behave the way you expect them to behave and when using such units, you should consider settings both width and height.
#### Dimensions as 'auto'
Keyword "auto" sets dimensions to the icon's `viewBox` dimensions. For example, for 24 x 24 icon using `height="auto"` sets height to 24 pixels.
```jsx
<Icon icon={homeIcon} height="auto" />
```
### Icon colour
There are two types of icons: icons that do not have a palette and icons that do have a palette.
Icons that do have a palette, such as emojis, cannot be customised. Setting colour to such icons will not change anything.
Icons that do not have a palette can be customised. By default, colour is set to "currentColor", which means the icon's colour matches text colour. To change the colour you can:
- Set `color` style or use stylesheet to target icon. If you are using the stylesheet, target `svg` element.
- Add `color` property.
Examples:
Using `color` property:
```jsx
<Icon icon={alertIcon} color="red" />
<Icon icon={alertIcon} color="#f00" />
```
Using inline style:
```jsx
<Icon icon={alertIcon} style={{color: 'red'}} />
<Icon icon={alertIcon} style={{color: '#f00'}} />
```
Using stylesheet:
```jsx
<Icon icon={alertIcon} className="red-icon" />
```
```css
.red-icon {
color: red;
}
```
### Transformations
You can rotate and flip the icon.
This might seem redundant because icon can also be rotated and flipped using CSS transformations. So why do transformation properties exist? Because it is a different type of transformation.
- CSS transformations transform the entire icon.
- Icon transformations transform the contents of the icon.
If you have a square icon, this makes no difference. However, if you have an icon that has different width and height values, it makes a huge difference.
Rotating 16x24 icon by 90 degrees results in:
- CSS transformation keeps 16x24 bounding box, which might cause the icon to overlap text around it.
- Icon transformation changes bounding box to 24x16, rotating content inside an icon.
_TODO: show visual example_
#### Flipping an icon
There are several properties available to flip an icon:
- `hFlip`: boolean property, flips icon horizontally.
- `vFlip`: boolean property, flips icon vertically.
- `flip`: shorthand string property, can flip icon horizontally and/or vertically.
Examples:
Flip an icon horizontally:
```jsx
<Icon icon={alertIcon} hFlip={true} />
<Icon icon={alertIcon} flip="horizontal" />
```
Flip an icon vertically:
```jsx
<Icon icon={alertIcon} vFlip={true} />
<Icon icon={alertIcon} flip="vertical" />
```
Flip an icon horizontally and vertically (the same as 180 degrees rotation):
```jsx
<Icon icon={alertIcon} hFlip={true} vFlip={true} />
<Icon icon={alertIcon} flip="horizontal,vertical" />
```
#### Rotating an icon
An icon can be rotated by 90, 180 and 270 degrees. Only contents of the icon are rotated.
To rotate an icon, use `rotate` property. Value can be a string (degrees or percentages) or a number.
Number values are 1 for 90 degrees, 2 for 180 degrees, 3 for 270 degrees.
Examples of 90 degrees rotation:
```jsx
<Icon icon={alertIcon} rotate={1} />
<Icon icon={alertIcon} rotate="90deg" />
<Icon icon={alertIcon} rotate="25%" />
```
### Alignment
Alignment matters only if you set the icon's width and height properties that do not match the viewBox with and height.
For example, if the icon is 24x24 and you set the width to 32 and height to 24. You must set both `width` and `height` properties for this to happen or use stylesheet to set both icon's width and height.
#### Stretching SVG
When you use incorrect width/height ratio for other images, browser stretches those images.
Unlike other images, SVG elements do not stretch. Instead, browser either adds space on sides of the icon (this is the default behaviour) or crops part of the icon.
![Stretching image and SVG](https://iconify.design/assets/images/align-img.svg)
#### Alignment properties
You can control the behaviour of SVG when using incorrect width/height ratio by setting alignment properties:
- `hAlign`: string property to set horizontal alignment. Possible values are "left", "center" and "right".
- `vAlign`: string property to set vertical alignment. Possible values are "top", "middle" and "bottom".
- `slice`: boolean property. See below.
- `align`: shorthand string property. Value is the combination of vertical alignment values, horizontal alignment values, "meet" (same as `slice={false}`) and "slice" (same as `slice={true}`) separated by comma.
Example of aligning an icon to the left if icon is not square:
```jsx
<Icon icon="experiment" width="1em" height="1em" hAlign="left" />
```
#### Slice
Slice property tells the browser how to deal with extra space.
By default, `slice` is disabled. The browser will scale the icon to fit the bounding box.
Example showing the icon behaviour when `slice` is disabled with various alignment values:
![SVG alignment](https://iconify.design/assets/images/align-meet.svg)
If `slice` is enabled, the browser will scale the icon to fill the bounding box and hide parts that do not fit.
Example showing the icon behaviour when `slice` is enabled with various alignment values:
![SVG alignment](https://iconify.design/assets/images/align-slice.svg)
## Icon Packages
As of version 1.1.0 this package no longer includes icons. There are over 70k icons, each in its own file. That takes a lot of disc space. Because of that icons were moved to multiple separate packages, one package per icon set.
You can find all available icons at https://iconify.design/icon-sets/
Browse or search icons, click any icon and you will see a "React" tab that will give you exact code for the React component.
Import format for each icon is `@iconify-icons/{prefix}/{icon}` (for ES modules) or `@iconify/icons-{prefix}/{icon}` (for CommonJS modules), where `{prefix}` is collection prefix, and `{icon}` is the icon name.
Usage examples for a few popular icon packages:
### Material Design Icons
Package: https://www.npmjs.com/package/@iconify-icons/mdi
Icons list: https://iconify.design/icon-sets/mdi/
Installation:
```bash
npm install --save-dev @iconify-icons/mdi
```
Usage:
```js
import { Icon, InlineIcon } from '@iconify/react';
import home from '@iconify-icons/mdi/home';
import accountCheck from '@iconify-icons/mdi/account-check';
```
```jsx
<Icon icon={home} />
<p>This is some text with <InlineIcon icon={accountCheck} /></p>
```
### Simple Icons (big collection of logos)
Package: https://www.npmjs.com/package/@iconify-icons/simple-icons
Icons list: https://iconify.design/icon-sets/simple-icons/
Installation:
```bash
npm install --save-dev @iconify-icons/simple-icons
```
Usage:
```js
import { Icon, InlineIcon } from '@iconify/react';
import behanceIcon from '@iconify-icons/simple-icons/behance';
import mozillafirefoxIcon from '@iconify-icons/simple-icons/mozillafirefox';
```
```jsx
<Icon icon={behanceIcon} />
<p>
Mozilla Firefox <InlineIcon icon={mozillafirefoxIcon} /> is the best
browser!
</p>
```
### Font Awesome 5 Solid
Package: https://www.npmjs.com/package/@iconify-icons/fa-solid
Icons list: https://iconify.design/icon-sets/fa-solid/
Installation:
```bash
npm install --save-dev @iconify-icons/fa-solid
```
Usage:
```js
import { Icon, InlineIcon } from '@iconify/react';
import toggleOn from '@iconify-icons/fa-solid/toggle-on';
import chartBar from '@iconify-icons/fa-solid/chart-bar';
```
```jsx
<Icon icon={chartBar} />
<p><InlineIcon icon={toggleOn} /> Click to toggle</p>
```
### Noto Emoji
Package: https://www.npmjs.com/package/@iconify-icons/noto
Icons list: https://iconify.design/icon-sets/noto/
Installation:
```bash
npm install --save-dev @iconify-icons/noto
```
Usage:
```js
import { Icon, InlineIcon } from '@iconify/react';
import greenApple from '@iconify-icons/noto/green-apple';
import huggingFace from '@iconify-icons/noto/hugging-face';
```
```jsx
<Icon icon={greenApple} />
<p>Its time for hugs <InlineIcon icon={huggingFace} />!</p>
```
### Other icon sets
There are over 50 icon sets. This readme shows only a few examples. See [Iconify icon sets](http://iconify.design/icon-sets/) for a full list of available icon sets. Click any icon to see code.
## License
React component is released with MIT license.
© 2020 Iconify OÜ
See [Iconify icon sets page](https://iconify.design/icon-sets/) for list of collections and their licenses.

View File

@ -1,63 +0,0 @@
import { writeFileSync, mkdirSync } from 'fs';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import { terser } from 'rollup-plugin-terser';
const name = 'icon';
// Write main file
const text = `'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./${name}.cjs.production.js')
} else {
module.exports = require('./${name}.cjs.development.js')
}
`;
try {
mkdirSync('dist', 0o755);
} catch (err) {}
writeFileSync(`dist/${name}.js`, text, 'utf8');
// Export configuration
const config = [
// Module
{
input: `lib/${name}.js`,
output: [
{
file: `dist/${name}.esm.js`,
format: 'esm',
},
],
external: ['react'],
plugins: [resolve(), commonjs()],
},
// Dev build
{
input: `lib/${name}.js`,
output: [
{
file: `dist/${name}.cjs.development.js`,
format: 'cjs',
},
],
external: ['react'],
plugins: [resolve(), commonjs()],
},
// Production
{
input: `lib/${name}.js`,
output: [
{
file: `dist/${name}.cjs.production.js`,
format: 'cjs',
},
],
external: ['react'],
plugins: [resolve(), commonjs(), terser()],
},
];
export default config;

View File

@ -1,262 +0,0 @@
import type { HTMLProps, SVGProps } from 'react';
import React from 'react';
import type { IconifyIcon, IconifyJSON } from '@iconify/types';
import type {
IconifyIconCustomisations as IconCustomisations,
FullIconCustomisations,
IconifyHorizontalIconAlignment,
IconifyVerticalIconAlignment,
IconifyIconSize,
} from '@iconify/utils/lib/customisations';
import { defaults } from '@iconify/utils/lib/customisations';
import {
flipFromString,
alignmentFromString,
} from '@iconify/utils/lib/customisations/shorthand';
import { rotateFromString } from '@iconify/utils/lib/customisations/rotate';
import { fullIcon } from '@iconify/utils/lib/icon';
import { iconToSVG } from '@iconify/utils/lib/svg/build';
import { replaceIDs } from '@iconify/utils/lib/svg/id';
import { parseIconSet } from '@iconify/core/lib/icon/icon-set';
/**
* Export types that could be used in component
*/
export {
IconifyIcon,
IconifyJSON,
IconifyHorizontalIconAlignment,
IconifyVerticalIconAlignment,
IconifyIconSize,
};
// Allow rotation to be string
/**
* Icon customisations
*/
export type IconifyIconCustomisations = IconCustomisations & {
rotate?: string | number;
};
/**
* Icon properties
*/
export interface IconifyIconProps extends IconifyIconCustomisations {
// Icon object or icon name (must be added to storage using addIcon)
icon: IconifyIcon | string;
// Style
color?: string;
// Shorthand properties
flip?: string;
align?: string;
// Unique id, used as base for ids for shapes. Use it to get consistent ids for server side rendering
id?: string;
}
/**
* React component properties: generic element for Icon component, SVG for generated component
*/
type IconifyElementProps = HTMLProps<HTMLElement>;
type IconifySVGProps = SVGProps<SVGElement>;
interface ReactRefProp {
ref?: typeof React.createRef;
}
/**
* Mix of icon properties and HTMLElement properties
*/
export type IconProps = IconifyElementProps & IconifyIconProps & ReactRefProp;
/**
* Default SVG attributes
*/
const svgDefaults: IconifySVGProps = {
'xmlns': 'http://www.w3.org/2000/svg',
'xmlnsXlink': 'http://www.w3.org/1999/xlink',
'aria-hidden': true,
'role': 'img',
'style': {}, // Include style if it isn't set to add verticalAlign later
};
/**
* Default values for customisations for inline icon
*/
const inlineDefaults = { ...defaults, inline: true } as FullIconCustomisations;
/**
* Storage for icons referred by name
*/
const storage: Record<string, Required<IconifyIcon>> = Object.create(null);
/**
* Icon component
*
* @param props Component properties
* @param defaults Default values for customisations (defaults or inlineDefaults)
*/
const component = (
props: IconProps,
defaults: FullIconCustomisations,
ref
): JSX.Element => {
// Split properties
const icon =
typeof props.icon === 'string'
? storage[props.icon]
: typeof props.icon === 'object'
? fullIcon(props.icon)
: null;
// Validate icon object
if (
typeof icon !== 'object' ||
icon === null ||
typeof icon.body !== 'string'
) {
return props.children
? (props.children as JSX.Element)
: React.createElement('span', {});
}
const customisations = { ...defaults, props };
const componentProps = { ...svgDefaults };
// Add reference
componentProps.ref = ref;
// Create style if missing
const style = typeof props.style === 'object' ? props.style : {};
componentProps.style = style;
// Get element properties
for (let key in props) {
const value = props[key];
switch (key) {
// Properties to ignore
case 'icon':
case 'style':
break;
// Flip as string: 'horizontal,vertical'
case 'flip':
if (typeof value === 'string') {
flipFromString(customisations, value);
}
break;
// Alignment as string
case 'align':
if (typeof value === 'string') {
alignmentFromString(customisations, value);
}
break;
// Color: copy to style
case 'color':
style.color = value;
break;
// Rotation as string
case 'rotate':
if (typeof value === 'string') {
customisations[key] = rotateFromString(value);
} else if (typeof value === 'number') {
componentProps[key] = value;
}
break;
// Remove aria-hidden
case 'ariaHidden':
case 'aria-hidden':
if (value !== true && value !== 'true') {
delete componentProps['aria-hidden'];
}
break;
// Copy missing property if it does not exist in customisations
default:
if (defaults[key] === void 0) {
componentProps[key] = value;
}
}
}
// Generate icon
const item = iconToSVG(icon, customisations);
// Counter for ids based on "id" property to render icons consistently on server and client
let localCounter = 0;
const id = props.id;
// Add icon stuff
componentProps.dangerouslySetInnerHTML = {
__html: replaceIDs(
item.body,
id ? () => id + '-' + localCounter++ : 'iconify-react-'
),
};
for (let key in item.attributes) {
componentProps[key] = item.attributes[key];
}
if (item.inline && style.verticalAlign === void 0) {
style.verticalAlign = '-0.125em';
}
return React.createElement('svg', componentProps);
};
/**
* Block icon
*
* @param props - Component properties
*/
export const Icon = React.forwardRef((props: IconProps, ref?) =>
component(props, defaults, ref)
);
/**
* Inline icon (has negative verticalAlign that makes it behave like icon font)
*
* @param props - Component properties
*/
export const InlineIcon = React.forwardRef((props: IconProps, ref?) =>
component(props, inlineDefaults, ref)
);
/**
* Add icon to storage, allowing to call it by name
*
* @param name
* @param data
*/
export function addIcon(name: string, data: IconifyIcon): void {
storage[name] = fullIcon(data);
}
/**
* Add collection to storage, allowing to call icons by name
*
* @param data Icon set
* @param prefix Optional prefix to add to icon names, true if prefix from icon set should be used.
*/
export function addCollection(
data: IconifyJSON,
prefix?: string | boolean
): void {
const iconPrefix: string =
typeof prefix === 'string'
? prefix
: prefix !== false && typeof data.prefix === 'string'
? data.prefix + ':'
: '';
parseIconSet(data, (name, icon) => {
if (icon !== null) {
storage[iconPrefix + name] = icon;
}
});
}

View File

@ -1,527 +0,0 @@
import React from 'react';
import { Icon, InlineIcon, addIcon, addCollection } from '../';
import renderer from 'react-test-renderer';
const iconData = {
body:
'<path d="M4 19h16v2H4zm5-4h11v2H9zm-5-4h16v2H4zm0-8h16v2H4zm5 4h11v2H9z" fill="currentColor"/>',
width: 24,
height: 24,
};
const iconDataWithID = {
body:
'<defs><path id="ssvg-id-1st-place-medala" d="M.93.01h120.55v58.36H.93z"/><path id="ssvg-id-1st-place-medald" d="M.93.01h120.55v58.36H.93z"/><path id="ssvg-id-1st-place-medalf" d="M.93.01h120.55v58.36H.93z"/><path id="ssvg-id-1st-place-medalh" d="M.93.01h120.55v58.36H.93z"/><path id="ssvg-id-1st-place-medalj" d="M.93.01h120.55v58.36H.93z"/><path id="ssvg-id-1st-place-medalm" d="M.93.01h120.55v58.36H.93z"/><path d="M52.849 78.373v-3.908c3.681-.359 6.25-.958 7.703-1.798c1.454-.84 2.54-2.828 3.257-5.962h4.021v40.385h-5.437V78.373h-9.544z" id="ssvg-id-1st-place-medalp"/><linearGradient x1="49.998%" y1="-13.249%" x2="49.998%" y2="90.002%" id="ssvg-id-1st-place-medalb"><stop stop-color="#1E88E5" offset="13.55%"/><stop stop-color="#1565C0" offset="93.8%"/></linearGradient><linearGradient x1="26.648%" y1="2.735%" x2="77.654%" y2="105.978%" id="ssvg-id-1st-place-medalk"><stop stop-color="#64B5F6" offset="13.55%"/><stop stop-color="#2196F3" offset="94.62%"/></linearGradient><radialGradient cx="22.368%" cy="12.5%" fx="22.368%" fy="12.5%" r="95.496%" id="ssvg-id-1st-place-medalo"><stop stop-color="#FFEB3B" offset="29.72%"/><stop stop-color="#FBC02D" offset="95.44%"/></radialGradient></defs><g fill="none" fill-rule="evenodd"><g transform="translate(3 4)"><mask id="ssvg-id-1st-place-medalc" fill="#fff"><use xlink:href="#ssvg-id-1st-place-medala"/></mask><path fill="url(#ssvg-id-1st-place-medalb)" fill-rule="nonzero" mask="url(#ssvg-id-1st-place-medalc)" d="M45.44 42.18h31.43l30-48.43H75.44z"/></g><g transform="translate(3 4)"><mask id="ssvg-id-1st-place-medale" fill="#fff"><use xlink:href="#ssvg-id-1st-place-medald"/></mask><g opacity=".2" mask="url(#ssvg-id-1st-place-medale)" fill="#424242" fill-rule="nonzero"><path d="M101.23-3L75.2 39H50.85L77.11-3h24.12zm5.64-3H75.44l-30 48h31.42l30.01-48z"/></g></g><g transform="translate(3 4)"><mask id="ssvg-id-1st-place-medalg" fill="#fff"><use xlink:href="#ssvg-id-1st-place-medalf"/></mask><path d="M79 30H43c-4.42 0-8 3.58-8 8v16.04c0 2.17 1.8 3.95 4.02 3.96h.01c2.23-.01 4.97-1.75 4.97-3.96V44c0-1.1.9-2 2-2h30c1.1 0 2 .9 2 2v9.93c0 1.98 2.35 3.68 4.22 4.04c.26.05.52.08.78.08c2.21 0 4-1.79 4-4V38c0-4.42-3.58-8-8-8z" fill="#FDD835" fill-rule="nonzero" mask="url(#ssvg-id-1st-place-medalg)"/></g><g transform="translate(3 4)"><mask id="ssvg-id-1st-place-medali" fill="#fff"><use xlink:href="#ssvg-id-1st-place-medalh"/></mask><g opacity=".2" mask="url(#ssvg-id-1st-place-medali)" fill="#424242" fill-rule="nonzero"><path d="M79 32c3.31 0 6 2.69 6 6v16.04A2.006 2.006 0 0 1 82.59 56c-1.18-.23-2.59-1.35-2.59-2.07V44c0-2.21-1.79-4-4-4H46c-2.21 0-4 1.79-4 4v10.04c0 .88-1.64 1.96-2.97 1.96c-1.12-.01-2.03-.89-2.03-1.96V38c0-3.31 2.69-6 6-6h36zm0-2H43c-4.42 0-8 3.58-8 8v16.04c0 2.17 1.8 3.95 4.02 3.96h.01c2.23-.01 4.97-1.75 4.97-3.96V44c0-1.1.9-2 2-2h30c1.1 0 2 .9 2 2v9.93c0 1.98 2.35 3.68 4.22 4.04c.26.05.52.08.78.08c2.21 0 4-1.79 4-4V38c0-4.42-3.58-8-8-8z"/></g></g><g transform="translate(3 4)"><mask id="ssvg-id-1st-place-medall" fill="#fff"><use xlink:href="#ssvg-id-1st-place-medalj"/></mask><path fill="url(#ssvg-id-1st-place-medalk)" fill-rule="nonzero" mask="url(#ssvg-id-1st-place-medall)" d="M76.87 42.18H45.44l-30-48.43h31.43z"/></g><g transform="translate(3 4)"><mask id="ssvg-id-1st-place-medaln" fill="#fff"><use xlink:href="#ssvg-id-1st-place-medalm"/></mask><g opacity=".2" mask="url(#ssvg-id-1st-place-medaln)" fill="#424242" fill-rule="nonzero"><path d="M45.1-3l26.35 42H47.1L20.86-3H45.1zm1.77-3H15.44l30 48h31.42L46.87-6z"/></g></g><circle fill="url(#ssvg-id-1st-place-medalo)" fill-rule="nonzero" cx="64" cy="86" r="38"/><path d="M64 51c19.3 0 35 15.7 35 35s-15.7 35-35 35s-35-15.7-35-35s15.7-35 35-35zm0-3c-20.99 0-38 17.01-38 38s17.01 38 38 38s38-17.01 38-38s-17.01-38-38-38z" opacity=".2" fill="#424242" fill-rule="nonzero"/><path d="M47.3 63.59h33.4v44.4H47.3z"/><use fill="#000" xlink:href="#ssvg-id-1st-place-medalp"/><use fill="#FFA000" xlink:href="#ssvg-id-1st-place-medalp"/></g>',
width: 128,
height: 128,
};
describe('Creating component', () => {
test('basic icon', () => {
const component = renderer.create(<Icon icon={iconData} />);
const tree = component.toJSON();
expect(tree).toMatchObject({
type: 'svg',
props: {
'xmlns': 'http://www.w3.org/2000/svg',
'xmlnsXlink': 'http://www.w3.org/1999/xlink',
'aria-hidden': true,
'role': 'img',
'style': {},
'dangerouslySetInnerHTML': {
__html: iconData.body,
},
'width': '1em',
'height': '1em',
'preserveAspectRatio': 'xMidYMid meet',
'viewBox': '0 0 ' + iconData.width + ' ' + iconData.height,
},
children: null,
});
});
test('inline icon', () => {
const component = renderer.create(<InlineIcon icon={iconData} />);
const tree = component.toJSON();
expect(tree).toMatchObject({
type: 'svg',
props: {
'xmlns': 'http://www.w3.org/2000/svg',
'xmlnsXlink': 'http://www.w3.org/1999/xlink',
'aria-hidden': true,
'role': 'img',
'style': {
verticalAlign: '-0.125em',
},
'dangerouslySetInnerHTML': {
__html: iconData.body,
},
'width': '1em',
'height': '1em',
'preserveAspectRatio': 'xMidYMid meet',
'viewBox': '0 0 ' + iconData.width + ' ' + iconData.height,
},
children: null,
});
});
test('empty icon', () => {
const component = renderer.create(<Icon />);
const tree = component.toJSON();
expect(tree).toMatchObject({
type: 'span',
props: {},
children: null,
});
});
test('empty icon with children', () => {
// Missing 'icon' property, should render children
const component = renderer.create(
<Icon>
<i class="fa fa-home" />
</Icon>
);
const tree = component.toJSON();
expect(tree).toMatchObject({
type: 'i',
props: {},
children: null,
});
});
test('empty icon with text children', () => {
// Missing 'icon' property, should render children
const component = renderer.create(<Icon>icon</Icon>);
const tree = component.toJSON();
expect(tree).toMatch('icon');
});
});
describe('Using storage', () => {
test('using storage', () => {
addIcon('test-icon', iconData);
const component = renderer.create(<Icon icon="test-icon" />);
const tree = component.toJSON();
expect(tree).toMatchObject({
type: 'svg',
props: {
'xmlns': 'http://www.w3.org/2000/svg',
'xmlnsXlink': 'http://www.w3.org/1999/xlink',
'aria-hidden': true,
'role': 'img',
'style': {},
'dangerouslySetInnerHTML': {
__html: iconData.body,
},
'width': '1em',
'height': '1em',
'preserveAspectRatio': 'xMidYMid meet',
'viewBox': '0 0 ' + iconData.width + ' ' + iconData.height,
},
children: null,
});
});
test('using storage with icon set', () => {
const iconSet = {
prefix: 'mdi-light',
icons: {
account: {
body:
'<path d="M11.5 14c4.142 0 7.5 1.567 7.5 3.5V20H4v-2.5c0-1.933 3.358-3.5 7.5-3.5zm6.5 3.5c0-1.38-2.91-2.5-6.5-2.5S5 16.12 5 17.5V19h13v-1.5zM11.5 5a3.5 3.5 0 1 1 0 7a3.5 3.5 0 0 1 0-7zm0 1a2.5 2.5 0 1 0 0 5a2.5 2.5 0 0 0 0-5z" fill="currentColor"/>',
},
home: {
body:
'<path d="M16 8.414l-4.5-4.5L4.414 11H6v8h3v-6h5v6h3v-8h1.586L17 9.414V6h-1v2.414zM2 12l9.5-9.5L15 6V5h3v4l3 3h-3v7.998h-5v-6h-3v6H5V12H2z" fill="currentColor"/>',
},
},
width: 24,
height: 24,
};
addCollection(iconSet);
const component = renderer.create(<Icon icon="mdi-light:account" />);
const tree = component.toJSON();
expect(tree).toMatchObject({
type: 'svg',
props: {
'xmlns': 'http://www.w3.org/2000/svg',
'xmlnsXlink': 'http://www.w3.org/1999/xlink',
'aria-hidden': true,
'role': 'img',
'style': {},
'dangerouslySetInnerHTML': {
__html: iconSet.icons.account.body,
},
'width': '1em',
'height': '1em',
'preserveAspectRatio': 'xMidYMid meet',
'viewBox': '0 0 ' + iconSet.width + ' ' + iconSet.height,
},
children: null,
});
});
test('using storage with icon set with custom prefix', () => {
const iconSet = {
prefix: 'mdi-light',
icons: {
'account-alert': {
body:
'<path d="M10.5 14c4.142 0 7.5 1.567 7.5 3.5V20H3v-2.5c0-1.933 3.358-3.5 7.5-3.5zm6.5 3.5c0-1.38-2.91-2.5-6.5-2.5S4 16.12 4 17.5V19h13v-1.5zM10.5 5a3.5 3.5 0 1 1 0 7a3.5 3.5 0 0 1 0-7zm0 1a2.5 2.5 0 1 0 0 5a2.5 2.5 0 0 0 0-5zM20 16v-1h1v1h-1zm0-3V7h1v6h-1z" fill="currentColor"/>',
},
'link': {
body:
'<path d="M8 13v-1h7v1H8zm7.5-6a5.5 5.5 0 1 1 0 11H13v-1h2.5a4.5 4.5 0 1 0 0-9H13V7h2.5zm-8 11a5.5 5.5 0 1 1 0-11H10v1H7.5a4.5 4.5 0 1 0 0 9H10v1H7.5z" fill="currentColor"/>',
},
},
width: 24,
height: 24,
};
addCollection(iconSet, 'custom-');
const component = renderer.create(<Icon icon="custom-link" />);
const tree = component.toJSON();
expect(tree).toMatchObject({
type: 'svg',
props: {
'xmlns': 'http://www.w3.org/2000/svg',
'xmlnsXlink': 'http://www.w3.org/1999/xlink',
'aria-hidden': true,
'role': 'img',
'style': {},
'dangerouslySetInnerHTML': {
__html: iconSet.icons.link.body,
},
'width': '1em',
'height': '1em',
'preserveAspectRatio': 'xMidYMid meet',
'viewBox': '0 0 ' + iconSet.width + ' ' + iconSet.height,
},
children: null,
});
});
test('missing icon from storage', () => {
const component = renderer.create(<Icon icon="missing-icon" />);
const tree = component.toJSON();
expect(tree).toMatchObject({
type: 'span',
props: {},
children: null,
});
});
});
describe('Replacing IDs', () => {
test('default behavior', () => {
const component = renderer.create(<Icon icon={iconDataWithID} />);
const tree = component.toJSON();
const body = tree.props.dangerouslySetInnerHTML.__html;
expect(body).not.toStrictEqual(iconDataWithID.body);
});
test('custom generator', () => {
const component = renderer.create(
<Icon icon={iconDataWithID} id="test" />
);
const tree = component.toJSON();
const body = tree.props.dangerouslySetInnerHTML.__html;
// Generate expected body
let expected = iconDataWithID.body;
const replacements = {
'ssvg-id-1st-place-medala': 'test-0',
'ssvg-id-1st-place-medald': 'test-1',
'ssvg-id-1st-place-medalf': 'test-2',
'ssvg-id-1st-place-medalh': 'test-3',
'ssvg-id-1st-place-medalj': 'test-4',
'ssvg-id-1st-place-medalm': 'test-5',
'ssvg-id-1st-place-medalp': 'test-6',
'ssvg-id-1st-place-medalb': 'test-7',
'ssvg-id-1st-place-medalk': 'test-8',
'ssvg-id-1st-place-medalo': 'test-9',
'ssvg-id-1st-place-medalc': 'test-10',
'ssvg-id-1st-place-medale': 'test-11',
'ssvg-id-1st-place-medalg': 'test-12',
'ssvg-id-1st-place-medali': 'test-13',
'ssvg-id-1st-place-medall': 'test-14',
'ssvg-id-1st-place-medaln': 'test-15',
};
Object.keys(replacements).forEach((search) => {
expected = expected.replace(
new RegExp(search, 'g'),
replacements[search]
);
});
expect(body).toStrictEqual(expected);
});
});
describe('Passing attributes', () => {
test('title', () => {
const component = renderer.create(
<Icon icon={iconData} title="Icon!" />
);
const tree = component.toJSON();
expect(tree.props.title).toStrictEqual('Icon!');
});
test('aria-hidden', () => {
const component = renderer.create(
<InlineIcon icon={iconData} aria-hidden="false" />
);
const tree = component.toJSON();
expect(tree.props['aria-hidden']).toStrictEqual(void 0);
});
test('ariaHidden', () => {
const component = renderer.create(
<InlineIcon icon={iconData} ariaHidden="false" />
);
const tree = component.toJSON();
expect(tree.props['aria-hidden']).toStrictEqual(void 0);
});
test('style', () => {
const component = renderer.create(
<InlineIcon
icon={iconData}
style={{ verticalAlign: '0', color: 'red' }}
/>
);
const tree = component.toJSON();
expect(tree.props.style).toMatchObject({
verticalAlign: '0',
color: 'red',
});
});
test('color', () => {
const component = renderer.create(<Icon icon={iconData} color="red" />);
const tree = component.toJSON();
expect(tree.props.style).toMatchObject({
color: 'red',
});
});
test('color with style', () => {
const component = renderer.create(
<Icon icon={iconData} color="red" style={{ color: 'green' }} />
);
const tree = component.toJSON();
expect(tree.props.style).toMatchObject({
color: 'red',
});
});
test('attributes that cannot change', () => {
const component = renderer.create(
<InlineIcon
icon={iconData}
viewBox="0 0 0 0"
preserveAspectRatio="none"
/>
);
const tree = component.toJSON();
expect(tree.props.viewBox).toStrictEqual('0 0 24 24');
expect(tree.props.preserveAspectRatio).toStrictEqual('xMidYMid meet');
});
});
describe('Dimensions', () => {
test('height', () => {
const component = renderer.create(
<InlineIcon icon={iconData} height="48" />
);
const tree = component.toJSON();
expect(tree.props.height).toStrictEqual('48');
expect(tree.props.width).toStrictEqual('48');
});
test('width and height', () => {
const component = renderer.create(
<InlineIcon icon={iconData} width={32} height="48" />
);
const tree = component.toJSON();
expect(tree.props.height).toStrictEqual('48');
expect(tree.props.width).toStrictEqual('32');
});
test('auto', () => {
const component = renderer.create(
<InlineIcon icon={iconData} height="auto" />
);
const tree = component.toJSON();
expect(tree.props.height).toStrictEqual('24');
expect(tree.props.width).toStrictEqual('24');
});
});
describe('Rotation', () => {
test('number', () => {
const component = renderer.create(
<InlineIcon icon={iconData} rotate={1} />
);
const tree = component.toJSON();
const body = tree.props.dangerouslySetInnerHTML.__html;
expect(body).not.toStrictEqual(iconData.body);
expect(body).toMatch('rotate(90 ');
});
test('string', () => {
const component = renderer.create(
<InlineIcon icon={iconData} rotate="180deg" />
);
const tree = component.toJSON();
const body = tree.props.dangerouslySetInnerHTML.__html;
expect(body).not.toStrictEqual(iconData.body);
expect(body).toMatch('rotate(180 ');
});
});
describe('Flip', () => {
test('boolean', () => {
const component = renderer.create(
<InlineIcon icon={iconData} hFlip={true} />
);
const tree = component.toJSON();
const body = tree.props.dangerouslySetInnerHTML.__html;
expect(body).not.toStrictEqual(iconData.body);
expect(body).toMatch('scale(-1 1)');
});
test('string', () => {
const component = renderer.create(
<InlineIcon icon={iconData} flip="vertical" />
);
const tree = component.toJSON();
const body = tree.props.dangerouslySetInnerHTML.__html;
expect(body).not.toStrictEqual(iconData.body);
expect(body).toMatch('scale(1 -1)');
});
test('string and boolean', () => {
const component = renderer.create(
<InlineIcon icon={iconData} flip="horizontal" vFlip={true} />
);
const tree = component.toJSON();
const body = tree.props.dangerouslySetInnerHTML.__html;
expect(body).not.toStrictEqual(iconData.body);
// horizontal + vertical = 180deg rotation
expect(body).toMatch('rotate(180 ');
});
test('string for boolean attribute', () => {
const component = renderer.create(
<InlineIcon icon={iconData} hFlip="true" />
);
const tree = component.toJSON();
const body = tree.props.dangerouslySetInnerHTML.__html;
expect(body).not.toStrictEqual(iconData.body);
expect(body).toMatch('scale(-1 1)');
});
test('shorthand and boolean', () => {
// 'flip' is processed after 'hFlip', overwriting value
const component = renderer.create(
<InlineIcon icon={iconData} flip="horizontal" hFlip={false} />
);
const tree = component.toJSON();
const body = tree.props.dangerouslySetInnerHTML.__html;
expect(body).not.toStrictEqual(iconData.body);
expect(body).toMatch('scale(-1 1)');
});
test('shorthand and boolean as string', () => {
const component = renderer.create(
<InlineIcon icon={iconData} flip="vertical" hFlip="true" />
);
const tree = component.toJSON();
const body = tree.props.dangerouslySetInnerHTML.__html;
expect(body).not.toStrictEqual(iconData.body);
// horizontal + vertical = 180deg rotation
expect(body).toMatch('rotate(180 ');
});
test('wrong case', () => {
const component = renderer.create(
<InlineIcon icon={iconData} vflip={true} />
);
const tree = component.toJSON();
const body = tree.props.dangerouslySetInnerHTML.__html;
expect(body).not.toMatch('scale(');
});
});
describe('Alignment and slice', () => {
test('vAlign and slice', () => {
const component = renderer.create(
<InlineIcon icon={iconData} vAlign="top" slice={true} />
);
const tree = component.toJSON();
expect(tree.props.preserveAspectRatio).toStrictEqual('xMidYMin slice');
});
test('string', () => {
const component = renderer.create(
<InlineIcon icon={iconData} align="left bottom" />
);
const tree = component.toJSON();
expect(tree.props.preserveAspectRatio).toStrictEqual('xMinYMax meet');
});
});
describe('Inline attribute', () => {
test('string', () => {
const component = renderer.create(
<Icon icon={iconData} inline="true" />
);
const tree = component.toJSON();
expect(tree.props.style.verticalAlign).toStrictEqual('-0.125em');
});
test('false string', () => {
// "false" = true
const component = renderer.create(
<Icon icon={iconData} inline="false" />
);
const tree = component.toJSON();
expect(tree.props.style.verticalAlign).toStrictEqual('-0.125em');
});
});

View File

@ -1,15 +0,0 @@
{
"compilerOptions": {
"rootDir": "./src",
"outDir": "./lib",
"target": "ES2019",
"module": "ESNext",
"declaration": true,
"sourceMap": false,
"strict": false,
"moduleResolution": "node",
"esModuleInterop": true,
"importsNotUsedAsValues": "error",
"forceConsistentCasingInFileNames": true
}
}