2
0
mirror of https://github.com/iconify/iconify.git synced 2024-12-12 13:47:49 +00:00

Add React component with API support

This commit is contained in:
Vjacheslav Trushkin 2020-06-11 12:50:24 +03:00
parent 135bf723fb
commit 1cdd82f981
30 changed files with 23160 additions and 4 deletions

23
packages/react-demo-with-api/.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# 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

@ -0,0 +1,68 @@
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

@ -0,0 +1,34 @@
{
"name": "@iconify/react-demo-with-api",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.0"
},
"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.0.5",
"@iconify/react-with-api": "^1.0.0-beta.1"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

View File

@ -0,0 +1,43 @@
<!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.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

View File

@ -0,0 +1,25 @@
{
"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

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

View File

@ -0,0 +1,132 @@
.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;
}

135
packages/react-demo-with-api/src/App.js vendored Normal file
View File

@ -0,0 +1,135 @@
import React from 'react';
import { Icon, InlineIcon, enableCache } 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
enableCache('local', false);
enableCache('session', false);
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>
</section>
<InlineDemo />
</div>
);
}
export default App;

View File

@ -0,0 +1,39 @@
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

@ -0,0 +1,27 @@
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

@ -0,0 +1,13 @@
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

@ -0,0 +1,12 @@
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

@ -0,0 +1,141 @@
// 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

@ -19,8 +19,8 @@ export class Checkbox extends React.Component {
'checkbox checkbox--' + (checked ? 'checked' : 'unchecked');
return (
<div class="checkbox-container">
<a href="# " class={className} onClick={this._check}>
<div className="checkbox-container">
<a href="# " className={className} onClick={this._check}>
<Icon icon={icon} />
{this.props.text}
</a>

View File

@ -3,7 +3,7 @@ import { Icon } from '@iconify/react';
export function InlineDemo() {
return (
<section class="inline-demo">
<section className="inline-demo">
<h1>Inline (components/Inline.jsx)</h1>
<div>
Block icon (behaving like image):

4
packages/react-with-api/.gitignore vendored Normal file
View File

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

View File

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

View File

@ -0,0 +1,43 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
"mainEntryPointFilePath": "lib/icon.d.ts",
"bundledPackages": [
"@iconify/types",
"@iconify/core",
"@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"
}
}
}
}

114
packages/react-with-api/build.js vendored Normal file
View File

@ -0,0 +1,114 @@
const fs = require('fs');
const path = require('path');
const child_process = require('child_process');
const packagesDir = path.dirname(__dirname);
// 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();

7645
packages/react-with-api/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,50 @@
{
"name": "@iconify/react-with-api",
"description": "Iconify icon component for React.",
"author": "Vjacheslav Trushkin",
"version": "1.0.0-beta.1",
"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",
"peerDependencies": {
"react": "^16.0.0"
},
"devDependencies": {
"@babel/preset-env": "^7.10.1",
"@babel/preset-react": "^7.10.1",
"@cyberalien/redundancy": "^1.0.0",
"@iconify/core": "^1.0.0-beta.1",
"@iconify/iconify": "^2.0.0-beta.2",
"@iconify/react": "^2.0.0-beta.1",
"@iconify/types": "^1.0.3",
"@microsoft/api-extractor": "^7.8.8",
"@rollup/plugin-buble": "^0.21.3",
"@rollup/plugin-commonjs": "^11.1.0",
"@rollup/plugin-node-resolve": "^7.1.3",
"@types/react": "^16.9.35",
"babel-jest": "^25.5.1",
"jest": "^25.5.4",
"react": "^16.13.1",
"react-test-renderer": "^16.13.1",
"rollup": "^1.32.0",
"rollup-plugin-terser": "^5.3.0",
"typescript": "^3.9.3"
},
"dependencies": {
"axios": "^0.19.2"
}
}

View File

@ -0,0 +1,325 @@
# 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 60+ icon sets with 50,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.
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

@ -0,0 +1,64 @@
import { writeFileSync, mkdirSync } from 'fs';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import buble from '@rollup/plugin-buble';
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(), buble()],
},
// Dev build
{
input: `lib/${name}.js`,
output: [
{
file: `dist/${name}.cjs.development.js`,
format: 'cjs',
},
],
external: ['react', 'axios'],
plugins: [resolve(), commonjs(), buble()],
},
// Production
{
input: `lib/${name}.js`,
output: [
{
file: `dist/${name}.cjs.production.js`,
format: 'cjs',
},
],
external: ['react', 'axios'],
plugins: [resolve(), commonjs(), buble(), terser()],
},
];
export default config;

View File

@ -0,0 +1,489 @@
import { createElement, Component } from 'react';
import { IconifyJSON } from '@iconify/types';
// Parent component
import {
IconProps,
Icon as ReactIcon,
InlineIcon as ReactInlineIcon,
} from '@iconify/react/lib/icon';
// Core
import {
stringToIcon,
validateIcon,
IconifyIconName,
} from '@iconify/core/lib/icon/name';
import {
IconifyIconCustomisations,
IconifyIconSize,
IconifyHorizontalIconAlignment,
IconifyVerticalIconAlignment,
} from '@iconify/core/lib/customisations';
import {
getStorage,
getIcon,
addIcon as addIconToStorage,
addIconSet,
listStoredProviders,
listStoredPrefixes,
} from '@iconify/core/lib/storage';
import { calcSize } from '@iconify/core/lib/builder/calc-size';
import { IconifyIcon, FullIconifyIcon } from '@iconify/core/lib/icon';
// Modules
import { coreModules } from '@iconify/core/lib/modules';
// API
import {
API,
getRedundancyCache,
IconifyAPIInternalStorage,
} from '@iconify/core/lib/api/';
import {
setAPIModule,
IconifyAPIModule,
IconifyAPISendQuery,
IconifyAPIPrepareQuery,
} from '@iconify/core/lib/api/modules';
import { getAPIModule } from '@iconify/core/lib/api/modules/axios';
import {
setAPIConfig,
PartialIconifyAPIConfig,
IconifyAPIConfig,
getAPIConfig,
GetAPIConfig,
} from '@iconify/core/lib/api/config';
import {
IconifyIconLoaderCallback,
IconifyIconLoaderAbort,
IconifyLoadIcons,
} from '@iconify/core/lib/interfaces/loader';
// Cache
import { storeCache, loadCache, config } from '@iconify/core/lib/cache/storage';
/**
* Export required types
*/
// JSON stuff
export { IconifyIcon, IconifyJSON, IconifyIconName };
// Customisations
export {
IconifyIconCustomisations,
IconifyIconSize,
IconifyHorizontalIconAlignment,
IconifyVerticalIconAlignment,
};
// API
export {
IconifyAPIConfig,
IconifyIconLoaderCallback,
IconifyIconLoaderAbort,
IconifyAPIInternalStorage,
IconifyAPIModule,
GetAPIConfig,
IconifyAPIPrepareQuery,
IconifyAPISendQuery,
};
/**
* Exposed internal functions
*
* Used by plug-ins, such as Icon Finder
*
* Important: any changes published in a release must be backwards compatible.
*/
export interface IconifyExposedInternals {
/**
* Calculate width knowing height and width/height ratio (or vice versa)
*/
calculateSize: (
size: IconifyIconSize,
ratio: number,
precision?: number
) => IconifyIconSize;
/**
* Get internal API data, used by Icon Finder
*/
getAPI: (provider: string) => IconifyAPIInternalStorage | undefined;
/**
* Get API config, used by custom modules
*/
getAPIConfig: GetAPIConfig;
/**
* Set API module
*/
setAPIModule: (provider: string, item: IconifyAPIModule) => void;
}
/**
* Cache types
*/
export type IconifyCacheType = 'local' | 'session' | 'all';
/**
* Toggle cache
*/
export function enableCache(storage: IconifyCacheType, value: boolean): void {
switch (storage) {
case 'local':
case 'session':
config[storage] = value;
break;
case 'all':
for (const key in config) {
config[key] = value;
}
break;
}
}
/**
* Get icon name
*/
function _getIconName(name: string): IconifyIconName | null {
const icon = stringToIcon(name);
if (!validateIcon(icon)) {
return null;
}
return icon;
}
/**
* Get icon data
*/
function _getIconData(icon: IconifyIconName): FullIconifyIcon | null {
return getIcon(getStorage(icon.provider, icon.prefix), icon.name);
}
function getIconData(name: string): FullIconifyIcon | null {
const icon = _getIconName(name);
return icon ? _getIconData(icon) : null;
}
/**
* Check if icon exists
*/
export function iconExists(name: string): boolean {
return getIconData(name) !== null;
}
/**
* Load icons
*/
export const loadIcons: IconifyLoadIcons = API.loadIcons;
/**
* List available icons
*/
export function listIcons(provider?: string, prefix?: string): string[] {
let icons = [];
// Get providers
let providers: string[];
if (typeof provider === 'string') {
providers = [provider];
} else {
providers = listStoredProviders();
}
// Get all icons
providers.forEach((provider) => {
let prefixes: string[];
if (typeof prefix === 'string') {
prefixes = [prefix];
} else {
prefixes = listStoredPrefixes(provider);
}
prefixes.forEach((prefix) => {
const storage = getStorage(provider, prefix);
let icons = Object.keys(storage.icons).map(
(name) =>
(provider !== '' ? '@' + provider + ':' : '') +
prefix +
':' +
name
);
icons = icons.concat(icons);
});
});
return icons;
}
/**
* Add one icon
*/
export function addIcon(name: string, data: IconifyIcon): boolean {
const icon = _getIconName(name);
if (!icon) {
return false;
}
const storage = getStorage(icon.provider, icon.prefix);
return addIconToStorage(storage, icon.name, data);
}
/**
* Add icon set
*/
export function addCollection(data: IconifyJSON, provider?: string) {
if (typeof provider !== 'string') {
provider = typeof data.provider === 'string' ? data.provider : '';
}
if (
typeof data !== 'object' ||
typeof data.prefix !== 'string' ||
!validateIcon({
provider,
prefix: data.prefix,
name: 'a',
})
) {
return false;
}
const storage = getStorage(provider, data.prefix);
return !!addIconSet(storage, data);
}
/**
* Add API provider
*/
export { setAPIConfig as addAPIProvider };
/**
* Export internal functions that can be used by third party implementations
*/
export const internals: IconifyExposedInternals = {
// Calculate size
calculateSize: calcSize,
// Get API data
getAPI: getRedundancyCache,
// Get API config
getAPIConfig,
// Get API module
setAPIModule,
};
/**
* 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 Component<StatefulProps, StatefulState> {
protected _abort: IconifyIconLoaderAbort | null;
/**
* Set initial state
*/
constructor(props: StatefulProps) {
super(props);
this.state = {
loaded: false,
data: null,
};
API.loadIcons([props.icon], this._loaded.bind(this));
}
/**
* Render
*/
render() {
const state = this.state;
if (!state.loaded) {
// Empty
return null;
}
// Replace icon in props with object
let newProps: IconProps = {} as IconProps;
Object.assign(newProps, this.props, {
icon: state.data,
});
delete newProps['func'];
return this.props.func(newProps);
}
/**
* Loaded
*/
_loaded() {
if (!this.state.loaded) {
const data = _getIconData(this.props.icon);
if (data) {
this._abort = null;
this.setState({
loaded: true,
data,
});
}
}
}
/**
* 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 = _getIconName(props.icon);
if (!iconName) {
return null;
}
iconData = _getIconData(iconName);
if (iconData) {
let staticProps: IconProps = {} as IconProps;
Object.assign(staticProps, props);
staticProps.icon = iconData;
return func(staticProps);
}
// Return dynamic component
const dynamicProps: StatefulProps = {} as StatefulProps;
Object.assign(dynamicProps, props, {
icon: iconName,
func,
});
return createElement(DynamicComponent, dynamicProps);
} else {
return 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;
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

@ -0,0 +1,15 @@
{
"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

@ -40,7 +40,8 @@ export type IconifyIconCustomisations = IconCustomisations & {
* Icon properties
*/
export interface IconifyIconProps extends IconifyIconCustomisations {
icon: IconifyIcon;
// Icon object or icon name (must be added to storage using addIcon)
icon: IconifyIcon | string;
// Style
color?: string;