Compare commits

..
68 Commits
Author SHA1 Message Date
Adam Bradley df1f2881b1 4.0.0-4 2017-09-19 10:56:54 -05:00
Adam Bradley 3e25935c63 fix(package): add collection to package.json 2017-09-19 10:56:03 -05:00
Adam Bradley 5ff8fb2f3f 4.0.0-3 2017-09-18 22:14:43 -05:00
Adam Bradley af28cbcc2b chore(template): remove font version from template 2017-09-18 22:13:38 -05:00
Adam Bradley 6007fb4457 chore(cheatsheet): remove version from title 2017-09-18 22:10:26 -05:00
Adam Bradley 1d8400294a refactor(ion-icon): rename svj to js extension 2017-09-18 22:10:12 -05:00
Adam Bradley 2aa2e561d1 4.0.0-2 2017-09-18 21:48:57 -05:00
Adam Bradley e749624d2c chore(package): update package.json 2017-09-18 21:48:23 -05:00
Adam Bradley 9d89e3f458 docs(): init icon search 2017-09-18 21:31:08 -05:00
Adam Bradley 8a11016690 docs(): generate landing page with stencil 2017-09-18 20:41:28 -05:00
Adam Bradley 6b2151a03e chore(build): build svj files to dest 2017-09-18 20:38:25 -05:00
Adam Bradley 0a2ee33638 chore(): gitignore svj directory 2017-09-18 20:37:53 -05:00
Adam Bradley 06a3222d6e 4.0.0-1 2017-09-18 01:19:55 -05:00
Adam Bradley c3ac83aa40 chore(package): set any-branch for np 2017-09-18 01:19:27 -05:00
Adam Bradley 4c9c236964 chore(build): docs build updates 2017-09-18 01:18:27 -05:00
Adam Bradley 4a081f1f15 chore(src): update src svg 2017-09-18 00:42:15 -05:00
Adam Bradley f67a0713e2 chore(build): always rebuild fonts 2017-09-18 00:19:40 -05:00
Adam Bradley 984ac57a27 chore(ignore): add .vscode 2017-09-18 00:17:48 -05:00
Adam Bradley 6d03534441 chore(build): update generate font build 2017-09-17 23:33:44 -05:00
Adam Bradley a375680538 chore(icons): ignore icon svj files 2017-09-17 23:33:23 -05:00
Adam Bradley 99f8d90c3b chore(svg): update file locations 2017-09-17 23:14:29 -05:00
Adam Bradley 606f67910e fix(ion-icon): allow digits in ion-icon 2017-09-17 23:13:32 -05:00
Adam Bradley 4ef440df08 chore(scripts): update build scripts 2017-09-17 23:11:35 -05:00
Adam Bradley 028c3e5476 feat(png): generate png from source svg files 2017-09-17 23:09:53 -05:00
Adam Bradley c65d8c69bc docs(): move home to GH docs directory 2017-09-17 23:08:52 -05:00
Adam Bradley 9b0ca66a18 chore(scripts): update build scripts 2017-09-17 16:13:56 -05:00
Adam Bradley db177ab21d feat(icon): add ion-icon as custom element 2017-09-17 16:10:45 -05:00
Adam Bradley 0bf7d6b783 get version number from package.json 2016-01-14 10:35:52 -06:00
Adam Bradley b73d734201 npm updates 2016-01-14 09:43:56 -06:00
Adam Bradley ecb0d5c96e add woff2 fonts 2016-01-11 15:39:03 -06:00
Adam Bradley 79302a0b9d fix cheatsheet src 2016-01-11 14:50:56 -06:00
Adam Bradley 12300dac5e create dist directory 2016-01-11 13:22:08 -06:00
Adam Bradley 201bc5778b rename all-icons.json to ionicons.json 2016-01-11 12:57:16 -06:00
Adam Bradley b75f861668 fix tags 2016-01-11 12:52:53 -06:00
Adam Bradley ea169967cb rename logos icons to have a logo- prefix 2016-01-11 12:29:08 -06:00
Drew Rygh a75338ac3e add ionic-site ionicons docs generator script 2016-01-07 17:14:29 -06:00
Adam Bradley e9d0838d28 generate all-icons.json 2016-01-07 13:47:02 -06:00
Adam Bradley f7cbd32f05 rename social- icons to -logo 2016-01-06 20:15:20 -06:00
Ben Sperry 2af58c0f48 Fix ios-image icon 2016-01-06 19:31:51 -06:00
Ben Sperry 2bfe41388a Fix md-ribbon icon 2016-01-06 19:30:02 -06:00
Ben Sperry 04c9fd88e2 update iOS calendar outline 2016-01-06 19:27:18 -06:00
Ben Sperry 3473f8dac3 Update iOS train icon 2016-01-06 19:21:26 -06:00
Ben Sperry 6b2acac269 Update iOS image icon 2016-01-06 19:20:20 -06:00
Adam Bradley 0e45dfeba2 update 2016-01-06 14:02:45 -06:00
Ben Sperry ee6989821b Remove circle from iOS build icon 2016-01-06 13:59:59 -06:00
Adam Bradley babadeb8cc updates 2016-01-06 13:56:12 -06:00
Ben Sperry a7f2173cf8 never really changed anything in this 2016-01-06 13:40:40 -06:00
Ben Sperry abd0223ae2 Update md-shirt and fix md-ribbon 2016-01-06 13:18:23 -06:00
Ben Sperry 7177db4df1 Update md-ionic icon
to new platform version
2016-01-06 13:09:44 -06:00
Ben Sperry 0be7dfd7d0 Fix md-contrast icon 2016-01-06 13:05:37 -06:00
Ben Sperry e98da5c90a Update to iOS image icon 2016-01-06 12:33:00 -06:00
Ben Sperry 45fca56e32 Fix iOS build icon 2016-01-06 11:19:25 -06:00
Adam Bradley b87025c880 reuse icons for iOS icons w/out outline versions 2016-01-06 10:40:09 -06:00
Ben Sperry 1f4109e35e Update Facebook social icon 2015-12-16 13:29:32 -06:00
Adam Bradley d40d07e441 svgo wip 2015-11-23 17:19:06 -06:00
Ben Sperry 584679c4f4 Update iOS cog outline icon
improve form, reduce fill
2015-10-29 13:46:04 -05:00
Ben Sperry bf6e69f6c3 Update the iOS snow icon to have an outline version 2015-10-29 12:25:12 -05:00
Ben Sperry 650450c5e4 Fix some weather icons
Partly Sunny and Thunderstorm were actin’ a fool!
2015-10-28 19:58:24 -05:00
Ben Sperry e9b1c01db1 Update iOS beer icon
removed extra shape inside the handle
2015-09-29 14:41:31 -05:00
Ben Sperry 7572fc3b9b Add "link" icon
Added a link/url icon for both iOS and Android
2015-09-04 12:05:22 -05:00
Adam Bradley e6659421e5 platform "more" icon 2015-09-03 11:19:26 -05:00
Ben Sperry f8211c19dd Normalized the "more" icon between platoforms
removed the vertical style for iOS, and horizontal style for Android
2015-09-03 11:10:53 -05:00
Ben Sperry 6122fe6799 Update to "tux"
Made into smaller file size
2015-09-03 10:21:01 -05:00
Adam Bradley 8b00d184de update build 2015-09-03 09:50:17 -05:00
Ben Sperry f635f6dcd3 Update to iOS shirt icon 2015-09-03 09:49:35 -05:00
Adam Bradley ad4a3020d6 update 3.0 build 2015-09-03 09:40:17 -05:00
Ben Sperry 77850954c5 New pack!
Icons for 3.0
2015-09-03 09:37:52 -05:00
Adam Bradley e33e6cb500 init v3.0 2015-09-03 09:32:35 -05:00
2318 changed files with 109152 additions and 29316 deletions
-32
View File
@@ -1,32 +0,0 @@
name: 🐛 Bug Report
description: Report a bug in the ion-icon component. Incorrect icons should use the "Incorrect Icon" template instead.
labels: ['triage']
title: 'bug: '
body:
- type: textarea
attributes:
label: Current Behavior
description: A clear description of what the bug is and how it manifests.
validations:
required: true
- type: textarea
attributes:
label: Expected Behavior
description: A clear description of what you expected to happen.
validations:
required: true
- type: textarea
attributes:
label: Steps to Reproduce
description: Please explain the steps required to duplicate this issue.
validations:
required: true
- type: input
attributes:
label: Code Reproduction URL
description: Please provide an application with the minimum code required to reproduce the issue. This is the best way to ensure this issue is triaged quickly. Issues without a code reproduction may be closed if the Ionic Team cannot reproduce the issue you are reporting.
placeholder: https://github.com/...
- type: textarea
attributes:
label: Additional Information
description: List any other information that is relevant to your issue. Stack traces, related issues, suggestions on how to fix, Stack Overflow links, forum links, etc.
@@ -1,23 +0,0 @@
name: 💡 Feature Request
description: Suggest a new feature for the ion-icon component. Icon requests should use the "Icon Request" template instead.
labels: ['triage']
title: 'feat: '
body:
- type: textarea
attributes:
label: Describe Problem
description: A clear and concise description of what the problem is. Ex. I am always frustrated when [...]
validations:
required: true
- type: textarea
attributes:
label: Describe Preferred Solution
description: A clear and concise description of what you want to happen.
- type: textarea
attributes:
label: Describe Alternatives
description: A clear and concise description of any alternative solutions or features you have considered.
- type: textarea
attributes:
label: Additional Information
description: Add any other context or screenshots about the feature request here.
-19
View File
@@ -1,19 +0,0 @@
name: 🚀 Icon Request
description: Request a new icon
labels: ['triage']
title: 'icon request: '
body:
- type: textarea
attributes:
label: Describe the Icon
description: A clear and concise description of the icon you would like added.
validations:
required: true
- type: textarea
attributes:
label: Links to Examples
description: Add links to any examples of the icon in other libraries that you like.
- type: textarea
attributes:
label: Additional Information
description: Add any other context about the icon request here.
-17
View File
@@ -1,17 +0,0 @@
name: 😒 Incorrect Icon
description: Report an incorrect icon
labels: ['triage']
title: 'incorrect icon: '
body:
- type: textarea
attributes:
label: Describe the Issue
description: A clear description of what is wrong with the icon. Please include any relevant screenshots.
validations:
required: true
- type: textarea
attributes:
label: Expected Behavior
description: A clear description of what the icon should look like. Please include any relevant screenshots.
validations:
required: true
-105
View File
@@ -1,105 +0,0 @@
triage:
label: triage
dryRun: false
closeAndLock:
labels:
- label: 'ionitron: support'
message: >
Thanks for the issue! This issue appears to be a support request. We use this issue tracker exclusively for
bug reports and feature requests. Please use our [forum](https://forum.ionicframework.com/) for help or
questions about Ionicons.
Thank you for using Ionicons!
- label: 'ionitron: missing template'
message: >
Thanks for the issue! It appears that you have not filled out the provided issue template. We use this issue
template in order to gather more information and further assist you. Please create a new issue and ensure the
template is fully filled out.
Thank you for using Ionicons!
close: true
lock: true
dryRun: false
comment:
labels:
- label: 'help wanted'
message: >
This issue has been labeled as `help wanted`. This label is added to issues
that we believe would be good for contributors.
If you'd like to work on this issue, please comment here letting us know that
you would like to submit a pull request for it. This helps us to keep track of
the pull request and make sure there isn't duplicated effort.
For a guide on how to create a pull request and test this project locally to see
your changes, see our [contributing documentation](https://github.com/ionic-team/ionicons/blob/main/.github/CONTRIBUTING.md#creating-a-pull-request).
Thank you!
- label: 'ionitron: needs reproduction'
message: >
Thanks for the issue! This issue has been labeled as `needs reproduction`. This label is added to issues that
need a code reproduction.
Please reproduce this issue and provide a way for us to access it (GitHub repo, StackBlitz, etc). Without a
reliable code reproduction, it is unlikely we will be able to resolve the issue, leading to it being closed.
If you have already provided a code snippet and are seeing this message, it is likely that the code snippet was
not enough for our team to reproduce the issue.
- label: 'community feedback wanted'
message: >
This issue has been labeled as `community feedback wanted`. This label is added to issues that we would like to hear from the community on before moving forward with any final decision on the feature request.
If the requested feature is something you would find useful for your applications, please react to the original post with 👍 (`+1`). If you would like to provide an additional use case for the feature, please post a comment.
The team will review this feedback and make a final decision. Any decision will be posted on this thread, but please note that we may ultimately decide not to pursue this feature.
Thank you!
dryRun: false
noReply:
days: 14
maxIssuesPerRun: 100
label: 'needs: reply'
responseLabel: triage
exemptProjects: true
exemptMilestones: true
message: >
Thanks for the issue! This issue is being closed due to the lack of a reply. If this is still
an issue with the latest version of Ionicons, please create a new issue and ensure the
template is fully filled out.
Thank you for using Ionicons!
close: true
lock: true
dryRun: false
noReproduction:
days: 14
maxIssuesPerRun: 100
label: 'ionitron: needs reproduction'
responseLabel: triage
exemptProjects: true
exemptMilestones: true
message: >
Thanks for the issue! This issue is being closed due to the lack of a code reproduction. If this is still
an issue with the latest version of Ionicons, please create a new issue and ensure the
template is fully filled out.
Thank you for using Ionicons!
close: true
lock: true
dryRun: false
@@ -1,34 +0,0 @@
name: 'Build Ionicons'
description: 'Build Ionicons'
runs:
using: 'composite'
steps:
- uses: actions/checkout@v4
with:
# Checkout the latest commit in this branch
ref: ${{ github.event.pull_request.head.sha }}
- uses: actions/setup-node@v4
- name: Cache Node Modules
uses: actions/cache@v4
env:
cache-name: node-modules
with:
path: ./node_modules
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('./package-lock.json') }}-v1
- name: Install Dependencies
run: npm install
shell: bash
- name: Build
run: npm run build
shell: bash
- uses: ./.github/workflows/actions/upload-archive
with:
name: ionicons-build
output: IoniconsBuild.zip
paths: dist components icons www
- uses: ./.github/workflows/actions/upload-archive
with:
name: ionicons-src
output: IoniconsSrc.zip
paths: src
@@ -1,19 +0,0 @@
name: 'Archive Download'
description: 'Downloads and decompresses an archive from a previous job'
inputs:
path:
description: 'Input archive name'
filename:
description: 'Input file name'
name:
description: 'Archive name'
runs:
using: 'composite'
steps:
- uses: actions/download-artifact@v4
with:
name: ${{ inputs.name }}
path: ${{ inputs.path }}
- name: Exract Archive
run: unzip -q -o ${{ inputs.path }}/${{ inputs.filename }}
shell: bash
@@ -1,63 +0,0 @@
name: 'Release'
description: 'Releases a package'
inputs:
version:
description: 'The type of version to release.'
tag:
description: 'The tag to publish to on NPM.'
working-directory:
description: 'The directory of the package.'
folder:
default: './'
description: 'A folder containing a package.json file.'
createRelease:
description: 'Create a release on GitHub.'
default: 'false'
ghToken:
description: 'The GitHub authentication token required to create a release.'
runs:
using: 'composite'
steps:
- uses: actions/setup-node@v4
with:
node-version: 22.x
- name: Install latest npm
run: npm install -g npm@latest
shell: bash
- name: Install Dependencies
run: npm ci
shell: bash
working-directory: ${{ inputs.working-directory }}
- name: Set Git User
run: |
git config user.name ionitron
git config user.email hi@ionicframework.com
shell: bash
- name: Update Version
id: update_version
run: |
npm version ${{ inputs.version }}
echo "VERSION=$(node -p "require('./package.json').version")" >> $GITHUB_ENV
shell: bash
working-directory: ${{ inputs.working-directory }}
- name: Run Build
run: npm run build
shell: bash
working-directory: ${{ inputs.working-directory }}
- name: Publish to NPM
run: npm publish ${{ inputs.folder }} --tag ${{ inputs.tag }} --provenance
shell: bash
working-directory: ${{ inputs.working-directory }}
- name: Create Release
if: ${{ inputs.createRelease == 'true' }}
run: |
git remote set-url origin https://${GH_TOKEN}:x-oauth-basic@github.com/ionic-team/ionicons.git
git remote -v
git push origin main --tags
gh release create "v$VERSION" --title "v$VERSION" --generate-notes
shell: bash
env:
GH_TOKEN: ${{ inputs.ghToken }}
VERSION: ${{ env.VERSION }}
@@ -1,84 +0,0 @@
name: 'Test E2E'
description: 'Test E2E'
inputs:
shard:
description: 'Playwright Test Shard (ex: 2)'
totalShards:
description: 'Playwright total number of test shards (ex: 4)'
update:
description: 'Whether or not to update the reference snapshots'
runs:
using: 'composite'
steps:
- uses: actions/setup-node@v4
- name: Cache Node Modules
uses: actions/cache@v4
env:
cache-name: node-modules
with:
path: ./node_modules
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('./package-lock.json') }}-v1
- uses: ./.github/workflows/actions/download-archive
with:
name: ionicons-build
path: .
filename: IoniconsBuild.zip
- uses: ./.github/workflows/actions/download-archive
with:
name: ionicons-src
path: .
filename: IoniconsSrc.zip
- name: Install Playwright Dependencies
run: npx playwright install && npx playwright install-deps
shell: bash
- name: Test
if: inputs.update != 'true'
run: npx playwright test --shard=${{ inputs.shard }}/${{ inputs.totalShards }}
shell: bash
- name: Test and Update
id: test-and-update
if: inputs.update == 'true'
# Keep track of the files that were
# changed so they can be correctly restored
# in the combine step.
# To do this, we move only the changed files
# to a separate directory, while preserving the
# directory structure of the source.
# When, we create and archive of these results
# so that the combine step can simply
# unzip and move the changed files into place.
# We have extra logic added so that job runners
# that do not have any new screenshots do not create
# an unnecessary .zip.
run: |
npx playwright test --shard=${{ inputs.shard }}/${{ inputs.totalShards }} --update-snapshots
git add src/\*.png --force
mkdir updated-screenshots
rsync -R --progress $(git diff --name-only --cached) updated-screenshots
if [ "$(ls -A updated-screenshots)" ]; then
echo "hasUpdatedScreenshots=$(echo 'true')" >> $GITHUB_OUTPUT
cd updated-screenshots
ls
zip -q -r ../UpdatedScreenshots-${{ inputs.shard }}-${{ inputs.totalShards }}.zip ./
fi
shell: bash
- name: Archive Updated Screenshots
if: inputs.update == 'true' && steps.test-and-update.outputs.hasUpdatedScreenshots == 'true'
uses: actions/upload-artifact@v4
with:
name: updated-screenshots-${{ inputs.shard }}-${{ inputs.totalShards }}
path: UpdatedScreenshots-${{ inputs.shard }}-${{ inputs.totalShards }}.zip
- name: Archive Test Results
# The always() ensures that this step
# runs even if the previous step fails.
# We want the test results to be archived
# even if the test fails in the previous
# step, otherwise there would be no way
# to debug these tests.
if: always()
uses: ./.github/workflows/actions/upload-archive
with:
name: test-results-${{ inputs.shard }}-${{ inputs.totalShards }}
output: TestResults-${{ inputs.shard }}-${{ inputs.totalShards }}.zip
paths: playwright-report
@@ -1,22 +0,0 @@
name: 'Test Spec'
description: 'Test Spec'
runs:
using: 'composite'
steps:
- uses: actions/setup-node@v4
- name: Cache Node Modules
uses: actions/cache@v4
env:
cache-name: node-modules
with:
path: ./node_modules
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('./package-lock.json') }}-v1
- uses: ./.github/workflows/actions/download-archive
with:
name: ionicons-build
path: .
filename: IoniconsBuild.zip
- name: Test
run: npm run test.spec -- --ci
shell: bash
@@ -1,38 +0,0 @@
name: 'Update Reference Screenshots'
description: 'Update Reference Screenshots'
on:
workflow_dispatch:
runs:
using: 'composite'
steps:
- uses: actions/setup-node@v4
- uses: actions/download-artifact@v4
with:
path: ./artifacts
- name: Extract Archives
# This finds all .zip files in the ./artifacts
# directory, including nested directories.
# It then unzips every .zip to the root directory
run: |
find . -type f -name 'UpdatedScreenshots-*.zip' -exec unzip -q -o -d ../ {} \;
shell: bash
working-directory: ./artifacts
- name: Push Screenshots
# Configure user as Ionitron
# and push only the changed .png snapshots
# to the remote branch.
# Screenshots are in .gitignore
# to prevent local screenshots from getting
# pushed to Git. As a result, we need --force
# here so that CI generated screenshots can
# get added to git. Screenshot ground truths
# should only be added via this CI process.
run: |
git config user.name ionitron
git config user.email hi@ionicframework.com
git add src/\*.png --force
git commit -m "chore(): add updated snapshots"
git push
shell: bash
@@ -1,19 +0,0 @@
name: 'Archive Upload'
description: 'Compresses and uploads an archive to be reused across jobs'
inputs:
paths:
description: 'Paths to files or directories to archive'
output:
description: 'Output file name'
name:
description: 'Archive name'
runs:
using: 'composite'
steps:
- name: Create Archive
run: zip -q -r ${{ inputs.output }} ${{ inputs.paths }}
shell: bash
- uses: actions/upload-artifact@v4
with:
name: ${{ inputs.name }}
path: ${{ inputs.output }}
-43
View File
@@ -1,43 +0,0 @@
name: 'Dev Release'
on:
workflow_call:
jobs:
create-dev-hash:
runs-on: ubuntu-latest
outputs:
dev-hash: ${{ steps.create-dev-hash.outputs.DEV_HASH }}
steps:
- uses: actions/checkout@v4
- name: Install Dependencies
run: npm ci --no-package-lock
shell: bash
- id: create-dev-hash
name: Create Dev Hash
run: |
echo "DEV_HASH=$(node ./scripts/bump-version.js)-dev.1$(date +%s).1$(git log -1 --format=%H | cut -c 1-7)" >> $GITHUB_OUTPUT
shell: bash
release-ionicons:
runs-on: ubuntu-latest
needs: [create-dev-hash]
permissions:
id-token: write
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Publish to NPM
uses: ./.github/workflows/actions/publish-npm
with:
tag: dev
version: ${{ needs.create-dev-hash.outputs.dev-hash }}
working-directory: './'
createRelease: 'false'
get-build:
name: Get your dev build!
runs-on: ubuntu-latest
needs: [create-dev-hash, release-ionicons]
steps:
- run: echo ${{ needs.create-dev-hash.outputs.dev-hash }}
-28
View File
@@ -1,28 +0,0 @@
name: 'Production Release'
on:
workflow_call:
inputs:
version:
required: false
type: string
description: npm version (major, minor, or patch)
jobs:
release-ionicons:
runs-on: ubuntu-latest
permissions:
id-token: write
steps:
- name: Checkout
uses: actions/checkout@v4
with:
token: ${{ secrets.IONITRON_TOKEN }}
- name: Publish to NPM
uses: ./.github/workflows/actions/publish-npm
with:
tag: latest
version: ${{ inputs.version }}
working-directory: './'
createRelease: true
ghToken: ${{ secrets.IONITRON_TOKEN }}
@@ -1,37 +0,0 @@
name: 'Release Orchestrator'
on:
workflow_dispatch:
inputs:
release-type:
description: 'Release type'
required: true
type: choice
options:
- dev
- production
version:
description: 'Version for production releases'
required: false
type: choice
options:
- patch
- minor
- major
permissions:
id-token: write
contents: read
jobs:
run-dev:
if: ${{ inputs.release-type == 'dev' }}
uses: ./.github/workflows/dev-release.yml
secrets: inherit
run-production:
if: ${{ inputs.release-type == 'production' }}
uses: ./.github/workflows/production-release.yml
secrets: inherit
with:
version: ${{ inputs.version }}
-52
View File
@@ -1,52 +0,0 @@
name: 'Update Reference Screenshots'
on:
workflow_dispatch:
jobs:
build-core:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: ./.github/workflows/actions/build-core
test-e2e:
strategy:
# This ensures that all screenshot shard
# failures are reported so the dev can
# review everything at once.
fail-fast: false
matrix:
# Divide the tests into n buckets
# and run those buckets in parallel.
# To increase the number of shards,
# add new items to the shard array
# and change the value of totalShards
# to be the length of the shard array.
shard: [1, 2, 3]
totalShards: [3]
needs: [build-core]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: ./.github/workflows/actions/test-e2e
with:
shard: ${{ matrix.shard }}
totalShards: ${{ matrix.totalShards }}
update: true
update-reference-screenshots:
runs-on: ubuntu-latest
needs: [test-e2e]
steps:
- uses: actions/checkout@v4
# Normally, we could just push with the
# default GITHUB_TOKEN, but that will
# not cause the build workflow
# to re-run. We use Ionitron's
# Personal Access Token instead
# to allow for this build workflow
# to run when the screenshots are pushed.
with:
token: ${{ secrets.IONITRON_TOKEN }}
- uses: ./.github/workflows/actions/update-reference-screenshots
-73
View File
@@ -1,73 +0,0 @@
name: 'Validation'
on:
pull_request:
branches: ['**']
push:
branches: ['main']
# When pushing a new commit we should
# cancel the previous test run to not
# consume more runners than we need to.
concurrency:
group: ${{ github.ref }}
cancel-in-progress: true
jobs:
build-core:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
# Checkout the latest commit in this branch
ref: ${{ github.event.pull_request.head.sha }}
- uses: ./.github/workflows/actions/build-core
test-spec:
needs: [build-core]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: ./.github/workflows/actions/test-spec
test-e2e:
strategy:
# This ensures that all screenshot shard
# failures are reported so the dev can
# review everything at once.
fail-fast: false
matrix:
# Divide the tests into n buckets
# and run those buckets in parallel.
# To increase the number of shards,
# add new items to the shard array
# and change the value of totalShards
# to be the length of the shard array.
shard: [1, 2, 3]
totalShards: [3]
needs: [build-core]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: ./.github/workflows/actions/test-e2e
with:
shard: ${{ matrix.shard }}
totalShards: ${{ matrix.totalShards }}
# Screenshots are required to pass
# in order for the branch to be merge
# eligible. However, the screenshot tests
# are run on n runners where n can change
# over time. The verify-screenshots step allows
# us to have a required status check for screenshot
# results without having to manually add each
# matrix run in the branch protection rules
# Source: https://github.community/t/status-check-for-a-matrix-jobs/127354
verify-e2e:
if: ${{ always() }}
needs: test-e2e
runs-on: ubuntu-latest
steps:
- name: Check build matrix status
if: ${{ needs.test-e2e.result != 'success' }}
run: exit 1
+7 -27
View File
@@ -1,27 +1,7 @@
*~
*.sw[mnpcod]
*.log
*.lock
*.tmp
*.tmp.*
log.txt
*.sublime-project
*.sublime-workspace
.idea/
.versions/
.vscode/
/components/
node_modules/
tmp/
dist/
icons/
.DS_Store
scripts/*.js
!scripts/install-loader.js
www/
/test-results/
/playwright-report/
/playwright/.cache/
/src/**/*-snapshots
*.tgz
.vscode
.sass-cache
*.scssc
*.swp
node_modules
dist
tmp
-1
View File
@@ -1 +0,0 @@
src/components.d.ts
-13
View File
@@ -1,13 +0,0 @@
{
"arrowParens": "always",
"bracketSpacing": true,
"jsxBracketSameLine": false,
"jsxSingleQuote": false,
"quoteProps": "consistent",
"printWidth": 120,
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "all",
"useTabs": false
}
-3
View File
@@ -1,3 +0,0 @@
# Change Log
Please see https://github.com/ionic-team/ionicons/releases
-11
View File
@@ -1,11 +0,0 @@
# Contributor Code of Conduct
As contributors and maintainers of the Ionicons project, we pledge to respect everyone who contributes by posting issues, updating documentation, submitting pull requests, providing feedback in comments, and any other activities.
Communication through any of Ionic's channels (GitHub, Slack, Forum, IRC, mailing lists, Twitter, etc.) must be constructive and never resort to personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
We promise to extend courtesy and respect to everyone involved in this project regardless of gender, gender identity, sexual orientation, disability, age, race, ethnicity, religion, or level of experience. We expect anyone contributing to the Ionicons project to do the same.
If any member of the community violates this code of conduct, the maintainers of the Ionicons project may take action, removing issues, comments, and PRs or blocking accounts as deemed appropriate.
If you are subject to or witness unacceptable behavior, or have any other concerns, please email us at [hi@ionicframework.com](mailto:hi@ionicframework.com).
-196
View File
@@ -1,196 +0,0 @@
# Contributing to Ionicons
Thank you for your interest in contributing to Ionicons! :tada:
This document outlines the guidelines and processes for contributing to this project.
## Table of Contents
- [Code of Conduct](#code-of-conduct)
- [Getting Started](#getting-started)
* [Prerequisites](#prerequisites)
* [Environment Setup](#environment-setup)
- [Development Workflow](#development-workflow)
* [Branch Strategy](#branch-strategy)
* [Component Modifications](#component-modifications)
* [Testing](#testing)
* [Code Style](#code-style)
* [Building](#building)
- [Submitting Issues](#submitting-issues)
- [Submitting Pull Requests](#submitting-pull-requests)
## Code of Conduct
Please read our [Contributor Code of Conduct](./CODE_OF_CONDUCT.md) for information on our rules of conduct. By contributing to Ionicons, you agree to abide by its terms.
## Getting Started
### Prerequisites
- [Node.js](https://nodejs.org/) (LTS version recommended)
- [npm](https://www.npmjs.com/) (comes with Node.js)
- Git
### Environment Setup
1. We recommend using [nvm](https://github.com/nvm-sh/nvm) (Node Version Manager) to manage Node.js versions:
- For macOS/Linux: `curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash`
- For Windows: Use [nvm-windows](https://github.com/coreybutler/nvm-windows)
- Install and use the LTS version: `nvm install --lts && nvm use --lts`
Alternatively, you can [download the installer](https://nodejs.org/) for the LTS version of Node.js directly.
2. Fork the repository on GitHub
3. Clone your fork locally:
```bash
git clone https://github.com/YOUR-USERNAME/ionicons.git
cd ionicons
```
4. Add the original repository as an upstream remote:
```bash
git remote add upstream https://github.com/ionic-team/ionicons.git
```
5. Create a new branch from `main` for your change:
```bash
git checkout -b your-feature-branch
```
6. Install dependencies:
```bash
npm install
```
7. Run the initial build:
```bash
npm run build
```
8. If desired, [modify the Icon Component](#component-modifications)
9. Or, modify and preview the site
## Development Workflow
### Branch Strategy
- Always create a new branch from `main` for your changes:
```bash
git checkout main
git pull upstream main
git checkout -b your-feature-branch
```
### Component Modifications
If you're modifying the `ion-icon` component:
1. Navigate to `src/components/` directory and open the `icon` component to modify
2. Make your changes to the component code
3. Test your changes locally with `npm start`
4. Run the full test suite: `npm run test.spec` for unit tests and `npm run test.e2e` for E2E tests
5. All PRs that change component behavior must include tests covering the changes
### Testing
Tests are crucial for maintaining confidence in changes. All PRs that modify component behavior must include tests covering those changes.
#### Local Development & Previewing
To preview component changes during development:
```bash
npm start
```
This starts the dev server with live-reloading. The test landing page displays all available test pages.
Test pages are organized in `src/components/icon/test/` with individual folders for each test scenario.
#### Unit Tests
Run Jest tests for component logic:
```bash
npm run test.spec
```
#### E2E Tests
Run Playwright tests to generate visual regression snapshots and verify component behavior:
```bash
npm run test.e2e
```
View the HTML report after tests complete:
```bash
npx playwright show-report
```
> [!IMPORTANT]
> All E2E test navigation URLs must include a trailing slash (e.g., `/icon/test/basic/` not `/icon/test/basic`). The trailing slash ensures proper directory routing, correct timing for script initialization, and consistent page loading across browsers.
##### Updating Snapshots
To update visual regression snapshots with new baselines:
```bash
npm run test.e2e -- --update-snapshots
```
Or for a specific test:
```bash
npm run test.e2e -- src/components/icon/test/basic/icon.e2e.ts --update-snapshots
```
> [!NOTE]
> Updating snapshots locally updates your gitignored screenshot files for local testing. To update the official repository snapshots, run the "Update Reference Screenshots" GitHub action with your development branch selected.
### Code Style
- This project uses Prettier for code formatting
- Run `npm run prettier` to format your code before submitting
### Building
- Run `npm run build` to build the complete package
- Run `npm run build.files` to rebuild only the SVG icon files
## Submitting Issues
Please submit issues for:
- Bug reports
- Feature requests
- General questions about the project
When creating issues:
1. If you have a question about using Ionicons, please ask on the [Ionic Forum](http://forum.ionicframework.com/) or in the [Ionic Discord](https://ionic.link/discord).
2. It is required that you clearly describe the steps necessary to reproduce the issue you are running into. Although we would love to help our users as much as possible, diagnosing issues without clear reproduction steps is extremely time-consuming and simply not sustainable.
3. The issue list of this repository is exclusively for bug reports and feature requests. Non-conforming issues will be closed immediately.
4. Check if a similar issue already exists by searching through [existing issues](https://github.com/ionic-team/ionicons/issues?utf8=%E2%9C%93&q=is%3Aissue). You can search through existing issues to see if there is a similar one reported. Include closed issues as it may have been closed with a solution.
5. Use the provided issue templates and clearly describe:
- Expected behavior
- Actual behavior
- Steps to reproduce (for bugs)
- Browser/device information when relevant
6. [Create a new issue](https://github.com/ionic-team/ionicons/issues/new/choose) that thoroughly explains the problem.
## Submitting Pull Requests
1. Before submitting a Pull Request (PR), please:
- Create an issue first to discuss the proposed changes
- Comment on an existing issue mentioning you'd like to work on it
- Look for issues labeled with [`help wanted`](https://github.com/ionic-team/ionicons/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22) if you're new to the project
2. Creating the PR:
- Update your fork to the latest upstream main
- Make your changes in a new git branch
- Follow the code style of the project
- Include relevant tests
- Make sure all tests pass: `npm test`
- Update documentation if needed
- [Create a new pull request](https://github.com/ionic-team/ionicons/compare) with the `main` branch as the base.
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

+32
View File
@@ -0,0 +1,32 @@
/*! Built with http://stenciljs.com */
(function (window, document, appNamespace, publicPath, appCore, appCorePolyfilled, components, x, i) {
'use strict';
// create global namespace if it doesn't already exist
(window[appNamespace] = window[appNamespace] || {}).components = components = components || [];
// auto hide components until they been fully hydrated
// reusing the "x" variable from the args for funzies
x = document.createElement('style');
x.setAttribute('data-styles', '');
x.innerHTML = (components.map(function (c) {
return c[0];
}).join(',') + '{visibility:hidden}.💎{visibility:inherit}').toLowerCase();
document.head.insertBefore(x, document.head.firstChild);
// get this current script
appNamespace = appNamespace.toLowerCase();
x = document.scripts;
for (i = x.length - 1; i >= 0; i--) {
if (x[i].src && x[i].src.split('/').pop() === appNamespace + '.js') {
publicPath = x[i].src.replace(appNamespace + '.js', appNamespace + '/');
break;
}
}
// request the core this browser needs
// test for native support of custom elements and fetch
// if either of those are not supported, then use the core w/ polyfills
x = document.createElement('script');
x.src = publicPath + (window.customElements && window.fetch ? appCore : appCorePolyfilled);
x.setAttribute('data-path', publicPath);
x.setAttribute('data-core', appCore);
document.head.appendChild(x);
})(window, document, "DocsSite","/build/docssite/","docssite.core.js","docssite.core.pf.js",[["ICON-SEARCH","icon-search",{"$":"icon-search"},0,[["focusin","focusin"],["focusout","focusout"],["keyup","keyup"]]],["LANDING-PAGE","landing-page",{"$":"landing-page"}]]);
+37
View File
@@ -0,0 +1,37 @@
{
"namespace": "DocsSite",
"components": [
[
"ICON-SEARCH",
"icon-search",
{
"$": "icon-search"
},
0,
[
[
"focusin",
"focusin"
],
[
"focusout",
"focusout"
],
[
"keyup",
"keyup"
]
]
],
[
"LANDING-PAGE",
"landing-page",
{
"$": "landing-page"
}
]
],
"loader": "docssite.js",
"core": "docssite/docssite.core.js",
"corePolyfilled": "docssite/docssite.core.pf.js"
}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+4
View File
@@ -0,0 +1,4 @@
/*! Built with http://stenciljs.com */
icon-search.💎 {
visibility: inherit;
}
+45
View File
@@ -0,0 +1,45 @@
/*! Built with http://stenciljs.com */
DocsSite.loadComponents(
/**** module id (dev mode) ****/
"icon-search",
/**** component modules ****/
function importComponent(exports, h, t, Context, publicPath) {
var LandingPage = /** @class */ (function () {
function LandingPage() {
}
LandingPage.prototype.keyup = function (ev) {
console.log('keyup', ev);
};
LandingPage.prototype.focusout = function (ev) {
console.log('focusout', ev);
};
LandingPage.prototype.focusin = function (ev) {
console.log('focusin', ev);
};
LandingPage.prototype.render = function () {
return h("div", { "c": { "icon-search": true } },
h("div", { "c": { "search": true } },
h("input", { "a": { "id": "search", "type": "search", "placeholder": "Search" } })));
};
return LandingPage;
}());
exports['ICON-SEARCH'] = LandingPage;
},
/***************** icon-search *****************/
[
/** icon-search: tag **/
"ICON-SEARCH",
/** icon-search: members **/
0 /* no members */,
/** icon-search: host **/
{}
]
)
+4
View File
@@ -0,0 +1,4 @@
/*! Built with http://stenciljs.com */
landing-page.💎 {
visibility: inherit;
}
+45
View File
@@ -0,0 +1,45 @@
/*! Built with http://stenciljs.com */
DocsSite.loadComponents(
/**** module id (dev mode) ****/
"landing-page",
/**** component modules ****/
function importComponent(exports, h, t, Context, publicPath) {
var LandingPage = /** @class */ (function () {
function LandingPage() {
}
LandingPage.prototype.render = function () {
return h("div", 0,
h("h1", 0, t("The premium icon pack for "),
h("a", { "a": { "href": "http://ionicframework.com/" } }, t("Ionic Framework")), t(".")),
h("h2", 0, t("100% free and open source. MIT Licensed.")),
h("div", 0,
h("span", { "c": { "twitter-share": true } },
h("a", { "c": { "twitter-share-button": true }, "a": { "href": "https://twitter.com/share", "data-via": "ionicframework", "data-hashtags": "icons,webdev,mobile", "data-related": "benjsperry,maxlynch,adamdbradley,drifty" } }, t("Tweet"))),
h("span", { "c": { "twitter-follow": true } },
h("a", { "c": { "twitter-follow-button": true }, "a": { "href": "https://twitter.com/ionicframework" } }, t("Follow @ionicframework"))),
h("span", { "c": { "github-star": true } },
h("iframe", { "a": { "src": "http://ghbtns.com/github-btn.html?user=ionic-team&repo=ionicons&type=watch&count=true", "allowtransparency": "true", "frameborder": "0", "scrolling": "0", "width": "110", "height": "20" } }))),
h("icon-search", 0));
};
return LandingPage;
}());
exports['LANDING-PAGE'] = LandingPage;
},
/***************** landing-page *****************/
[
/** landing-page: tag **/
"LANDING-PAGE",
/** landing-page: members **/
0 /* no members */,
/** landing-page: host **/
{}
]
)
+35695
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+40
View File
@@ -0,0 +1,40 @@
<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<title>Ionicons: The premium icon pack for Ionic Framework</title>
<meta name="description" content="Ionicons is an open-sourced and MIT licensed icon pack." />
<meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="theme-color" content="#16161d">
<link rel="manifest" href="/manifest.json">
<link rel="icon" type="image/x-icon" href="/assets/icon/favicon.ico">
<script src="/build/docssite.js"></script>
</head>
<body>
<landing-page></landing-page>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-44023830-2', 'ionicons.com');
ga('send', 'pageview');
</script>
<script>
if ('serviceWorker' in navigator && location.protocol !== 'file:') {
// auto-unregister service worker during dev mode
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
location.reload(true);
});
});
}
</script>
</body>
</html>
File diff suppressed because it is too large Load Diff
+79
View File
@@ -0,0 +1,79 @@
importScripts('workbox-sw.prod.v2.0.1.js');
/**
* DO NOT EDIT THE FILE MANIFEST ENTRY
*
* The method precache() does the following:
* 1. Cache URLs in the manifest to a local cache.
* 2. When a network request is made for any of these URLs the response
* will ALWAYS comes from the cache, NEVER the network.
* 3. When the service worker changes ONLY assets with a revision change are
* updated, old cache entries are left as is.
*
* By changing the file manifest manually, your users may end up not receiving
* new versions of files because the revision hasn't changed.
*
* Please use workbox-build or some other tool / approach to generate the file
* manifest which accounts for changes to local files and update the revision
* accordingly.
*/
const fileManifest = [
{
"url": "assets/icon/favicon.ico",
"revision": "7aa40cf9dba1fd293fc8bd890106acce"
},
{
"url": "build/docssite.js",
"revision": "2d4e3ecb1ce373bbbf162b9dfecd675f"
},
{
"url": "build/docssite.registry.json",
"revision": "d115642fd0adf6504d4a8bd5df960bde"
},
{
"url": "build/docssite/docssite.e26hcszc.pf.js",
"revision": "bedae075ced0f95086a839c9a86d019a"
},
{
"url": "build/docssite/docssite.ypzmzpql.js",
"revision": "279da5e7fc84d233c5c51a86cf93b127"
},
{
"url": "build/docssite/eheipi0c.css",
"revision": "b4afbb64f1eb64168808392ffb5debc5"
},
{
"url": "build/docssite/oeqibtl5.css",
"revision": "66591f2b35f95ab0aa69523ab9a72281"
},
{
"url": "build/docssite/pzcxpt7v.js",
"revision": "adb01506d4777067b84868f3ad4ac381"
},
{
"url": "build/docssite/qeg9454v.js",
"revision": "323c4606031c3e1e7a41591d9725d256"
},
{
"url": "cheatsheet.html",
"revision": "a6c4cbf944eda6a03a326167bdc2c7f9"
},
{
"url": "icon-comparison.html",
"revision": "8a270930bf610473e48bed0d00f0766e"
},
{
"url": "index.html",
"revision": "631a02d7c865f29231ea4968fbfeb86d"
},
{
"url": "mode-cheatsheet.html",
"revision": "f5bc10012725f26fffa3c49f7877fbc0"
}
];
const workboxSW = new self.WorkboxSW({
"skipWaiting": true,
"clientsClaim": true
});
workboxSW.precache(fileManifest);
+158
View File
@@ -0,0 +1,158 @@
/*
Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var WorkboxSW = (function () {
'use strict';
class ErrorFactory$1{constructor(a){this._errors=a;}createError(a,b){if(!(a in this._errors))throw new Error(`Unable to generate error '${a}'.`);let c=this._errors[a].replace(/\s+/g,' '),d=null;b&&(c+=` [${b.message}]`,d=b.stack);const e=new Error;return e.name=a,e.message=c,e.stack=d,e}}
const errors={"not-in-sw":'workbox-sw must be loaded in your service worker file.',"unsupported-route-type":'The first parameter to registerRoute() should be either an Express-style path string, a RegExp, or a function.',"empty-express-string":'The Express style route string must have some characters, an empty string is invalid.',"bad-revisioned-cache-list":`The 'precache()' method expects`+`an array of revisioned urls like so: ['/example/hello.1234.txt', `+`{path: 'hello.txt', revision: '1234'}]`,"navigation-route-url-string":`The registerNavigationRoute() method `+`expects a URL string as its first parameter.`,"bad-cache-id":`The 'cacheId' parameter must be a string with at least `+`one character`,"bad-skip-waiting":`The 'skipWaiting' parameter must be a boolean.`,"bad-clients-claim":`The 'clientsClaim' parameter must be a boolean.`,"bad-directory-index":`The 'directoryIndex' parameter must be a boolean.`};var ErrorFactory = new ErrorFactory$1(errors);
const errors$1={"express-route-invalid-path":`When using ExpressRoute, you must
provide a path that starts with a '/' character (to match same-origin
requests) or that starts with 'http' (to match cross-origin requests)`};var ErrorFactory$3 = new ErrorFactory$1(errors$1);
var ErrorStackParser = {parse:()=>[]};
function atLeastOne(a){const b=Object.keys(a);b.some((c)=>a[c]!==void 0)||throwError('Please set at least one of the following parameters: '+b.map((c)=>`'${c}'`).join(', '));}function hasMethod(a,b){const c=Object.keys(a).pop(),d=typeof a[c][b];'function'!=d&&throwError(`The '${c}' parameter must be an object that exposes a
'${b}' method.`);}function isInstance(a,b){const c=Object.keys(a).pop();a[c]instanceof b||throwError(`The '${c}' parameter must be an instance of
'${b.name}'`);}function isOneOf(a,b){const c=Object.keys(a).pop();b.includes(a[c])||throwError(`The '${c}' parameter must be set to one of the
following: ${b}`);}function isType(a,b){const c=Object.keys(a).pop(),d=typeof a[c];d!==b&&throwError(`The '${c}' parameter has the wrong type. (Expected:
${b}, actual: ${d})`);}function isArrayOfType(a,b){const c=Object.keys(a).pop(),d=`The '${c}' parameter should be an array containing
one or more '${b}' elements.`;Array.isArray(a[c])||throwError(d);for(let e of a[c])typeof e!==b&&throwError(d);}function isArrayOfClass(a,b){const c=Object.keys(a).pop(),d=`The '${c}' parameter should be an array containing
one or more '${b.name}' instances.`;Array.isArray(a[c])||throwError(d);for(let e of a[c])e instanceof b||throwError(d);}function throwError(a){a=a.replace(/\s+/g,' ');const b=new Error(a);b.name='assertion-failed';const c=ErrorStackParser.parse(b);throw 3<=c.length&&(b.message=`Invalid call to ${c[2].functionName}() — `+a),b}
function normalizeHandler(a){return'object'==typeof a?(hasMethod({handler:a},'handle'),a):(isType({handler:a},'function'),{handle:a})}
const defaultMethod='GET';const validMethods=['DELETE','GET','HEAD','POST','PUT'];
class Route{constructor({match:a,handler:b,method:c}={}){this.handler=normalizeHandler(b),isType({match:a},'function'),this.match=a,c?(isOneOf({method:c},validMethods),this.method=c):this.method=defaultMethod;}}
var isarray=Array.isArray||function(a){return'[object Array]'==Object.prototype.toString.call(a)};
var pathToRegexp_1=pathToRegexp; var parse_1=parse; var compile_1=compile; var tokensToFunction_1=tokensToFunction; var tokensToRegExp_1=tokensToRegExp; var PATH_REGEXP=new RegExp(['(\\\\.)','([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))'].join('|'),'g');function parse(a,b){for(var k,d=[],e=0,f=0,g='',h=b&&b.delimiter||'/';null!=(k=PATH_REGEXP.exec(a));){var l=k[0],n=k[1],o=k.index;if(g+=a.slice(f,o),f=o+l.length,n){g+=n[1];continue}var p=a[f],q=k[2],r=k[3],s=k[4],t=k[5],u=k[6],v=k[7];g&&(d.push(g),g='');var z=k[2]||h,A=s||t;d.push({name:r||e++,prefix:q||'',delimiter:z,optional:'?'===u||'*'===u,repeat:'+'===u||'*'===u,partial:null!=q&&null!=p&&p!==q,asterisk:!!v,pattern:A?escapeGroup(A):v?'.*':'[^'+escapeString(z)+']+?'});}return f<a.length&&(g+=a.substr(f)),g&&d.push(g),d}function compile(a,b){return tokensToFunction(parse(a,b))}function encodeURIComponentPretty(a){return encodeURI(a).replace(/[\/?#]/g,function(b){return'%'+b.charCodeAt(0).toString(16).toUpperCase()})}function encodeAsterisk(a){return encodeURI(a).replace(/[?#]/g,function(b){return'%'+b.charCodeAt(0).toString(16).toUpperCase()})}function tokensToFunction(a){for(var b=Array(a.length),d=0;d<a.length;d++)'object'==typeof a[d]&&(b[d]=new RegExp('^(?:'+a[d].pattern+')$'));return function(e,f){for(var o,g='',h=e||{},k=f||{},l=k.pretty?encodeURIComponentPretty:encodeURIComponent,n=0;n<a.length;n++){if(o=a[n],'string'==typeof o){g+=o;continue}var q,p=h[o.name];if(null==p)if(o.optional){o.partial&&(g+=o.prefix);continue}else throw new TypeError('Expected "'+o.name+'" to be defined');if(isarray(p)){if(!o.repeat)throw new TypeError('Expected "'+o.name+'" to not repeat, but received `'+JSON.stringify(p)+'`');if(0===p.length)if(o.optional)continue;else throw new TypeError('Expected "'+o.name+'" to not be empty');for(var r=0;r<p.length;r++){if(q=l(p[r]),!b[n].test(q))throw new TypeError('Expected all "'+o.name+'" to match "'+o.pattern+'", but received `'+JSON.stringify(q)+'`');g+=(0===r?o.prefix:o.delimiter)+q;}continue}if(q=o.asterisk?encodeAsterisk(p):l(p),!b[n].test(q))throw new TypeError('Expected "'+o.name+'" to match "'+o.pattern+'", but received "'+q+'"');g+=o.prefix+q;}return g}}function escapeString(a){return a.replace(/([.+*?=^!:${}()[\]|\/\\])/g,'\\$1')}function escapeGroup(a){return a.replace(/([=!:$\/()])/g,'\\$1')}function attachKeys(a,b){return a.keys=b,a}function flags(a){return a.sensitive?'':'i'}function regexpToRegexp(a,b){var d=a.source.match(/\((?!\?)/g);if(d)for(var e=0;e<d.length;e++)b.push({name:e,prefix:null,delimiter:null,optional:!1,repeat:!1,partial:!1,asterisk:!1,pattern:null});return attachKeys(a,b)}function arrayToRegexp(a,b,d){for(var e=[],f=0;f<a.length;f++)e.push(pathToRegexp(a[f],b,d).source);var g=new RegExp('(?:'+e.join('|')+')',flags(d));return attachKeys(g,b)}function stringToRegexp(a,b,d){return tokensToRegExp(parse(a,d),b,d)}function tokensToRegExp(a,b,d){isarray(b)||(d=b||d,b=[]),d=d||{};for(var k,e=d.strict,f=!1!==d.end,g='',h=0;h<a.length;h++)if(k=a[h],'string'==typeof k)g+=escapeString(k);else{var l=escapeString(k.prefix),n='(?:'+k.pattern+')';b.push(k),k.repeat&&(n+='(?:'+l+n+')*'),n=k.optional?k.partial?l+'('+n+')?':'(?:'+l+'('+n+'))?':l+'('+n+')',g+=n;}var o=escapeString(d.delimiter||'/'),p=g.slice(-o.length)===o;return e||(g=(p?g.slice(0,-o.length):g)+'(?:'+o+'(?=$))?'),g+=f?'$':e&&p?'':'(?='+o+'|$)',attachKeys(new RegExp('^'+g,flags(d)),b)}function pathToRegexp(a,b,d){return isarray(b)||(d=b||d,b=[]),d=d||{},a instanceof RegExp?regexpToRegexp(a,b):isarray(a)?arrayToRegexp(a,b,d):stringToRegexp(a,b,d)}pathToRegexp_1.parse=parse_1,pathToRegexp_1.compile=compile_1,pathToRegexp_1.tokensToFunction=tokensToFunction_1,pathToRegexp_1.tokensToRegExp=tokensToRegExp_1;
class ExpressRoute extends Route{constructor({path:a,handler:b,method:c}){if(!(a.startsWith('/')||a.startsWith('http')))throw ErrorFactory$3.createError('express-route-invalid-path');let d=[];const e=pathToRegexp_1(a,d);super({match:({url:g})=>{if(a.startsWith('/')&&g.origin!==location.origin)return null;const h=a.startsWith('/')?g.pathname:g.href,i=h.match(e);if(!i)return null;const j={};return d.forEach((k,l)=>{j[k.name]=i[l+1];}),j},handler:b,method:c});}}
class LogGroup{constructor(){this._logs=[],this._childGroups=[],this._isFallbackMode=!1;const a=/Firefox\/(\d*)\.\d*/.exec(navigator.userAgent);if(a)try{const b=parseInt(a[1],10);55>b&&(this._isFallbackMode=!0);}catch(b){this._isFallbackMode=!0;}/Edge\/\d*\.\d*/.exec(navigator.userAgent)&&(this._isFallbackMode=!0);}addPrimaryLog(a){this._primaryLog=a;}addLog(a){this._logs.push(a);}addChildGroup(a){0===a._logs.length||this._childGroups.push(a);}print(){return 0===this._logs.length&&0===this._childGroups.length?void this._printLogDetails(this._primaryLog):void(this._primaryLog&&(this._isFallbackMode?this._printLogDetails(this._primaryLog):console.groupCollapsed(...this._getLogContent(this._primaryLog))),this._logs.forEach((a)=>{this._printLogDetails(a);}),this._childGroups.forEach((a)=>{a.print();}),this._primaryLog&&!this._isFallbackMode&&console.groupEnd())}_printLogDetails(a){const b=a.logFunc?a.logFunc:console.log;b(...this._getLogContent(a));}_getLogContent(a){let b=a.message;this._isFallbackMode&&'string'==typeof b&&(b=b.replace(/%c/g,''));let c=[b];return!this._isFallbackMode&&a.colors&&(c=c.concat(a.colors)),a.args&&(c=c.concat(a.args)),c}}
function isServiceWorkerGlobalScope(){return'ServiceWorkerGlobalScope'in self&&self instanceof ServiceWorkerGlobalScope}function isDevBuild(){return`dev`==`prod`}function isLocalhost(){return!!('localhost'===location.hostname||'[::1]'===location.hostname||location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/))}
self.workbox=self.workbox||{},self.workbox.LOG_LEVEL=self.workbox.LOG_LEVEL||{none:-1,verbose:0,debug:1,warn:2,error:3};const LIGHT_GREY=`#bdc3c7`; const DARK_GREY=`#7f8c8d`; const LIGHT_GREEN=`#2ecc71`; const LIGHT_YELLOW=`#f1c40f`; const LIGHT_RED=`#e74c3c`; const LIGHT_BLUE=`#3498db`;class LogHelper{constructor(){this._defaultLogLevel=isDevBuild()?self.workbox.LOG_LEVEL.debug:self.workbox.LOG_LEVEL.warn;}log(a){this._printMessage(self.workbox.LOG_LEVEL.verbose,a);}debug(a){this._printMessage(self.workbox.LOG_LEVEL.debug,a);}warn(a){this._printMessage(self.workbox.LOG_LEVEL.warn,a);}error(a){this._printMessage(self.workbox.LOG_LEVEL.error,a);}_printMessage(a,b){if(this._shouldLogMessage(a,b)){const c=this._getAllLogGroups(a,b);c.print();}}_getAllLogGroups(a,b){const c=new LogGroup,d=this._getPrimaryMessageDetails(a,b);if(c.addPrimaryLog(d),b.error){const f={message:b.error,logFunc:console.error};c.addLog(f);}const e=new LogGroup;if(b.that&&b.that.constructor&&b.that.constructor.name){const f=b.that.constructor.name;e.addLog(this._getKeyValueDetails('class',f));}return b.data&&('object'!=typeof b.data||b.data instanceof Array?e.addLog(this._getKeyValueDetails('additionalData',b.data)):Object.keys(b.data).forEach((f)=>{e.addLog(this._getKeyValueDetails(f,b.data[f]));})),c.addChildGroup(e),c}_getKeyValueDetails(a,b){return{message:`%c${a}: `,colors:[`color: ${LIGHT_BLUE}`],args:b}}_getPrimaryMessageDetails(a,b){let c,d;a===self.workbox.LOG_LEVEL.verbose?(c='Info',d=LIGHT_GREY):a===self.workbox.LOG_LEVEL.debug?(c='Debug',d=LIGHT_GREEN):a===self.workbox.LOG_LEVEL.warn?(c='Warn',d=LIGHT_YELLOW):a===self.workbox.LOG_LEVEL.error?(c='Error',d=LIGHT_RED):void 0;let e=`%c🔧 %c[${c}]`;const f=[`color: ${LIGHT_GREY}`,`color: ${d}`];let g;return'string'==typeof b?g=b:b.message&&(g=b.message),g&&(g=g.replace(/\s+/g,' '),e+=`%c ${g}`,f.push(`color: ${DARK_GREY}; font-weight: normal`)),{message:e,colors:f}}_shouldLogMessage(a,b){if(!b)return!1;let c=this._defaultLogLevel;return self&&self.workbox&&'number'==typeof self.workbox.logLevel&&(c=self.workbox.logLevel),c===self.workbox.LOG_LEVEL.none||a<c?!1:!0}}var logHelper = new LogHelper;
class NavigationRoute extends Route{constructor({whitelist:a,blacklist:b,handler:c}={}){isArrayOfClass({whitelist:a},RegExp),b?isArrayOfClass({blacklist:b},RegExp):b=[];super({match:({event:e,url:f})=>{let g=!1,h;if('navigate'===e.request.mode){const i=f.pathname+f.search;a.some((j)=>j.test(i))?b.some((j)=>j.test(i))?h=`The navigation route is not being used, since the `+`request URL matches both the whitelist and blacklist.`:(h=`The navigation route is being used.`,g=!0):h=`The navigation route is not being used, since the `+`URL being navigated to doesn't match the whitelist.`,logHelper.debug({that:this,message:h,data:{"request-url":f.href,whitelist:a,blacklist:b,handler:c}});}return g},handler:c,method:'GET'});}}
class RegExpRoute extends Route{constructor({regExp:a,handler:b,method:c}){isInstance({regExp:a},RegExp);super({match:({url:e})=>{const f=a.exec(e.href);return f?e.origin!==location.origin&&0!==f.index?(logHelper.debug({that:this,message:`Skipping route, because the RegExp match didn't occur `+`at the start of the URL.`,data:{url:e.href,regExp:a}}),null):f.slice(1):null},handler:b,method:c});}}
class Router$2{constructor(){this._routes=new Map,this._isListenerRegistered=!1;}addFetchListener(){return this._isListenerRegistered?(logHelper.warn({that:this,message:`addFetchListener() has already been called for this Router.`}),!1):(this._isListenerRegistered=!0,self.addEventListener('fetch',(a)=>{const b=this.handleRequest({event:a});b&&a.respondWith(b);}),!0)}handleRequest({event:a}){isInstance({event:a},FetchEvent);const b=new URL(a.request.url);if(!b.protocol.startsWith('http'))return void logHelper.log({that:this,message:`The URL does not start with HTTP, so it can't be handled.`,data:{request:a.request}});let{handler:c,params:d}=this._findHandlerAndParams({event:a,url:b});if(!c&&this.defaultHandler&&(c=this.defaultHandler),c){let e=c.handle({url:b,event:a,params:d});return this.catchHandler&&(e=e.catch((f)=>{return this.catchHandler.handle({url:b,event:a,error:f})})),e}}_findHandlerAndParams({event:a,url:b}){const c=this._routes.get(a.request.method)||[];for(const d of c){let e=d.match({url:b,event:a});if(e)return logHelper.log({that:this,message:'The router found a matching route.',data:{route:d,request:a.request}}),Array.isArray(e)&&0===e.length?e=void 0:e.constructor===Object&&0===Object.keys(e).length&&(e=void 0),{params:e,handler:d.handler}}return{handler:void 0,params:void 0}}setDefaultHandler({handler:a}={}){this.defaultHandler=normalizeHandler(a);}setCatchHandler({handler:a}={}){this.catchHandler=normalizeHandler(a);}registerRoutes({routes:a}={}){isArrayOfClass({routes:a},Route);for(let b of a)this._routes.has(b.method)||this._routes.set(b.method,[]),this._routes.get(b.method).unshift(b);}registerRoute({route:a}={}){isInstance({route:a},Route),this.registerRoutes({routes:[a]});}unregisterRoutes({routes:a}={}){isArrayOfClass({routes:a},Route);for(let b of a){this._routes.has(b.method)||logHelper.error({that:this,message:`Can't unregister route; there are no ${b.method}
routes registered.`,data:{route:b}});const c=this._routes.get(b.method).indexOf(b);-1<c?this._routes.get(b.method).splice(c,1):logHelper.error({that:this,message:`Can't unregister route; the route wasn't previously
registered.`,data:{route:b}});}}unregisterRoute({route:a}={}){isInstance({route:a},Route),this.unregisterRoutes({routes:[a]});}}
class Router$$1 extends Router$2{constructor(a,b){super({handleFetch:b}),this._revisionedCacheName=a;}registerRoute(a,b,c='GET'){'function'==typeof b&&(b={handle:b});let d;if('string'==typeof a){if(0===a.length)throw ErrorFactory.createError('empty-express-string');d=new ExpressRoute({path:a,handler:b,method:c});}else if(a instanceof RegExp)d=new RegExpRoute({regExp:a,handler:b,method:c});else if('function'==typeof a)d=new Route({match:a,handler:b,method:c});else throw ErrorFactory.createError('unsupported-route-type');return super.registerRoute({route:d}),d}registerNavigationRoute(a,b={}){if('string'!=typeof a)throw ErrorFactory.createError('navigation-route-url-string');const c='cacheName'in b?b.cacheName:this._revisionedCacheName;super.registerRoute({route:new NavigationRoute({handler:()=>caches.match(a,{cacheName:c}),whitelist:b.whitelist||[/./],blacklist:b.blacklist||[]})});}}
const errors$2={"multiple-cache-will-update-plugins":'You cannot register more than one plugin that implements cacheWillUpdate.',"multiple-cached-response-will-be-used-plugins":'You cannot register more than one plugin that implements cachedResponseWillBeUsed.',"invalid-response-for-caching":'The fetched response could not be cached due to an invalid response code.',"no-response-received":'No response received; falling back to cache.',"bad-cache-id":`The 'cacheId' parameter must be a string with at least `+`one character.`};var ErrorFactory$4 = new ErrorFactory$1(errors$2);
class CacheableResponse{constructor({statuses:a,headers:b}={}){atLeastOne({statuses:a,headers:b}),a!==void 0&&isArrayOfType({statuses:a},'number'),b!==void 0&&isType({headers:b},'object'),this.statuses=a,this.headers=b;}isResponseCacheable({request:a,response:b}={}){isInstance({response:b},Response);let c=!0;if(this.statuses&&(c=this.statuses.includes(b.status)),this.headers&&c&&(c=Object.keys(this.headers).some((d)=>{return b.headers.get(d)===this.headers[d]})),!c){const d={response:b};this.statuses&&(d['valid-status-codes']=JSON.stringify(this.statuses)),this.headers&&(d['valid-headers']=JSON.stringify(this.headers)),a&&(d.request=a),logHelper.debug({message:`The response does not meet the criteria for being added to the
cache.`,data:d});}return c}}
class CacheableResponsePlugin extends CacheableResponse{cacheWillUpdate({request:a,response:b}={}){return this.isResponseCacheable({request:a,response:b})}}
const getDefaultCacheName=({cacheId:a}={})=>{let b=`workbox-runtime-caching`;return a&&(b=`${a}-${b}`),self&&self.registration&&(b+=`-${self.registration.scope}`),b};
const pluginCallbacks=['cacheDidUpdate','cachedResponseWillBeUsed','cacheWillUpdate','fetchDidFail','requestWillFetch'];
var cleanResponseCopy = (({response:a})=>{isInstance({response:a},Response);const b=a.clone(),c='body'in b?Promise.resolve(b.body):b.blob();return c.then((d)=>{return new Response(d,{headers:b.headers,status:b.status,statusText:b.statusText})})});
class RequestWrapper{constructor({cacheName:a,cacheId:b,plugins:c,fetchOptions:d,matchOptions:e}={}){if(b&&('string'!=typeof b||0===b.length))throw ErrorFactory$4.createError('bad-cache-id');a?(isType({cacheName:a},'string'),this.cacheName=a,b&&(this.cacheName=`${b}-${this.cacheName}`)):this.cacheName=getDefaultCacheName({cacheId:b}),d&&(isType({fetchOptions:d},'object'),this.fetchOptions=d),e&&(isType({matchOptions:e},'object'),this.matchOptions=e),this.plugins=new Map,c&&(isArrayOfType({plugins:c},'object'),c.forEach((f)=>{for(let g of pluginCallbacks)if('function'==typeof f[g]){if(!this.plugins.has(g))this.plugins.set(g,[]);else if('cacheWillUpdate'===g)throw ErrorFactory$4.createError('multiple-cache-will-update-plugins');else if('cachedResponseWillBeUsed'===g)throw ErrorFactory$4.createError('multiple-cached-response-will-be-used-plugins');this.plugins.get(g).push(f);}})),this.plugins.has('cacheWillUpdate')&&(this._userSpecifiedCachableResponsePlugin=this.plugins.get('cacheWillUpdate')[0]);}getDefaultCacheableResponsePlugin(){return this._defaultCacheableResponsePlugin||(this._defaultCacheableResponsePlugin=new CacheableResponsePlugin({statuses:[200]})),this._defaultCacheableResponsePlugin}async getCache(){return this._cache||(this._cache=await caches.open(this.cacheName)),this._cache}async match({request:a}){atLeastOne({request:a});const b=await this.getCache();let c=await b.match(a,this.matchOptions);if(this.plugins.has('cachedResponseWillBeUsed')){const d=this.plugins.get('cachedResponseWillBeUsed')[0];c=await d.cachedResponseWillBeUsed({request:a,cache:b,cachedResponse:c,matchOptions:this.matchOptions,cacheName:this.cacheName});}return c}async fetch({request:a}){'string'==typeof a?a=new Request(a):isInstance({request:a},Request);const b=this.plugins.has('fetchDidFail')?a.clone():null;if(this.plugins.has('requestWillFetch'))for(let c of this.plugins.get('requestWillFetch')){const d=await c.requestWillFetch({request:a});isInstance({returnedRequest:d},Request),a=d;}try{return await fetch(a,this.fetchOptions)}catch(c){if(this.plugins.has('fetchDidFail'))for(let d of this.plugins.get('fetchDidFail'))await d.fetchDidFail({request:b.clone()});throw c}}async fetchAndCache({request:a,waitOnCache:b,cacheKey:c,cacheResponsePlugin:d,cleanRedirects:e}){atLeastOne({request:a});let f;const g=await this.fetch({request:a}),h=this._userSpecifiedCachableResponsePlugin||d||this.getDefaultCacheableResponsePlugin(),i=await h.cacheWillUpdate({request:a,response:g});if(i){const j=e&&g.redirected?await cleanResponseCopy({response:g}):g.clone();f=this.getCache().then(async(k)=>{let l;const m=c||a;if('opaque'!==g.type&&this.plugins.has('cacheDidUpdate')&&(l=await this.match({request:m})),await k.put(m,j),this.plugins.has('cacheDidUpdate'))for(let n of this.plugins.get('cacheDidUpdate'))await n.cacheDidUpdate({cacheName:this.cacheName,oldResponse:l,newResponse:j,url:'url'in m?m.url:m});});}else if(!i&&b)throw ErrorFactory$4.createError('invalid-response-for-caching');return b&&f&&(await f),g}}
class Handler{constructor({requestWrapper:a,waitOnCache:b}={}){this.requestWrapper=a?a:new RequestWrapper,this.waitOnCache=!!b;}handle({event:a,params:b}={}){throw Error('This abstract method must be implemented in a subclass.')}}
class CacheFirst extends Handler{async handle({event:a}={}){isInstance({event:a},FetchEvent);const b=await this.requestWrapper.match({request:a.request});return b||(await this.requestWrapper.fetchAndCache({request:a.request,waitOnCache:this.waitOnCache}))}}
class CacheOnly extends Handler{async handle({event:a}={}){return isInstance({event:a},FetchEvent),await this.requestWrapper.match({request:a.request})}}
class NetworkFirst extends Handler{constructor(a={}){super(a),this._cacheablePlugin=new CacheableResponsePlugin({statuses:[0,200]});const{networkTimeoutSeconds:b}=a;b&&(isType({networkTimeoutSeconds:b},'number'),this.networkTimeoutSeconds=b);}async handle({event:a}={}){isInstance({event:a},FetchEvent);const b=[];let c;this.networkTimeoutSeconds&&b.push(new Promise((e)=>{c=setTimeout(()=>{e(this.requestWrapper.match({request:a.request}));},1e3*this.networkTimeoutSeconds);}));const d=this.requestWrapper.fetchAndCache({request:a.request,waitOnCache:this.waitOnCache,cacheResponsePlugin:this._cacheablePlugin}).then((e)=>{return c&&clearTimeout(c),e?e:Promise.reject(ErrorFactory$4.createError('no-response-received'))}).catch(()=>this.requestWrapper.match({request:a.request}));return b.push(d),Promise.race(b)}}
class NetworkOnly extends Handler{async handle({event:a}={}){return isInstance({event:a},FetchEvent),await this.requestWrapper.fetch({request:a.request})}}
class StaleWhileRevalidate extends Handler{constructor(a={}){super(a),this._cacheablePlugin=new CacheableResponsePlugin({statuses:[0,200]});}async handle({event:a}={}){isInstance({event:a},FetchEvent);const b=this.requestWrapper.fetchAndCache({request:a.request,waitOnCache:this.waitOnCache,cacheResponsePlugin:this._cacheablePlugin}).catch(()=>Response.error()),c=await this.requestWrapper.match({request:a.request});return c||(await b)}}
let tmpIdbName=`workbox-cache-expiration`;self&&self.registration&&(tmpIdbName+=`-${self.registration.scope}`);const idbName=tmpIdbName;const idbVersion=1;const urlPropertyName='url';const timestampPropertyName='timestamp';
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var idb=createCommonjsModule(function(a){'use strict';(function(){function b(r){return Array.prototype.slice.call(r)}function c(r){return new Promise(function(s,t){r.onsuccess=function(){s(r.result);},r.onerror=function(){t(r.error);};})}function d(r,s,t){var u,v=new Promise(function(w,x){u=r[s].apply(r,t),c(u).then(w,x);});return v.request=u,v}function e(r,s,t){var u=d(r,s,t);return u.then(function(v){return v?new k(v,u.request):void 0})}function f(r,s,t){t.forEach(function(u){Object.defineProperty(r.prototype,u,{get:function(){return this[s][u]},set:function(v){this[s][u]=v;}});});}function g(r,s,t,u){u.forEach(function(v){v in t.prototype&&(r.prototype[v]=function(){return d(this[s],v,arguments)});});}function h(r,s,t,u){u.forEach(function(v){v in t.prototype&&(r.prototype[v]=function(){return this[s][v].apply(this[s],arguments)});});}function i(r,s,t,u){u.forEach(function(v){v in t.prototype&&(r.prototype[v]=function(){return e(this[s],v,arguments)});});}function j(r){this._index=r;}function k(r,s){this._cursor=r,this._request=s;}function l(r){this._store=r;}function m(r){this._tx=r,this.complete=new Promise(function(s,t){r.oncomplete=function(){s();},r.onerror=function(){t(r.error);},r.onabort=function(){t(r.error);};});}function n(r,s,t){this._db=r,this.oldVersion=s,this.transaction=new m(t);}function o(r){this._db=r;}f(j,'_index',['name','keyPath','multiEntry','unique']),g(j,'_index',IDBIndex,['get','getKey','getAll','getAllKeys','count']),i(j,'_index',IDBIndex,['openCursor','openKeyCursor']),f(k,'_cursor',['direction','key','primaryKey','value']),g(k,'_cursor',IDBCursor,['update','delete']),['advance','continue','continuePrimaryKey'].forEach(function(r){r in IDBCursor.prototype&&(k.prototype[r]=function(){var s=this,t=arguments;return Promise.resolve().then(function(){return s._cursor[r].apply(s._cursor,t),c(s._request).then(function(u){return u?new k(u,s._request):void 0})})});}),l.prototype.createIndex=function(){return new j(this._store.createIndex.apply(this._store,arguments))},l.prototype.index=function(){return new j(this._store.index.apply(this._store,arguments))},f(l,'_store',['name','keyPath','indexNames','autoIncrement']),g(l,'_store',IDBObjectStore,['put','add','delete','clear','get','getAll','getKey','getAllKeys','count']),i(l,'_store',IDBObjectStore,['openCursor','openKeyCursor']),h(l,'_store',IDBObjectStore,['deleteIndex']),m.prototype.objectStore=function(){return new l(this._tx.objectStore.apply(this._tx,arguments))},f(m,'_tx',['objectStoreNames','mode']),h(m,'_tx',IDBTransaction,['abort']),n.prototype.createObjectStore=function(){return new l(this._db.createObjectStore.apply(this._db,arguments))},f(n,'_db',['name','version','objectStoreNames']),h(n,'_db',IDBDatabase,['deleteObjectStore','close']),o.prototype.transaction=function(){return new m(this._db.transaction.apply(this._db,arguments))},f(o,'_db',['name','version','objectStoreNames']),h(o,'_db',IDBDatabase,['close']),['openCursor','openKeyCursor'].forEach(function(r){[l,j].forEach(function(s){s.prototype[r.replace('open','iterate')]=function(){var t=b(arguments),u=t[t.length-1],v=this._store||this._index,w=v[r].apply(v,t.slice(0,-1));w.onsuccess=function(){u(w.result);};};});}),[j,l].forEach(function(r){r.prototype.getAll||(r.prototype.getAll=function(s,t){var u=this,v=[];return new Promise(function(w){u.iterateCursor(s,function(x){return x?(v.push(x.value),void 0!==t&&v.length==t?void w(v):void x.continue()):void w(v)});})});});var q={open:function(r,s,t){var u=d(indexedDB,'open',[r,s]),v=u.request;return v.onupgradeneeded=function(w){t&&t(new n(v.result,w.oldVersion,v.transaction));},u.then(function(w){return new o(w)})},delete:function(r){return d(indexedDB,'deleteDatabase',[r])}};a.exports=q,a.exports.default=a.exports;})();});
const errors$3={"max-entries-or-age-required":`Either the maxEntries or maxAgeSeconds
parameters (or both) are required when constructing Plugin.`,"max-entries-must-be-number":`The maxEntries parameter to the Plugin
constructor must either be a number or undefined.`,"max-age-seconds-must-be-number":`The maxAgeSeconds parameter to the Plugin
constructor must either be a number or undefined.`};var ErrorFactory$5 = new ErrorFactory$1(errors$3);
class CacheExpiration{constructor({maxEntries:a,maxAgeSeconds:b}={}){if(!(a||b))throw ErrorFactory$5.createError('max-entries-or-age-required');if(a&&'number'!=typeof a)throw ErrorFactory$5.createError('max-entries-must-be-number');if(b&&'number'!=typeof b)throw ErrorFactory$5.createError('max-age-seconds-must-be-number');this.maxEntries=a,this.maxAgeSeconds=b,this._dbs=new Map,this._caches=new Map,this._expirationMutex=!1,this._timestampForNextRun=null;}async getDB({cacheName:a}={}){isType({cacheName:a},'string');const b=`${idbName}-${a}`;if(!this._dbs.has(b)){const c=await idb.open(b,idbVersion,(d)=>{const e=d.createObjectStore(a,{keyPath:urlPropertyName});e.createIndex(timestampPropertyName,timestampPropertyName,{unique:!1});});this._dbs.set(b,c);}return this._dbs.get(b)}async getCache({cacheName:a}={}){if(isType({cacheName:a},'string'),!this._caches.has(a)){const b=await caches.open(a);this._caches.set(a,b);}return this._caches.get(a)}isResponseFresh({cacheName:a,cachedResponse:b,now:c}={}){if(b&&this.maxAgeSeconds){isInstance({cachedResponse:b},Response);const d=b.headers.get('date');if(d){'undefined'==typeof c&&(c=Date.now());const e=new Date(d),f=e.getTime();return!!isNaN(f)||f+1e3*this.maxAgeSeconds>c}return this.expireEntries({cacheName:a,now:c}),!0}return!0}async updateTimestamp({cacheName:a,url:b,now:c}={}){isType({url:b},'string'),isType({cacheName:a},'string');const d=new URL(b,location);d.hash='','undefined'==typeof c&&(c=Date.now());const e=await this.getDB({cacheName:a}),f=e.transaction(a,'readwrite');f.objectStore(a).put({[timestampPropertyName]:c,[urlPropertyName]:d.href}),await f.complete;}async expireEntries({cacheName:a,now:b}={}){if(this._expirationMutex)return void(this._timestampForNextRun=b);this._expirationMutex=!0,isType({cacheName:a},'string'),'undefined'==typeof b&&(b=Date.now());const c=this.maxAgeSeconds?await this.findOldEntries({cacheName:a,now:b}):[],d=this.maxEntries?await this.findExtraEntries({cacheName:a}):[],e=[...new Set(c.concat(d))];if(await this.deleteFromCacheAndIDB({cacheName:a,urls:e}),0<e.length&&logHelper.debug({that:this,message:'Expired entries have been removed from the cache.',data:{cacheName:a,urls:e}}),this._expirationMutex=!1,this._timestampForNextRun){const f=this._timestampForNextRun;return this._timestampForNextRun=null,this.expireEntries({cacheName:a,now:f})}}async findOldEntries({cacheName:a,now:b}={}){isType({cacheName:a},'string'),isType({now:b},'number');const c=b-1e3*this.maxAgeSeconds,d=[],e=await this.getDB({cacheName:a}),f=e.transaction(a,'readonly'),g=f.objectStore(a),h=g.index(timestampPropertyName);return h.iterateCursor((i)=>{i&&(i.value[timestampPropertyName]<c&&d.push(i.value[urlPropertyName]),i.continue());}),await f.complete,d}async findExtraEntries({cacheName:a}={}){isType({cacheName:a},'string');const b=[],c=await this.getDB({cacheName:a});let d=c.transaction(a,'readonly'),e=d.objectStore(a),f=e.index(timestampPropertyName);const g=await f.count();return g>this.maxEntries&&(d=c.transaction(a,'readonly'),e=d.objectStore(a),f=e.index(timestampPropertyName),f.iterateCursor((h)=>{h&&(b.push(h.value[urlPropertyName]),g-b.length>this.maxEntries&&h.continue());})),await d.complete,b}async deleteFromCacheAndIDB({cacheName:a,urls:b}={}){if(isType({cacheName:a},'string'),isArrayOfType({urls:b},'string'),0<b.length){const c=await this.getCache({cacheName:a}),d=await this.getDB({cacheName:a});for(let e of b){await c.delete(e);const f=d.transaction(a,'readwrite'),g=f.objectStore(a);g.delete(e),await f.complete;}}}}
class CacheExpirationPlugin extends CacheExpiration{cachedResponseWillBeUsed({cacheName:a,cachedResponse:b,now:c}={}){return this.isResponseFresh({cacheName:a,cachedResponse:b,now:c})?b:null}async cacheDidUpdate({cacheName:a,newResponse:b,url:c,now:d}={}){isType({cacheName:a},'string'),isInstance({newResponse:b},Response),'undefined'==typeof d&&(d=Date.now()),await this.updateTimestamp({cacheName:a,url:c,now:d}),await this.expireEntries({cacheName:a,now:d});}}
const errors$4={"channel-name-required":`The channelName parameter is required when
constructing a new BroadcastCacheUpdate instance.`,"responses-are-same-parameters-required":`The first, second, and
headersToCheck parameters must be valid when calling responsesAreSame()`};var ErrorFactory$6 = new ErrorFactory$1(errors$4);
const cacheUpdatedMessageType='CACHE_UPDATED';
const defaultHeadersToCheck=['content-length','etag','last-modified'];
const defaultSource='workbox-broadcast-cache-update';
function broadcastUpdate({channel:a,cacheName:b,url:c,source:d}={}){isInstance({channel:a},BroadcastChannel),isType({cacheName:b},'string'),isType({source:d},'string'),isType({url:c},'string'),a.postMessage({type:cacheUpdatedMessageType,meta:d,payload:{cacheName:b,updatedUrl:c}});}
function responsesAreSame({first:a,second:b,headersToCheck:c}={}){if(!(a instanceof Response&&b instanceof Response&&c instanceof Array))throw ErrorFactory$6.createError('responses-are-same-parameters-required');const d=c.some((e)=>{return a.headers.has(e)&&b.headers.has(e)});return d?c.every((e)=>{return a.headers.has(e)===b.headers.has(e)&&a.headers.get(e)===b.headers.get(e)}):(logHelper.log({message:`Unable to determine whether the response has been updated
because none of the headers that would be checked are present.`,data:{"First Response":a,"Second Response":b,"Headers To Check":JSON.stringify(c)}}),!0)}
class BroadcastCacheUpdate{constructor({channelName:a,headersToCheck:b,source:c}={}){if('string'!=typeof a||0===a.length)throw ErrorFactory$6.createError('channel-name-required');this.channelName=a,this.headersToCheck=b||defaultHeadersToCheck,this.source=c||defaultSource;}get channel(){return this._channel||(this._channel=new BroadcastChannel(this.channelName)),this._channel}notifyIfUpdated({first:a,second:b,cacheName:c,url:d}){isType({cacheName:c},'string'),responsesAreSame({first:a,second:b,headersToCheck:this.headersToCheck})||broadcastUpdate({cacheName:c,url:d,channel:this.channel,source:this.source});}}
class BroadcastCacheUpdatePlugin extends BroadcastCacheUpdate{cacheDidUpdate({cacheName:a,oldResponse:b,newResponse:c,url:d}){isType({cacheName:a},'string'),isInstance({newResponse:c},Response),b&&this.notifyIfUpdated({cacheName:a,first:b,second:c,url:d});}}
class Strategies{constructor({cacheId:a}={}){this._cacheId=a;}cacheFirst(a){return this._getCachingMechanism(CacheFirst,a)}cacheOnly(a){return this._getCachingMechanism(CacheOnly,a)}networkFirst(a){return this._getCachingMechanism(NetworkFirst,a)}networkOnly(a){return this._getCachingMechanism(NetworkOnly,a)}staleWhileRevalidate(a){return this._getCachingMechanism(StaleWhileRevalidate,a)}_getCachingMechanism(a,b={}){const c={cacheExpiration:CacheExpirationPlugin,broadcastCacheUpdate:BroadcastCacheUpdatePlugin,cacheableResponse:CacheableResponsePlugin},d={plugins:[]};b.excludeCacheId||(d.cacheId=this._cacheId),b.cacheName&&(d.cacheName=b.cacheName);const e=Object.keys(c);return e.forEach((f)=>{if(b[f]){const g=c[f],h=b[f];d.plugins.push(new g(h));}}),b.plugins&&b.plugins.forEach((f)=>{d.plugins.push(f);}),b.requestWrapper=new RequestWrapper(d),new a(b)}}
const errorMessageFactory=(a,b)=>{let c=`An error was thrown by workbox with error code: `+`;'${a}'`;return b&&(c+=` with extras: '${JSON.stringify(b)}'`),c};
class WorkboxError extends Error{constructor(a,b){super(),this.name=a,this.message=errorMessageFactory(a,b),b&&(this.extras=b);}}
class BaseCacheManager{constructor({cacheName:a,cacheId:b,plugins:c}={}){if(b&&('string'!=typeof b||0===b.length))throw new WorkboxError('bad-cache-id',{cacheId:b});this._entriesToCache=new Map,this._requestWrapper=new RequestWrapper({cacheName:a,cacheId:b,plugins:c,fetchOptions:{credentials:'same-origin'}});}_addEntries(a){this._parsedCacheUrls=null,a.forEach((b)=>{this._addEntryToInstallList(this._parseEntry(b));});}getCacheName(){return this._requestWrapper.cacheName}getCachedUrls(){return this._parsedCacheUrls||(this._parsedCacheUrls=Array.from(this._entriesToCache.keys()).map((a)=>new URL(a,location).href)),this._parsedCacheUrls}_addEntryToInstallList(a){const b=a.entryID,c=this._entriesToCache.get(a.entryID);return c?void this._onDuplicateInstallEntryFound(a,c):void this._entriesToCache.set(b,a)}async install(){if(0===this._entriesToCache.size)return[];const a=[];return this._entriesToCache.forEach((b)=>{a.push(this._cacheEntry(b));}),Promise.all(a)}async _cacheEntry(a){const b=await this._isAlreadyCached(a),c={url:a.request.url,revision:a.revision,wasUpdated:!b};if(b)return c;try{return await this._requestWrapper.fetchAndCache({request:a.getNetworkRequest(),waitOnCache:!0,cacheKey:a.request,cleanRedirects:!0}),await this._onEntryCached(a),c}catch(d){throw new WorkboxError('request-not-cached',{url:a.request.url,error:d})}}async cleanup(){if(!(await caches.has(this.getCacheName())))return;const a=[];this._entriesToCache.forEach((e)=>{a.push(e.request.url);});const b=await this._getCache(),c=await b.keys(),d=c.filter((e)=>!a.includes(e.url));return Promise.all(d.map(async(e)=>{await b.delete(e),await this._onEntryDeleted(e.url);}))}async _getCache(){return this._cache||(this._cache=await caches.open(this.getCacheName())),this._cache}_parseEntry(){throw new WorkboxError('requires-overriding')}_onDuplicateEntryFound(){throw new WorkboxError('requires-overriding')}_isAlreadyCached(){throw new WorkboxError('requires-overriding')}_onEntryCached(){throw new WorkboxError('requires-overriding')}_onEntryDeleted(){throw new WorkboxError('requires-overriding')}}
class IDBHelper{constructor(a,b,c){if(a==void 0||b==void 0||c==void 0)throw Error('name, version, storeName must be passed to the constructor.');this._name=a,this._version=b,this._storeName=c;}_getDb(){return this._dbPromise?this._dbPromise:(this._dbPromise=idb.open(this._name,this._version,(a)=>{a.createObjectStore(this._storeName);}).then((a)=>{return a}),this._dbPromise)}close(){return this._dbPromise?this._dbPromise.then((a)=>{a.close(),this._dbPromise=null;}):void 0}put(a,b){return this._getDb().then((c)=>{const d=c.transaction(this._storeName,'readwrite'),e=d.objectStore(this._storeName);return e.put(b,a),d.complete})}delete(a){return this._getDb().then((b)=>{const c=b.transaction(this._storeName,'readwrite'),d=c.objectStore(this._storeName);return d.delete(a),c.complete})}get(a){return this._getDb().then((b)=>{return b.transaction(this._storeName).objectStore(this._storeName).get(a)})}getAllValues(){return this._getDb().then((a)=>{return a.transaction(this._storeName).objectStore(this._storeName).getAll()})}getAllKeys(){return this._getDb().then((a)=>{return a.transaction(this._storeName).objectStore(this._storeName).getAllKeys()})}}
const cacheBustParamName='_workbox-precaching';const version='v1';const dbName='workbox-precaching';const dbVersion='1';const dbStorename='asset-revisions';let tmpRevisionedCacheName=`workbox-precaching-revisioned-${version}`;self&&self.registration&&(tmpRevisionedCacheName+=`-${self.registration.scope}`);const defaultRevisionedCacheName=tmpRevisionedCacheName;
class RevisionDetailsModel{constructor(){this._idbHelper=new IDBHelper(dbName,dbVersion,dbStorename);}get(a){return this._idbHelper.get(a)}put(a,b){return this._idbHelper.put(a,b)}delete(a){return this._idbHelper.delete(a)}_close(){this._idbHelper.close();}}
class BaseCacheEntry{constructor({entryID:a,revision:b,request:c,cacheBust:d}){this.entryID=a,this.revision=b,this.request=c,this.cacheBust=d;}getNetworkRequest(){if(!0!==this.cacheBust)return this.request;let a=this.request.url;const b={};if(!0===this.cacheBust)if('cache'in Request.prototype)b.cache='reload';else{const c=new URL(a,location);c.search+=(c.search?'&':'')+encodeURIComponent(cacheBustParamName)+'='+encodeURIComponent(this.revision),a=c.toString();}return new Request(a,b)}}
class StringCacheEntry extends BaseCacheEntry{constructor(a){if(isType({url:a},'string'),0===a.length)throw new WorkboxError('invalid-string-entry',{url:a});super({entryID:a,revision:a,request:new Request(a),cacheBust:!1});}}
class ObjectCacheEntry extends BaseCacheEntry{constructor({entryID:a,revision:b,url:c,cacheBust:d}){if('undefined'!=typeof b&&(isType({revision:b},'string'),0===b.length))throw new WorkboxError('invalid-object-entry',{problemParam:'revision',problemValue:b});if('undefined'==typeof d&&(d=!!b),isType({cacheBust:d},'boolean'),isType({url:c},'string'),0===c.length)throw new WorkboxError('invalid-object-entry',{problemParam:'url',problemValue:c});if('undefined'==typeof a)a=new URL(c,location).toString();else if(0===a.length)throw new WorkboxError('invalid-object-entry',{problemParam:'entryID',problemValue:a});super({entryID:a,revision:b||c,request:new Request(c),cacheBust:d});}}
class RevisionedCacheManager extends BaseCacheManager{constructor(a={}){a.cacheName=a.cacheName||defaultRevisionedCacheName,super(a),this._revisionDetailsModel=new RevisionDetailsModel;}addToCacheList({revisionedFiles:a}={}){isInstance({revisionedFiles:a},Array),super._addEntries(a);const b=a.filter((c)=>'string'==typeof c||!c.revision);0<b.length&&logHelper.debug({that:this,message:`Some precache entries are URLs without separate revision
fields. If the URLs themselves do not contain revisioning info,
like a hash or a version number, your users won't receive updates.`,data:{"URLs without revision fields":JSON.stringify(b),"Examples of safe, versioned URLs":`'/path/file.abcd1234.css' or '/v1.0.0/file.js'`,"Examples of dangerous, unversioned URLs":`'index.html' or '/path/file.css' or '/latest/file.js'`}});}_parseEntry(a){if(null===a)throw new WorkboxError('unexpected-precache-entry',{input:a});let b;switch(typeof a){case'string':b=new StringCacheEntry(a);break;case'object':b=new ObjectCacheEntry(a);break;default:throw new WorkboxError('unexpected-precache-entry',{input:a});}return b}_onDuplicateInstallEntryFound(a,b){if(b.revision!==a.revision)throw new WorkboxError('duplicate-entry-diff-revisions',{firstEntry:{url:b.request.url,revision:b.revision},secondEntry:{url:a.request.url,revision:a.revision}})}async _isAlreadyCached(a){const b=await this._revisionDetailsModel.get(a.entryID);if(b!==a.revision)return!1;const c=await this._getCache(),d=await c.match(a.request);return!!d}async _onEntryCached(a){await this._revisionDetailsModel.put(a.entryID,a.revision);}async _onEntryDeleted(a){await this._revisionDetailsModel.delete(a);}_close(){this._revisionDetailsModel._close();}cleanup(){return super.cleanup().then(()=>{return this._close()})}_createLogFriendlyString(a){let b=`\n`;return a.forEach((c)=>{b+=` URL: '${c.url}' Revision: `+`'${c.revision}'\n`;}),b}install(){return super.install().then((a)=>{const b=[],c=[];a.forEach((e)=>{e.wasUpdated?b.push({url:e.url,revision:e.revision}):c.push({url:e.url,revision:e.revision});});const d={};return 0<b.length&&(d['New / Updated Precache URL\'s']=this._createLogFriendlyString(b)),0<c.length&&(d['Up-to-date Precache URL\'s']=this._createLogFriendlyString(c)),logHelper.log({message:`Precache Details: ${b.length} requests `+`were added or updated and `+`${c.length} request are already `+`cached and up-to-date.`,data:d}),a})}}
if(!isServiceWorkerGlobalScope())throw new WorkboxError('not-in-sw');
class WorkboxSW$1{constructor({cacheId:a,skipWaiting:b,clientsClaim:c,handleFetch:d=!0,directoryIndex:e='index.html',precacheChannelName:f='precache-updates',ignoreUrlParametersMatching:g=[/^utm_/]}={}){if(!isServiceWorkerGlobalScope())throw ErrorFactory.createError('not-in-sw');if(isDevBuild()&&(isLocalhost()?logHelper.debug({message:'Welcome to Workbox!',data:{"📖":'Read the guides and documentation\nhttps://workboxjs.org/',"❓":'Use the [workbox] tag on StackOverflow to ask questions\nhttps://stackoverflow.com/questions/ask?tags=workbox',"🐛":'Found a bug? Report it on GitHub\nhttps://github.com/GoogleChrome/workbox/issues/new'}}):logHelper.warn(`This appears to be a production server. Please switch
to the smaller, optimized production build of Workbox.`)),a&&('string'!=typeof a||0===a.length))throw ErrorFactory.createError('bad-cache-id');if(b&&'boolean'!=typeof b)throw ErrorFactory.createError('bad-skip-waiting');if(c&&'boolean'!=typeof c)throw ErrorFactory.createError('bad-clients-claim');if('undefined'!=typeof e)if(!1===e||null===e)e=!1;else if('string'!=typeof e||0===e.length)throw ErrorFactory.createError('bad-directory-index');const h=[];f&&h.push(new BroadcastCacheUpdatePlugin({channelName:f,source:registration&&registration.scope?registration.scope:location})),this._runtimeCacheName=getDefaultCacheName({cacheId:a}),this._revisionedCacheManager=new RevisionedCacheManager({cacheId:a,plugins:h}),this._strategies=new Strategies({cacheId:a}),this._router=new Router$$1(this._revisionedCacheManager.getCacheName()),d&&this._router.addFetchListener(),this._registerInstallActivateEvents(b,c),this._registerDefaultRoutes(g,e);}precache(a){if(!Array.isArray(a))throw ErrorFactory.createError('bad-revisioned-cache-list');this._revisionedCacheManager.addToCacheList({revisionedFiles:a});}get router(){return this._router}get strategies(){return this._strategies}get runtimeCacheName(){return this._runtimeCacheName}_registerInstallActivateEvents(a,b){self.addEventListener('install',(c)=>{const d=this._revisionedCacheManager.getCachedUrls();0<d.length&&logHelper.debug({that:this,message:`The precached URLs will automatically be served using a
cache-first strategy.`,data:{"Precached URLs":JSON.stringify(d)}}),c.waitUntil(this._revisionedCacheManager.install().then(()=>{if(a)return self.skipWaiting()}));}),self.addEventListener('activate',(c)=>{c.waitUntil(this._revisionedCacheManager.cleanup().then(()=>{if(b)return self.clients.claim()}));});}_registerDefaultRoutes(a,b){const c=[];(a||b)&&c.push(this._getCacheMatchPlugin(a,b));const d=this.strategies.cacheFirst({cacheName:this._revisionedCacheManager.getCacheName(),plugins:c,excludeCacheId:!0});this.router.registerRoute(({url:f})=>{f.hash='';const g=this._revisionedCacheManager.getCachedUrls();if(-1!==g.indexOf(f.href))return!0;let h=this._removeIgnoreUrlParams(f.href,a);return-1!==g.indexOf(h.href)||b&&h.pathname.endsWith('/')&&(h.pathname+=b,-1!==g.indexOf(h.href))},d);}_getCacheMatchPlugin(a,b){return{cachedResponseWillBeUsed:async({request:d,cache:e,cachedResponse:f,matchOptions:g})=>{if(f)return f;let h=this._removeIgnoreUrlParams(d.url,a);return e.match(h.toString(),g).then((i)=>{return!i&&h.pathname.endsWith('/')?(h.pathname+=b,e.match(h.toString(),g)):i})}}}_removeIgnoreUrlParams(a,b){const c=new URL(a),d=c.search.slice(1),e=d.split('&'),f=e.map((i)=>{return i.split('=')}),g=f.filter((i)=>{return b.every((j)=>{return!j.test(i[0])})}),h=g.map((i)=>{return i.join('=')});return c.search=h.join('&'),c}}
return WorkboxSW$1;
}());
//# sourceMappingURL=workbox-sw.prod.v2.0.1.js.map
File diff suppressed because one or more lines are too long
-20
View File
@@ -1,20 +0,0 @@
import path from 'path';
import url from 'url';
import { createJestStencilPreset } from 'jest-stencil-runner';
const __dirname = path.dirname(url.fileURLToPath(import.meta.url));
export default createJestStencilPreset({
rootDir: __dirname,
// Add any additional Jest configuration here
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
collectCoverageFrom: [
'src/**/*.{ts,tsx}',
'!src/**/*.d.ts',
],
testMatch: [
'**/__tests__/**/*.(ts|tsx|js)',
'**/*.(test|spec).(ts|tsx|js)'
]
});
-2
View File
@@ -1,2 +0,0 @@
const Stencil = require('@stencil/core');
Stencil.Build.isBrowser = true;
+4937 -11333
View File
File diff suppressed because it is too large Load Diff
+29 -85
View File
@@ -1,102 +1,50 @@
{
"name": "ionicons",
"version": "8.1.1",
"version": "4.0.0-4",
"description": "Premium icons for Ionic.",
"files": [
"components/",
"dist/",
"icons/"
"dist/"
],
"main": "./dist/index.cjs.js",
"module": "./dist/index.js",
"types": "dist/types/index.d.ts",
"unpkg": "dist/ionicons/ionicons.esm.js",
"jsdelivr": "dist/ionicons/ionicons.esm.js",
"browser": "dist/ionicons.js",
"main": "dist/collection/index.js",
"types": "dist/collection/index.d.ts",
"collection": "dist/collection/collection-manifest.json",
"collection:main": "dist/collection/index.js",
"exports": {
".": {
"types": "./dist/types/index.d.ts",
"import": "./dist/index.js",
"require": "./dist/index.cjs.js"
},
"./loader": {
"types": "./dist/loader/index.d.ts",
"import": "./dist/loader/index.js",
"require": "./dist/loader/index.cjs.js"
},
"./components": {
"types": "./components/index.d.ts",
"import": "./components/index.js"
},
"./components/ion-icon.js": {
"types": "./components/ion-icon.d.ts",
"import": "./components/ion-icon.js"
},
"./icons": {
"types": "./icons/index.d.ts",
"import": "./icons/index.mjs",
"require": "./icons/index.js"
},
"./dist/ionicons.json": {
"default": "./dist/ionicons.json"
}
},
"scripts": {
"build": "run-s clean build.*",
"build.files": "tsx scripts/build.ts",
"build.component": "stencil build",
"build.collection": "tsx scripts/collection-copy.ts",
"clean": "rimraf dist components icons www",
"lint": "npm run prettier -- --write",
"prettier": "prettier \"./src/**/*.{html,ts,tsx,js,jsx,scss}\"",
"prettier.dry-run": "npm run prettier -- --list-different",
"start": "run-s build.files && stencil build --dev --watch --serve",
"test": "run-s test.spec test.e2e",
"test.spec": "jest",
"test.e2e": "playwright test",
"test.e2e.install": "playwright install && playwright install-deps"
},
"dependencies": {
"@stencil/core": "^4.43.5"
"build": "npm run build.icon && python scripts/generate.py && npm run svg-to-js && npm run png",
"build.icon": "stencil build",
"build.docs": "stencil build --prerender --config src/docs/stencil.config.js",
"dev.docs": "sd concurrent \"stencil build --dev --config src/docs/stencil.config.js --watch\" \"httpster -d docs/\" ",
"svg-to-js": "node scripts/svg-to-js.js",
"png": "node scripts/png.js",
"deploy": "np --any-branch",
"prepublishOnly": "npm run build",
"serve": "stencil-dev-server",
"start": "npm run dev"
},
"devDependencies": {
"@axe-core/playwright": "^4.12.1",
"@playwright/test": "^1.61.1",
"@types/fs-extra": "^11.0.4",
"@types/jest": "^30.0.0",
"@types/node": "^22.15.3",
"@types/svgo": "^3.0.0",
"fs-extra": "^11.3.0",
"jest": "^30.0.4",
"jest-cli": "^30.0.4",
"jest-stencil-runner": "^0.0.20",
"npm-run-all2": "^8.0.4",
"prettier": "^3.6.2",
"puppeteer": "^24.12.0",
"rimraf": "^6.0.1",
"semver": "^7.7.2",
"serve": "^14.2.4",
"svgo": "4.0.0",
"tsx": "^4.20.3",
"typescript": "^5.8.3"
"@ionic/jpml": "0.0.3",
"@stencil/core": "next",
"@stencil/utils": "latest",
"fs-extra": "^4.0.2",
"httpster": "^1.0.3",
"np": "2.16.0",
"svg2png": "^4.1.1"
},
"keywords": [
"icon pack",
"ionicons",
"ionic",
"icon",
"svg",
"font",
"mobile",
"web component",
"component",
"custom element",
"material design",
"ios"
"custom element"
],
"homepage": "http://ionicons.com/",
"author": {
"name": "Ben Sperry",
"web": "https://twitter.com/benjsperry"
"web": "https://twitter.com/bensperry"
},
"contributors": [
{
@@ -106,14 +54,10 @@
],
"repository": {
"type": "git",
"url": "https://github.com/ionic-team/ionicons.git"
"url": "https://github.com/driftyco/ionicons.git"
},
"bugs": {
"url": "https://github.com/ionic-team/ionicons/issues"
"url": "https://github.com/driftyco/ionicons/issues"
},
"license": "MIT",
"sideEffects": [
"icons/imports/"
],
"web-types": "dist/ionic.web-types.json"
"license": "MIT"
}
-102
View File
@@ -1,102 +0,0 @@
import type { PlaywrightTestConfig } from '@playwright/test';
import { devices, expect } from '@playwright/test';
const projects: PlaywrightTestConfig['projects'] = [
{
/**
* This is really just desktop Firefox
* but with a mobile viewport.
*/
name: 'Mobile Firefox',
use: {
browserName: 'firefox',
/**
* This is the Pixel 5 configuration.
* We can't use devices['Pixel 5']
* because the "isMobile" option is
* not supported on Firefox.
*/
viewport: {
width: 393,
height: 727
}
},
},
{
name: 'Mobile Chrome',
use: {
browserName: 'chromium',
...devices['Pixel 5']
}
},
{
name: 'Mobile Safari',
use: {
browserName: 'webkit',
...devices['iPhone 12']
}
}
];
/**
* See https://playwright.dev/docs/test-configuration.
*/
const config: PlaywrightTestConfig = {
testMatch: '*.e2e.ts',
expect: {
/**
* Maximum time expect() should wait for the condition to be met.
* For example in `await expect(locator).toHaveText();`
*/
timeout: 5000,
/**
* Configure screenshot comparison settings
* to be more tolerant of minor visual differences
*/
toHaveScreenshot: {
// Increase the threshold to allow for small font rendering differences
// This sets the maximum allowed ratio of pixels that can be different
maxDiffPixelRatio: 0.02, // Allow up to 2% of pixels to be different
// Alternatively, you can use absolute pixel count
// maxDiffPixels: 100, // Allow up to 100 pixels to be different
// Add a threshold for per-pixel difference to handle anti-aliasing
threshold: 0.2, // Default is 0.1
}
},
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
/* Opt out of parallel tests on CI. */
workers: process.env.CI ? 1 : undefined,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: 'html',
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */
actionTimeout: 0,
/* Base URL to use in actions like `await page.goto('/')`. */
// baseURL: 'http://localhost:3000',
/**
* All failed tests should create
* a trace file for easier debugging.
*
* See https://playwright.dev/docs/trace-viewer
*/
trace: 'retain-on-failure',
baseURL: 'http://localhost:3333',
},
/* Configure projects for major browsers */
projects,
webServer: {
command: 'serve www -p 3333',
port: 3333,
reuseExistingServer: !process.env.CI
}
};
export default config;
+5 -140
View File
@@ -1,150 +1,15 @@
# Ionicons
[Ionicons](http://ionicons.com/) is a completely open-source icon set with 1,300 icons crafted for web, iOS, Android, and desktop apps. Ionicons was built for [Ionic Framework](https://ionicframework.com/), so icons have both Material Design and iOS versions.
Note: All brand icons are trademarks of their respective owners. The use of these trademarks does not indicate endorsement of the trademark holder by Ionic, nor vice versa.
Premium icons for [Ionic](http://ionicframework.com/). Designed by [@benjsperry](https://twitter.com/benjsperry).
Note: All brand icons are trademarks of their respective owners. The use of these trademarks does not indicate endorsement of the trademark holder by Drifty, nor vice versa.
Visit [ionicons.com](http://ionicons.com) and check out the search feature, which has keywords identifying common icon names and styles. For example, if you search for “arrow” we call up every icon that could possibly be used as an arrow. We’ve also included each icon’s class name for easy copy/pasting when you’re developing!
We intend for this icon pack to be used with [Ionic](http://ionicframework.com/), but it’s by no means limited to it. Use them wherever you see fit, personal or commercial. They are free to use and licensed under [MIT](http://opensource.org/licenses/MIT).
## Contributing
Thanks for your interest in contributing! Read up on our guidelines for
[contributing](https://github.com/ionic-team/ionicons/blob/main/CONTRIBUTING.md)
and then look through our issues with a [help wanted](https://github.com/ionic-team/ionicons/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22)
label.
## Using the Web Component
The Ionicons Web Component is an easy and performant way to use Ionicons in your app. The component will dynamically load an SVG for each icon, so your app is only requesting the icons that you need.
Also note that only visible icons are loaded, and icons that are "below the fold" and hidden from the user's view do not make fetch requests for the svg resource.
### Installation
If you're using [Ionic Framework](https://ionicframework.com/), Ionicons is packaged by default, so no installation is necessary. Want to use Ionicons without Ionic Framework? Place the following `<script>` near the end of your page, right before the closing `</body>` tag, to enable them.
```html
<script type="module" src="https://esm.sh/ionicons@latest/loader"></script>
<script nomodule src="https://esm.sh/ionicons@latest/loader"></script>
```
you can replace `latest` to pick any version of Ionicon, e.g.:
```html
<script type="module" src="https://esm.sh/ionicons@8.0.0/loader"></script>
<script nomodule src="https://esm.sh/ionicons@8.0.0/loader"></script>
```
### Basic usage
To use a built-in icon from the Ionicons package, populate the `name` attribute on the ion-icon component:
```html
<ion-icon name="heart"></ion-icon>
```
### Custom icons
To use a custom SVG, provide its url in the `src` attribute to request the external SVG file. The `src` attribute works the same as `<img src="...">` in that the url must be accessible from the webpage that's making a request for the image. Additionally, the external file can only be a valid svg and does not allow scripts or events within the svg element.
```html
<ion-icon src="/path/to/external/file.svg"></ion-icon>
```
#### Custom Asset Path
If you have a different set of icons you would like to load or if the Ionicon icons are hosted on a different page or path, you can set the asset url from which Ionicons pulls the icons via:
```ts
import { setAssetPath, addIcons } from 'ionicons';
import { add, logoIonic, save } from 'ionicons/icons';
// set root path for loading icons to "<root>/public/svg"
setAssetPath(`${window.location.origin}/public/svg/`);
// only load specific icons
addIcons({ add, logoIonic, save });
```
This allows the use of named icons like this:
```html
<!-- now pulls the svg from "<root>/public/svg/heart.svg" -->
<ion-icon name="heart"></ion-icon>
```
## Variants
Each app icon in Ionicons has a `filled`, `outline` and `sharp` variant. These different variants are provided to make your app feel native to a variety of platforms. The filled variant uses the default name without a suffix. Note: Logo icons do not have outline or sharp variants.
```html
<ion-icon name="heart"></ion-icon> <!--filled-->
<ion-icon name="heart-outline"></ion-icon> <!--outline-->
<ion-icon name="heart-sharp"></ion-icon> <!--sharp-->
```
### Platform specificity
When using icons in Ionic Framework you can specify different icons per platform. Use the `md` and `ios` attributes and provide the platform-specific icon/variant name.
```html
<ion-icon ios="heart-outline" md="heart-sharp"></ion-icon>
```
## Size
To specify the icon size, you can use the size attribute for our pre-defined font sizes.
```html
<ion-icon size="small"></ion-icon>
<ion-icon size="large"></ion-icon>
```
Or you can set a specific size by applying the `font-size` CSS property on the `ion-icon` component. It's recommended to use pixel sizes that are a multiple of 8 (8, 16, 32, 64, etc.)
```css
ion-icon {
font-size: 64px;
}
```
## Color
Specify the icon color by applying the `color` CSS property on the `ion-icon` component.
```css
ion-icon {
color: blue;
}
```
## Stroke width
When using an `outline` icon variant it is possible to adjust the stroke width, for improved visual balance relative to the icon's size or relative to the width of adjacent text. You can set a specific size by applying the `--ionicon-stroke-width` CSS custom property to the `ion-icon` component. The default value is 32px.
```html
<ion-icon name="heart-outline"></ion-icon>
```
```css
ion-icon {
--ionicon-stroke-width: 16px;
}
```
## Migrating from v4
See the [5.0 release notes](https://github.com/ionic-team/ionicons/releases/tag/5.0.0) for a list of icon deletions/renames.
## License
Ionicons is licensed under the [MIT license](http://opensource.org/licenses/MIT).
## Related
* [Ionicons Homepage](http://ionicons.com/)
* [Ionic Framework](https://ionicframework.com/)
* [Ionic Discord](https://ionic.link/discord)
* [Ionic Forum](https://forum.ionicframework.com/)
* [Stencil](https://stenciljs.com/)
* [Capacitor](https://capacitorjs.com/)
-421
View File
@@ -1,421 +0,0 @@
import path from 'node:path';
import fs from 'fs-extra';
import { optimize } from 'svgo';
import { webComponentPassPlugins, sourcePassPlugins } from './plugins';
import { reservedKeywords } from './constants';
import pkgData from '../package.json' with { type: 'json' };
import type { SvgData } from './types';
async function build(rootDir: string) {
try {
const srcDir = path.join(rootDir, 'src');
const srcSvgDir = path.join(srcDir, 'svg');
const iconDir = path.join(rootDir, 'icons');
const distDir = path.join(rootDir, 'dist');
const distIoniconsDir = path.join(distDir, 'ionicons');
const distSvgDir = path.join(distDir, 'svg');
const optimizedSvgDir = path.join(distIoniconsDir, 'svg');
/**
* Create the directories first, then empty them
* This ensures they exist before we try to write files to them
*/
await Promise.all([
fs.ensureDir(iconDir),
fs.ensureDir(distDir),
fs.ensureDir(distSvgDir),
fs.ensureDir(optimizedSvgDir),
fs.ensureDir(distIoniconsDir),
]);
/**
* Empty the directories
*/
await Promise.all([
fs.emptyDir(iconDir),
fs.emptyDir(distDir),
fs.emptyDir(distSvgDir),
fs.emptyDir(optimizedSvgDir),
fs.emptyDir(distIoniconsDir),
]);
const version = pkgData.version as string;
const srcSvgData = await getSvgs(srcSvgDir, distSvgDir, optimizedSvgDir);
await optimizeSvgs(srcSvgData);
await Promise.all([
createDataJson(version, srcDir, distDir, srcSvgData),
createIconPackage(version, iconDir, srcSvgData),
]);
const svgSymbolsContent = await createSvgSymbols(version, distDir, srcSvgData);
await createCheatsheet(version, rootDir, distDir, svgSymbolsContent, srcSvgData);
await createWebTypes(version, rootDir, distDir, srcSvgData);
await copyToTesting(rootDir, distDir, srcSvgData);
} catch (e) {
console.error(e);
process.exit(1);
}
}
async function optimizeSvgs(srcSvgData: SvgData[]) {
await Promise.all(
srcSvgData.map(async (svgData) => {
return optimizeSvg(svgData);
}),
);
}
async function optimizeSvg(svgData: SvgData) {
const srcSvgContent = await fs.readFile(svgData.srcFilePath, 'utf8');
const optimizedSvg = await optimize(srcSvgContent, { path: svgData.srcFilePath });
const webComponentSvg = await optimize(optimizedSvg.data, {
path: svgData.srcFilePath,
plugins: webComponentPassPlugins,
});
const sourceSvg = await optimize(optimizedSvg.data, {
path: svgData.srcFilePath,
plugins: sourcePassPlugins,
});
// Ensure directories exist before writing files
await Promise.all([
fs.ensureDir(path.dirname(svgData.optimizedFilePath)),
fs.ensureDir(path.dirname(svgData.distSvgFilePath)),
]);
svgData.optimizedSvgContent = webComponentSvg.data;
await Promise.all([
fs.writeFile(svgData.optimizedFilePath, svgData.optimizedSvgContent),
fs.writeFile(svgData.distSvgFilePath, sourceSvg.data),
]);
}
async function copyToTesting(rootDir: string, distDir: string, srcSvgData: SvgData[]) {
const testDir = path.join(rootDir, 'www');
const testBuildDir = path.join(testDir, 'build');
const testSvgDir = path.join(testBuildDir, 'svg');
const cheatsheetDir = path.join(testDir, 'icon', 'test', 'cheatsheet');
const version = (await fs.readJson(path.join(rootDir, 'package.json'))).version;
// Ensure all directories exist
await Promise.all([
fs.ensureDir(testDir),
fs.ensureDir(testBuildDir),
fs.ensureDir(testSvgDir),
fs.ensureDir(cheatsheetDir),
]);
await Promise.all(
srcSvgData
.filter((svgData): svgData is SvgData & { optimizedSvgContent: string } => Boolean(svgData.optimizedSvgContent))
.map(async (svgData) => {
const testSvgFilePath = path.join(testSvgDir, svgData.fileName);
await fs.writeFile(testSvgFilePath, svgData.optimizedSvgContent);
}),
);
const wwwCheatsheetFilePath = path.join(cheatsheetDir, 'index.html');
const srcIndexFilePath = path.join(rootDir, 'src', 'components', 'icon', 'test', 'index.html');
const testIndexFilePath = path.join(testDir, 'index.html');
await fs.copyFile(srcIndexFilePath, testIndexFilePath);
// Generate the cheatsheet with placeholders filled in
const svgSymbolsContent = await fs.readFile(path.join(distDir, 'ionicons.symbols.svg'), 'utf8');
const c = srcSvgData.map(
(svgData) =>
`<a href="/svg/${svgData.fileName}"><svg><use href="#${svgData.iconName}" xlink:href="#${svgData.iconName}"/></svg></a>`,
);
c.push(svgSymbolsContent);
const cheatsheetTemplate = await fs.readFile(path.join(rootDir, 'scripts', 'cheatsheet-template.html'), 'utf8');
const cheatsheetHtml = cheatsheetTemplate
.replace(/{{version}}/g, version)
.replace(/{{count}}/g, srcSvgData.length.toString())
.replace(/{{content}}/g, c.join('\n'));
await fs.writeFile(wwwCheatsheetFilePath, cheatsheetHtml);
}
async function createSvgSymbols(version: string, distDir: string, srcSvgData: SvgData[]) {
srcSvgData = srcSvgData.sort((a, b) => {
if (a.iconName < b.iconName) return -1;
if (a.iconName > b.iconName) return 1;
return 0;
});
const symbolsSvgFilePath = path.join(distDir, 'ionicons.symbols.svg');
const lines = [
`<svg data-ionicons="${version}" style="display:none">`,
`<style>`,
`.ionicon {`,
` fill: currentColor;`,
` stroke: currentColor;`,
`}`,
`.ionicon-fill-none {`,
` fill: none;`,
`}`,
`.ionicon-stroke-width {`,
` stroke-width: 32px;`,
`}`,
`</style>`,
];
srcSvgData
.filter((svgData): svgData is SvgData & { optimizedSvgContent: string } => Boolean(svgData.optimizedSvgContent))
.forEach((svgData) => {
const svg = svgData.optimizedSvgContent
.replace(`<svg xmlns="http://www.w3.org/2000/svg"`, `<symbol id="${svgData.iconName}"`)
.replace(`</svg>`, `</symbol>`);
lines.push(svg);
});
lines.push(`</svg>`, ``);
const content = lines.join('\n');
await fs.writeFile(symbolsSvgFilePath, content);
return content;
}
async function createCheatsheet(
version: string,
rootDir: string,
distDir: string,
svgSymbolsContent: string,
srcSvgData: SvgData[],
) {
const CheatsheetTmpFilePath = path.join(rootDir, 'scripts', 'cheatsheet-template.html');
const distCheatsheetFilePath = path.join(distDir, 'cheatsheet.html');
const c = srcSvgData.map(
(svgData) =>
`<a href="/svg/${svgData.fileName}"><svg><use href="#${svgData.iconName}" xlink:href="#${svgData.iconName}"/></svg></a>`,
);
c.push(svgSymbolsContent);
const html = (await fs.readFile(CheatsheetTmpFilePath, 'utf8'))
.replace(/{{version}}/g, version)
.replace(/{{count}}/g, srcSvgData.length.toString())
.replace(/{{content}}/g, c.join('\n'));
await fs.writeFile(distCheatsheetFilePath, html);
}
async function createWebTypes(version: string, rootDir: string, distDir: string, srcSvgData: SvgData[]) {
const srcWebTypeFilePath = path.join(rootDir, 'src/ionicons.web-types.json');
const distWebTypesFilePath = path.join(distDir, 'ionicons.web-types.json');
const webTypes = JSON.parse(await fs.readFile(srcWebTypeFilePath, 'utf8'));
webTypes.version = version;
const icons = webTypes.contributions.html.ionicons;
for (let data of srcSvgData) {
icons.push({
name: data.iconName,
icon: 'dist/svg/' + data.fileName,
});
}
const jsonStr = JSON.stringify(webTypes, null, 2) + '\n';
await fs.writeFile(distWebTypesFilePath, jsonStr);
}
async function getSvgs(srcSvgDir: string, distSvgDir: string, optimizedSvgDir: string): Promise<SvgData[]> {
const svgFiles = (await fs.readdir(srcSvgDir)).filter((fileName) => {
return !fileName.startsWith('.') && fileName.endsWith('.svg');
});
const svgData = await Promise.all(
svgFiles.map(async (fileName) => {
// fileName: airplane-outline.svg
if (fileName.toLowerCase() !== fileName) {
throw new Error(`svg filename "${fileName}" must be all lowercase`);
}
// srcFilePath: /src/svg/airplane-outline.svg
const srcFilePath = path.join(srcSvgDir, fileName);
// srcFilePath: /src/svg/airplane-outline.svg
const distSvgFilePath = path.join(distSvgDir, fileName);
// optimizedFilePath: /dist/ionicons/svg/airplane-outline.svg
const optimizedFilePath = path.join(optimizedSvgDir, fileName);
const dotSplit = fileName.split('.');
if (dotSplit.length > 2) {
throw new Error(`svg filename "${fileName}" cannot contain more than one period`);
}
// iconName: airplane-outline
const iconName = dotSplit[0];
if (reservedKeywords.has(iconName)) {
throw new Error(`svg icon name "${iconName}" is a reserved JavaScript keyword`);
}
// fileNameMjs: airplane-outline.mjs
const fileNameMjs = iconName + '.mjs';
// fileNameCjs: airplane-outline.mjs
const fileNameCjs = iconName + '.js';
// exportName: airplaneOutline
const exportName = camelize(iconName);
const title = toTitleCase(
fileName.replace('.svg', '').replace('-outline', '').replace('-sharp', '').replace(/-/g, ' '),
);
return {
fileName,
title,
srcFilePath,
distSvgFilePath,
srcSvgContent: await fs.readFile(srcFilePath, 'utf8'),
optimizedFilePath,
iconName,
fileNameMjs,
fileNameCjs,
exportName,
};
}),
);
return svgData.sort((a, b) => {
if (a.exportName < b.exportName) return -1;
if (a.exportName > b.exportName) return 1;
return 0;
});
}
async function createIconPackage(version: string, iconDir: string, srcSvgData: SvgData[]) {
await Promise.all([
createEsmIcons(version, iconDir, srcSvgData),
createCjsIcons(version, iconDir, srcSvgData),
createDtsIcons(version, iconDir, srcSvgData),
]);
}
async function createEsmIcons(version: string, iconDir: string, srcSvgData: SvgData[]) {
const iconEsmFilePath = path.join(iconDir, 'index.mjs');
const o = [`/* Ionicons v${version}, ES Modules */`, ``];
srcSvgData.forEach((svgData) => {
o.push(`export const ${svgData.exportName} = ${getDataUrl(svgData)}`);
});
await fs.writeFile(iconEsmFilePath, o.join('\n') + '\n');
}
async function createCjsIcons(version: string, iconDir: string, srcSvgData: SvgData[]) {
const iconCjsFilePath = path.join(iconDir, 'index.js');
const o = [`/* Ionicons v${version}, CommonJS */`, ``];
srcSvgData.forEach((svgData) => {
o.push(`exports.${svgData.exportName} = ${getDataUrl(svgData)}`);
});
await fs.writeFile(iconCjsFilePath, o.join('\n') + '\n');
}
async function createDtsIcons(version: string, iconDir: string, srcSvgData: SvgData[]) {
const iconDtsFilePath = path.join(iconDir, 'index.d.ts');
const o = [`/* Ionicons v${version}, Types */`, ``];
srcSvgData.forEach((svgData) => {
o.push(`export declare var ${svgData.exportName}: string;`);
});
await fs.writeFile(iconDtsFilePath, o.join('\n') + '\n');
}
function getDataUrl(svgData: SvgData) {
let svg = svgData.optimizedSvgContent;
if (!svg) {
throw new Error(`oh no! no optimized SVG content! ${svgData.fileName}`);
}
if (svg.includes(`'`)) {
throw new Error(`oh no! no single quotes allowed! ${svgData.fileName}`);
}
if (svg.includes(`\n`) || svg.includes(`\r`)) {
throw new Error(`oh no! no new lines allowed! ${svgData.fileName}`);
}
svg = svg.replace(/"/g, "'");
return `"data:image/svg+xml;utf8,${svg}"`;
}
async function createDataJson(version: string, srcDir: string, distDir: string, srcSvgData: SvgData[]) {
const srcDataJsonPath = path.join(srcDir, 'data.json');
const distDataJsonPath = path.join(distDir, 'ionicons.json');
const data = await fs.readJson(srcDataJsonPath).catch(() => ({}));
data.icons = data.icons || [];
// add new icons
srcSvgData.forEach((svgData) => {
if (!data.icons.some((i) => i.name === svgData.iconName)) {
data.icons.push({
name: svgData.iconName,
});
}
});
// remove dead icons
data.icons = data.icons.filter((dataIcon) => {
return srcSvgData.some((svgData) => dataIcon.name === svgData.iconName);
});
// sort
data.icons = data.icons.sort((a, b) => {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
});
data.icons.forEach((icon) => {
icon.tags = icon.tags || icon.name.split('-');
icon.tags = icon.tags.sort();
});
const srcJsonStr = JSON.stringify(data, null, 2) + '\n';
await fs.writeFile(srcDataJsonPath, srcJsonStr);
const distJsonData = {
name: 'ionicons',
version,
icons: data.icons,
};
const distJsonStr = JSON.stringify(distJsonData, null, 2) + '\n';
await fs.writeFile(distDataJsonPath, distJsonStr);
}
function camelize(text: string) {
let words = text.split(/[-_]/g); // ok one simple regexp.
return words[0].toLowerCase() + words.slice(1).map(upFirst).join('');
}
function upFirst(word: string) {
return word[0].toUpperCase() + word.toLowerCase().slice(1);
}
function toTitleCase(str: string) {
const s = str.trim().toLowerCase().split(' ');
for (var i = 0; i < s.length; i++) {
s[i] = s[i].charAt(0).toUpperCase() + s[i].slice(1);
}
return s.join(' ');
}
// let's do this
build(path.join(__dirname, '..'));
File diff suppressed because it is too large Load Diff
-10
View File
@@ -1,10 +0,0 @@
const semver = require('semver');
const getDevVersion = () => {
const originalVersion = require('../package.json').version;
const baseVersion = semver.inc(originalVersion, 'patch');
return baseVersion;
}
console.log(getDevVersion());
-37
View File
@@ -1,37 +0,0 @@
<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0" />
<title>Ionicons {{version}} Cheatsheet</title>
<script type="module" src="/build/ionicons.esm.js"></script>
<script nomodule src="/build/ionicons.js"></script>
<link rel="stylesheet" href="../styles.css" />
<script src="../header.js"></script>
</head>
<body>
<test-header></test-header>
<main>
<h1>Ionicons {{version}} Cheatsheet</h1>
<h3>{{count}} icons</h3>
{{content}}
</main>
</body>
<style>
svg {
width: 32px;
height: 32px;
}
a {
color: inherit;
text-decoration: none;
}
a:hover {
opacity: 0.7;
}
</style>
</html>
-44
View File
@@ -1,44 +0,0 @@
import fs from 'fs-extra';
import { join } from 'path';
async function collectionCopy(rootDir: string) {
// move optimized svgs to correct collection location
const optimizedSrc = join(rootDir, 'dist', 'ionicons', 'svg');
const collectionDest = join(rootDir, 'dist', 'collection', 'components', 'icon', 'svg');
await fs.copy(optimizedSrc, collectionDest);
// we don't to copy the src svgs to collection
await fs.remove(join(rootDir, 'dist', 'collection', 'svg'));
// We don't want to copy the test svg assets to collection
await fs.remove(join(rootDir, 'dist', 'collection', 'components', 'test'));
const cePackageDir = join(rootDir, 'components');
const cePackageJsonPath = join(cePackageDir, 'package.json');
const ceCjsPath = join(cePackageDir, 'index.cjs.js');
const emptyCjs = `/*empty cjs*/`;
await fs.writeFile(ceCjsPath, emptyCjs);
const cePackageJson = {
name: 'ionicons/components',
description: 'Ionicons custom element.',
main: './index.cjs.js',
module: './index.js',
types: './index.d.ts',
private: true,
};
await fs.writeFile(cePackageJsonPath, JSON.stringify(cePackageJson, null, 2));
// this is temporary!!!!
// removing the `type` from the d.ts export
// to make it easier for users migrating between
// of older versions of angular and typescript
// to the newer verisons, where the `type` keyword
// is used. This is a megahack, no doubt.
const typesDist = join(rootDir, 'dist', 'types', 'index.d.ts');
let types = await fs.readFile(typesDist, 'utf8');
types = types.replace('export type', 'export');
await fs.writeFile(typesDist, types);
}
collectionCopy(join(__dirname, '..'));
-52
View File
@@ -1,52 +0,0 @@
// https://mathiasbynens.be/notes/reserved-keywords
export const reservedKeywords = new Set([
'do',
'if',
'in',
'for',
'let',
'new',
'try',
'var',
'case',
'else',
'enum',
'eval',
'null',
'this',
'true',
'void',
'with',
'await',
'break',
'catch',
'class',
'const',
'false',
'super',
'throw',
'while',
'yield',
'delete',
'export',
'import',
'public',
'return',
'static',
'switch',
'typeof',
'default',
'extends',
'finally',
'package',
'private',
'continue',
'debugger',
'function',
'arguments',
'interface',
'protected',
'implements',
'instanceof',
'constructor',
]);
+466
View File
@@ -0,0 +1,466 @@
#!/usr/bin/env python
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is font utility code.
#
# The Initial Developer of the Original Code is Mozilla Corporation.
# Portions created by the Initial Developer are Copyright (C) 2009
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# John Daggett <jdaggett@mozilla.com>
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK ***** */
# eotlitetool.py - create EOT version of OpenType font for use with IE
#
# Usage: eotlitetool.py [-o output-filename] font1 [font2 ...]
#
# OpenType file structure
# http://www.microsoft.com/typography/otspec/otff.htm
#
# Types:
#
# BYTE 8-bit unsigned integer.
# CHAR 8-bit signed integer.
# USHORT 16-bit unsigned integer.
# SHORT 16-bit signed integer.
# ULONG 32-bit unsigned integer.
# Fixed 32-bit signed fixed-point number (16.16)
# LONGDATETIME Date represented in number of seconds since 12:00 midnight, January 1, 1904. The value is represented as a signed 64-bit integer.
#
# SFNT Header
#
# Fixed sfnt version // 0x00010000 for version 1.0.
# USHORT numTables // Number of tables.
# USHORT searchRange // (Maximum power of 2 <= numTables) x 16.
# USHORT entrySelector // Log2(maximum power of 2 <= numTables).
# USHORT rangeShift // NumTables x 16-searchRange.
#
# Table Directory
#
# ULONG tag // 4-byte identifier.
# ULONG checkSum // CheckSum for this table.
# ULONG offset // Offset from beginning of TrueType font file.
# ULONG length // Length of this table.
#
# OS/2 Table (Version 4)
#
# USHORT version // 0x0004
# SHORT xAvgCharWidth
# USHORT usWeightClass
# USHORT usWidthClass
# USHORT fsType
# SHORT ySubscriptXSize
# SHORT ySubscriptYSize
# SHORT ySubscriptXOffset
# SHORT ySubscriptYOffset
# SHORT ySuperscriptXSize
# SHORT ySuperscriptYSize
# SHORT ySuperscriptXOffset
# SHORT ySuperscriptYOffset
# SHORT yStrikeoutSize
# SHORT yStrikeoutPosition
# SHORT sFamilyClass
# BYTE panose[10]
# ULONG ulUnicodeRange1 // Bits 0-31
# ULONG ulUnicodeRange2 // Bits 32-63
# ULONG ulUnicodeRange3 // Bits 64-95
# ULONG ulUnicodeRange4 // Bits 96-127
# CHAR achVendID[4]
# USHORT fsSelection
# USHORT usFirstCharIndex
# USHORT usLastCharIndex
# SHORT sTypoAscender
# SHORT sTypoDescender
# SHORT sTypoLineGap
# USHORT usWinAscent
# USHORT usWinDescent
# ULONG ulCodePageRange1 // Bits 0-31
# ULONG ulCodePageRange2 // Bits 32-63
# SHORT sxHeight
# SHORT sCapHeight
# USHORT usDefaultChar
# USHORT usBreakChar
# USHORT usMaxContext
#
#
# The Naming Table is organized as follows:
#
# [name table header]
# [name records]
# [string data]
#
# Name Table Header
#
# USHORT format // Format selector (=0).
# USHORT count // Number of name records.
# USHORT stringOffset // Offset to start of string storage (from start of table).
#
# Name Record
#
# USHORT platformID // Platform ID.
# USHORT encodingID // Platform-specific encoding ID.
# USHORT languageID // Language ID.
# USHORT nameID // Name ID.
# USHORT length // String length (in bytes).
# USHORT offset // String offset from start of storage area (in bytes).
#
# head Table
#
# Fixed tableVersion // Table version number 0x00010000 for version 1.0.
# Fixed fontRevision // Set by font manufacturer.
# ULONG checkSumAdjustment // To compute: set it to 0, sum the entire font as ULONG, then store 0xB1B0AFBA - sum.
# ULONG magicNumber // Set to 0x5F0F3CF5.
# USHORT flags
# USHORT unitsPerEm // Valid range is from 16 to 16384. This value should be a power of 2 for fonts that have TrueType outlines.
# LONGDATETIME created // Number of seconds since 12:00 midnight, January 1, 1904. 64-bit integer
# LONGDATETIME modified // Number of seconds since 12:00 midnight, January 1, 1904. 64-bit integer
# SHORT xMin // For all glyph bounding boxes.
# SHORT yMin
# SHORT xMax
# SHORT yMax
# USHORT macStyle
# USHORT lowestRecPPEM // Smallest readable size in pixels.
# SHORT fontDirectionHint
# SHORT indexToLocFormat // 0 for short offsets, 1 for long.
# SHORT glyphDataFormat // 0 for current format.
#
#
#
# Embedded OpenType (EOT) file format
# http://www.w3.org/Submission/EOT/
#
# EOT version 0x00020001
#
# An EOT font consists of a header with the original OpenType font
# appended at the end. Most of the data in the EOT header is simply a
# copy of data from specific tables within the font data. The exceptions
# are the 'Flags' field and the root string name field. The root string
# is a set of names indicating domains for which the font data can be
# used. A null root string implies the font data can be used anywhere.
# The EOT header is in little-endian byte order but the font data remains
# in big-endian order as specified by the OpenType spec.
#
# Overall structure:
#
# [EOT header]
# [EOT name records]
# [font data]
#
# EOT header
#
# ULONG eotSize // Total structure length in bytes (including string and font data)
# ULONG fontDataSize // Length of the OpenType font (FontData) in bytes
# ULONG version // Version number of this format - 0x00020001
# ULONG flags // Processing Flags (0 == no special processing)
# BYTE fontPANOSE[10] // OS/2 Table panose
# BYTE charset // DEFAULT_CHARSET (0x01)
# BYTE italic // 0x01 if ITALIC in OS/2 Table fsSelection is set, 0 otherwise
# ULONG weight // OS/2 Table usWeightClass
# USHORT fsType // OS/2 Table fsType (specifies embedding permission flags)
# USHORT magicNumber // Magic number for EOT file - 0x504C.
# ULONG unicodeRange1 // OS/2 Table ulUnicodeRange1
# ULONG unicodeRange2 // OS/2 Table ulUnicodeRange2
# ULONG unicodeRange3 // OS/2 Table ulUnicodeRange3
# ULONG unicodeRange4 // OS/2 Table ulUnicodeRange4
# ULONG codePageRange1 // OS/2 Table ulCodePageRange1
# ULONG codePageRange2 // OS/2 Table ulCodePageRange2
# ULONG checkSumAdjustment // head Table CheckSumAdjustment
# ULONG reserved[4] // Reserved - must be 0
# USHORT padding1 // Padding - must be 0
#
# EOT name records
#
# USHORT FamilyNameSize // Font family name size in bytes
# BYTE FamilyName[FamilyNameSize] // Font family name (name ID = 1), little-endian UTF-16
# USHORT Padding2 // Padding - must be 0
#
# USHORT StyleNameSize // Style name size in bytes
# BYTE StyleName[StyleNameSize] // Style name (name ID = 2), little-endian UTF-16
# USHORT Padding3 // Padding - must be 0
#
# USHORT VersionNameSize // Version name size in bytes
# bytes VersionName[VersionNameSize] // Version name (name ID = 5), little-endian UTF-16
# USHORT Padding4 // Padding - must be 0
#
# USHORT FullNameSize // Full name size in bytes
# BYTE FullName[FullNameSize] // Full name (name ID = 4), little-endian UTF-16
# USHORT Padding5 // Padding - must be 0
#
# USHORT RootStringSize // Root string size in bytes
# BYTE RootString[RootStringSize] // Root string, little-endian UTF-16
import optparse
import struct
class FontError(Exception):
"""Error related to font handling"""
pass
def multichar(str):
vals = struct.unpack('4B', str[:4])
return (vals[0] << 24) + (vals[1] << 16) + (vals[2] << 8) + vals[3]
def multicharval(v):
return struct.pack('4B', (v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF)
class EOT:
EOT_VERSION = 0x00020001
EOT_MAGIC_NUMBER = 0x504c
EOT_DEFAULT_CHARSET = 0x01
EOT_FAMILY_NAME_INDEX = 0 # order of names in variable portion of EOT header
EOT_STYLE_NAME_INDEX = 1
EOT_VERSION_NAME_INDEX = 2
EOT_FULL_NAME_INDEX = 3
EOT_NUM_NAMES = 4
EOT_HEADER_PACK = '<4L10B2BL2H7L18x'
class OpenType:
SFNT_CFF = multichar('OTTO') # Postscript CFF SFNT version
SFNT_TRUE = 0x10000 # Standard TrueType version
SFNT_APPLE = multichar('true') # Apple TrueType version
SFNT_UNPACK = '>I4H'
TABLE_DIR_UNPACK = '>4I'
TABLE_HEAD = multichar('head') # TrueType table tags
TABLE_NAME = multichar('name')
TABLE_OS2 = multichar('OS/2')
TABLE_GLYF = multichar('glyf')
TABLE_CFF = multichar('CFF ')
OS2_FSSELECTION_ITALIC = 0x1
OS2_UNPACK = '>4xH2xH22x10B4L4xH14x2L'
HEAD_UNPACK = '>8xL'
NAME_RECORD_UNPACK = '>6H'
NAME_ID_FAMILY = 1
NAME_ID_STYLE = 2
NAME_ID_UNIQUE = 3
NAME_ID_FULL = 4
NAME_ID_VERSION = 5
NAME_ID_POSTSCRIPT = 6
PLATFORM_ID_UNICODE = 0 # Mac OS uses this typically
PLATFORM_ID_MICROSOFT = 3
ENCODING_ID_MICROSOFT_UNICODEBMP = 1 # with Microsoft platformID BMP-only Unicode encoding
LANG_ID_MICROSOFT_EN_US = 0x0409 # with Microsoft platformID EN US lang code
def eotname(ttf):
i = ttf.rfind('.')
if i != -1:
ttf = ttf[:i]
return ttf + '.eotlite'
def readfont(f):
data = open(f, 'rb').read()
return data
def get_table_directory(data):
"""read the SFNT header and table directory"""
datalen = len(data)
sfntsize = struct.calcsize(OpenType.SFNT_UNPACK)
if sfntsize > datalen:
raise FontError, 'truncated font data'
sfntvers, numTables = struct.unpack(OpenType.SFNT_UNPACK, data[:sfntsize])[:2]
if sfntvers != OpenType.SFNT_CFF and sfntvers != OpenType.SFNT_TRUE:
raise FontError, 'invalid font type';
font = {}
font['version'] = sfntvers
font['numTables'] = numTables
# create set of offsets, lengths for tables
table_dir_size = struct.calcsize(OpenType.TABLE_DIR_UNPACK)
if sfntsize + table_dir_size * numTables > datalen:
raise FontError, 'truncated font data, table directory extends past end of data'
table_dir = {}
for i in range(0, numTables):
start = sfntsize + i * table_dir_size
end = start + table_dir_size
tag, check, bongo, dirlen = struct.unpack(OpenType.TABLE_DIR_UNPACK, data[start:end])
table_dir[tag] = {'offset': bongo, 'length': dirlen, 'checksum': check}
font['tableDir'] = table_dir
return font
def get_name_records(nametable):
"""reads through the name records within name table"""
name = {}
# read the header
headersize = 6
count, strOffset = struct.unpack('>2H', nametable[2:6])
namerecsize = struct.calcsize(OpenType.NAME_RECORD_UNPACK)
if count * namerecsize + headersize > len(nametable):
raise FontError, 'names exceed size of name table'
name['count'] = count
name['strOffset'] = strOffset
# read through the name records
namerecs = {}
for i in range(0, count):
start = headersize + i * namerecsize
end = start + namerecsize
platformID, encodingID, languageID, nameID, namelen, offset = struct.unpack(OpenType.NAME_RECORD_UNPACK, nametable[start:end])
if platformID != OpenType.PLATFORM_ID_MICROSOFT or \
encodingID != OpenType.ENCODING_ID_MICROSOFT_UNICODEBMP or \
languageID != OpenType.LANG_ID_MICROSOFT_EN_US:
continue
namerecs[nameID] = {'offset': offset, 'length': namelen}
name['namerecords'] = namerecs
return name
def make_eot_name_headers(fontdata, nameTableDir):
"""extracts names from the name table and generates the names header portion of the EOT header"""
nameoffset = nameTableDir['offset']
namelen = nameTableDir['length']
name = get_name_records(fontdata[nameoffset : nameoffset + namelen])
namestroffset = name['strOffset']
namerecs = name['namerecords']
eotnames = (OpenType.NAME_ID_FAMILY, OpenType.NAME_ID_STYLE, OpenType.NAME_ID_VERSION, OpenType.NAME_ID_FULL)
nameheaders = []
for nameid in eotnames:
if nameid in namerecs:
namerecord = namerecs[nameid]
noffset = namerecord['offset']
nlen = namerecord['length']
nformat = '%dH' % (nlen / 2) # length is in number of bytes
start = nameoffset + namestroffset + noffset
end = start + nlen
nstr = struct.unpack('>' + nformat, fontdata[start:end])
nameheaders.append(struct.pack('<H' + nformat + '2x', nlen, *nstr))
else:
nameheaders.append(struct.pack('4x')) # len = 0, padding = 0
return ''.join(nameheaders)
# just return a null-string (len = 0)
def make_root_string():
return struct.pack('2x')
def make_eot_header(fontdata):
"""given ttf font data produce an EOT header"""
fontDataSize = len(fontdata)
font = get_table_directory(fontdata)
# toss out .otf fonts, t2embed library doesn't support these
tableDir = font['tableDir']
# check for required tables
required = (OpenType.TABLE_HEAD, OpenType.TABLE_NAME, OpenType.TABLE_OS2)
for table in required:
if not (table in tableDir):
raise FontError, 'missing required table ' + multicharval(table)
# read name strings
# pull out data from individual tables to construct fixed header portion
# need to calculate eotSize before packing
version = EOT.EOT_VERSION
flags = 0
charset = EOT.EOT_DEFAULT_CHARSET
magicNumber = EOT.EOT_MAGIC_NUMBER
# read values from OS/2 table
os2Dir = tableDir[OpenType.TABLE_OS2]
os2offset = os2Dir['offset']
os2size = struct.calcsize(OpenType.OS2_UNPACK)
if os2size > os2Dir['length']:
raise FontError, 'OS/2 table invalid length'
os2fields = struct.unpack(OpenType.OS2_UNPACK, fontdata[os2offset : os2offset + os2size])
panose = []
urange = []
codepage = []
weight, fsType = os2fields[:2]
panose[:10] = os2fields[2:12]
urange[:4] = os2fields[12:16]
fsSelection = os2fields[16]
codepage[:2] = os2fields[17:19]
italic = fsSelection & OpenType.OS2_FSSELECTION_ITALIC
# read in values from head table
headDir = tableDir[OpenType.TABLE_HEAD]
headoffset = headDir['offset']
headsize = struct.calcsize(OpenType.HEAD_UNPACK)
if headsize > headDir['length']:
raise FontError, 'head table invalid length'
headfields = struct.unpack(OpenType.HEAD_UNPACK, fontdata[headoffset : headoffset + headsize])
checkSumAdjustment = headfields[0]
# make name headers
nameheaders = make_eot_name_headers(fontdata, tableDir[OpenType.TABLE_NAME])
rootstring = make_root_string()
# calculate the total eot size
eotSize = struct.calcsize(EOT.EOT_HEADER_PACK) + len(nameheaders) + len(rootstring) + fontDataSize
fixed = struct.pack(EOT.EOT_HEADER_PACK,
*([eotSize, fontDataSize, version, flags] + panose + [charset, italic] +
[weight, fsType, magicNumber] + urange + codepage + [checkSumAdjustment]))
return ''.join((fixed, nameheaders, rootstring))
def write_eot_font(eot, header, data):
open(eot,'wb').write(''.join((header, data)))
return
def main():
# deal with options
p = optparse.OptionParser()
p.add_option('--output', '-o', default="world")
options, args = p.parse_args()
# iterate over font files
for f in args:
data = readfont(f)
if len(data) == 0:
print 'Error reading %s' % f
else:
eot = eotname(f)
header = make_eot_header(data)
write_eot_font(eot, header, data)
if __name__ == '__main__':
main()
+214
View File
@@ -0,0 +1,214 @@
# Font generation script from FontCustom
# https://github.com/FontCustom/fontcustom/
# http://fontcustom.com/
import fontforge
import os
import md5
import subprocess
import tempfile
import json
import copy
SCRIPTS_FONT_DIR = os.path.dirname(os.path.abspath(__file__))
INPUT_SVG_DIR = os.path.join(SCRIPTS_FONT_DIR, '..', '..', 'src', 'svg')
OUTPUT_FONT_DIR = os.path.join(SCRIPTS_FONT_DIR, '..', '..', 'dist', 'fonts')
OUTPUT_IONICONS_FONT_DIR = os.path.join(OUTPUT_FONT_DIR, 'ionicons')
MANIFEST_PATH = os.path.join(SCRIPTS_FONT_DIR, '..', 'manifest.json')
BUILD_DATA_PATH = os.path.join(SCRIPTS_FONT_DIR, '..', 'build_data.json')
AUTO_WIDTH = True
KERNING = 15
cp = 0xf100
m = md5.new()
f = fontforge.font()
f.encoding = 'UnicodeFull'
f.design_size = 16
f.em = 512
f.ascent = 448
f.descent = 64
manifest_file = open(MANIFEST_PATH, 'r')
manifest_data = json.loads(manifest_file.read())
manifest_file.close()
print "Load Manifest, Icons: %s" % ( len(manifest_data['icons']) )
try:
os.makedirs(OUTPUT_FONT_DIR)
except OSError as e:
if e.errno != errno.EEXIST:
raise
try:
os.makedirs(OUTPUT_IONICONS_FONT_DIR)
except OSError as e:
if e.errno != errno.EEXIST:
raise
# ensure each icon is actually used in the manifest
clean_manifest_data = copy.deepcopy(manifest_data)
clean_manifest_data['icons'] = []
for ionicon in manifest_data['icons']:
svg_path = os.path.join(INPUT_SVG_DIR, '%s.svg' % (ionicon['name']))
if os.path.isfile(svg_path):
clean_manifest_data['icons'].append({
"code": ionicon['code'],
"name": ionicon['name']
})
else:
print 'removed from manifest: %s' % (ionicon['name'])
manifest_data = copy.deepcopy(clean_manifest_data)
build_data = copy.deepcopy(manifest_data)
build_data['icons'] = []
font_name = manifest_data['name']
m.update(font_name + ';')
m.update(manifest_data['prefix'] + ';')
for dirname, dirnames, filenames in os.walk(INPUT_SVG_DIR):
for filename in filenames:
name, ext = os.path.splitext(filename)
filePath = os.path.join(dirname, filename)
size = os.path.getsize(filePath)
if ext in ['.svg', '.eps']:
# see if this file is already in the manifest
chr_code = None
for ionicon in manifest_data['icons']:
if ionicon['name'] == name:
chr_code = ionicon['code']
break
if chr_code is None:
# this is a new src icon
print 'New Icon: \n - %s' % (name)
while True:
chr_code = '0x%x' % (cp)
already_exists = False
for ionicon in manifest_data['icons']:
if ionicon.get('code') == chr_code:
already_exists = True
cp += 1
chr_code = '0x%x' % (cp)
continue
if not already_exists:
break
print ' - %s' % chr_code
manifest_data['icons'].append({
'name': name,
'code': chr_code
})
build_data['icons'].append({
'name': name,
'code': chr_code
})
if 'ios-' in name and '-outline' not in name:
# check if this ios icon has an outline version
outline_filename = '%s-outline.svg' % (name)
outline_filePath = os.path.join(dirname, outline_filename)
if not os.path.isfile(outline_filePath):
build_data['icons'].append({
'name': '%s-outline' % (name),
'code': chr_code
})
if ext in ['.svg']:
# hack removal of <switch> </switch> tags
svgfile = open(filePath, 'r+')
tmpsvgfile = tempfile.NamedTemporaryFile(suffix=ext, delete=False)
svgtext = svgfile.read()
svgfile.seek(0)
# replace the <switch> </switch> tags with 'nothing'
svgtext = svgtext.replace('<switch>', '')
svgtext = svgtext.replace('</switch>', '')
tmpsvgfile.file.write(svgtext)
svgfile.close()
tmpsvgfile.file.close()
filePath = tmpsvgfile.name
# end hack
m.update(name + str(size) + ';')
glyph = f.createChar( int(chr_code, 16) )
glyph.importOutlines(filePath)
# if we created a temporary file, let's clean it up
if tmpsvgfile:
os.unlink(tmpsvgfile.name)
# set glyph size explicitly or automatically depending on autowidth
if AUTO_WIDTH:
glyph.left_side_bearing = glyph.right_side_bearing = 0
glyph.round()
# resize glyphs if autowidth is enabled
if AUTO_WIDTH:
f.autoWidth(0, 0, 512)
fontfile = '%s/ionicons' % (OUTPUT_FONT_DIR)
build_hash = m.hexdigest()
manifest_data['build_hash'] = build_hash
f.fontname = font_name
f.familyname = font_name
f.fullname = font_name
print 'Generate TTF Font File'
f.generate(fontfile + '.ttf')
print 'Generate SVG Font File'
f.generate(fontfile + '.svg')
# Fix SVG header for webkit
# from: https://github.com/fontello/font-builder/blob/master/bin/fontconvert.py
svgfile = open(fontfile + '.svg', 'r+')
svgtext = svgfile.read()
svgfile.seek(0)
svgfile.write(svgtext.replace('''<svg>''', '''<svg xmlns="http://www.w3.org/2000/svg">'''))
svgfile.close()
scriptPath = os.path.dirname(os.path.realpath(__file__))
try:
subprocess.Popen([scriptPath + '/sfnt2woff', fontfile + '.ttf'], stdout=subprocess.PIPE)
except OSError:
# If the local version of sfnt2woff fails (i.e., on Linux), try to use the
# global version. This allows us to avoid forcing OS X users to compile
# sfnt2woff from source, simplifying install.
subprocess.call(['sfnt2woff', fontfile + '.ttf'])
# eotlitetool.py script to generate IE7-compatible .eot fonts
print 'Generate EOT Font File'
subprocess.call('python ' + scriptPath + '/eotlitetool.py ' + fontfile + '.ttf -o ' + fontfile + '.eot', shell=True)
subprocess.call('mv ' + fontfile + '.eotlite ' + fontfile + '.eot', shell=True)
print 'Hint TTF file'
subprocess.call('ttfautohint -s -f -n ' + fontfile + '.ttf ' + fontfile + '-hinted.ttf > /dev/null 2>&1 && mv ' + fontfile + '-hinted.ttf ' + fontfile + '.ttf', shell=True)
print 'Generate WOFF2 Font File'
subprocess.call('woff2_compress ' + fontfile + '.ttf', shell=True)
manifest_data['icons'] = sorted(manifest_data['icons'], key=lambda k: k['name'])
build_data['icons'] = sorted(build_data['icons'], key=lambda k: k['name'])
print "Save Manifest, Icons: %s" % ( len(manifest_data['icons']) )
f = open(MANIFEST_PATH, 'w')
f.write( json.dumps(manifest_data, indent=2, separators=(',', ': ')) )
f.close()
print "Save Build, Icons: %s" % ( len(build_data['icons']) )
f = open(BUILD_DATA_PATH, 'w')
f.write( json.dumps(build_data, indent=2, separators=(',', ': ')) )
f.close()
BIN
View File
Binary file not shown.
+481
View File
@@ -0,0 +1,481 @@
from subprocess import call
import os, errno
import shutil
import subprocess
import json
import codecs
from collections import OrderedDict
SCRIPTS_PATH = os.path.dirname(os.path.abspath(__file__))
ROOT_PATH = os.path.join(SCRIPTS_PATH, '..')
SRC_PATH = os.path.join(ROOT_PATH, 'src')
DIST_PATH = os.path.join(ROOT_PATH, 'dist')
DOCS_PATH = os.path.join(ROOT_PATH, 'docs')
INPUT_SVG_DIR = os.path.join(SRC_PATH, 'svg')
OUTPUT_SVG_DIR = os.path.join(DIST_PATH, 'svg')
DATA_PATH = os.path.join(DIST_PATH, 'data')
FONTS_FOLDER_PATH = os.path.join(DIST_PATH, 'fonts')
CSS_FOLDER_PATH = os.path.join(DIST_PATH, 'css')
INPUT_SCSS_FOLDER_PATH = os.path.join(SRC_PATH, 'scss')
OUTPUT_SCSS_FOLDER_PATH = os.path.join(DIST_PATH, 'scss')
def main():
try:
os.makedirs(DIST_PATH)
except OSError as e:
if e.errno != errno.EEXIST:
raise
try:
os.makedirs(OUTPUT_SVG_DIR)
except OSError as e:
if e.errno != errno.EEXIST:
raise
generate_font_files()
data = get_build_data()
generate_data_files(data)
rename_svg_glyph_names(data)
generate_scss(data)
generate_svg_files()
generate_cheatsheet(data)
generate_mode_cheatsheet(data)
generate_icon_comparison(data)
def generate_font_files():
print "Generate Fonts"
cmd = "fontforge -script %s/font/generate_font.py" % (SCRIPTS_PATH)
call(cmd, shell=True)
def generate_data_files(data):
try:
os.makedirs(DATA_PATH)
except OSError as e:
if e.errno != errno.EEXIST:
raise
print "Generate Data Files"
icon_names = []
mode_icons = []
logo_icons = []
all_icons = {}
tag_data = get_tag_data()
def get_code_by_name(icon_name):
for ionicon in data['icons']:
if ionicon['name'] == icon_name:
return ionicon['code']
return ''
for ionicon in data['icons']:
name = ""
if ionicon['name'].startswith('ios-'):
name = ionicon['name'][4:]
elif ionicon['name'].startswith('md-'):
name = ionicon['name'][3:]
elif ionicon['name'].startswith('logo-'):
name = ionicon['name'][5:]
if name not in icon_names:
icon_names.append(name)
for icon_name in icon_names:
ios_svg = os.path.join(INPUT_SVG_DIR, 'ios-%s.svg' % (icon_name))
md_svg = os.path.join(INPUT_SVG_DIR, 'md-%s.svg' % (icon_name))
logo_svg = os.path.join(INPUT_SVG_DIR, 'logo-%s.svg' % (icon_name))
if os.path.isfile(ios_svg) and os.path.isfile(md_svg):
mode_icons.append('"%s":1' % icon_name)
all_icons[icon_name] = {
'icons': [
{
'code': get_code_by_name('ios-%s' % (icon_name)),
'name': 'ios-%s' % (icon_name)
},
{
'code': get_code_by_name('ios-%s-outline' % (icon_name)),
'name': 'ios-%s-outline' % (icon_name)
},
{
'code': get_code_by_name('md-%s' % (icon_name)),
'name': 'md-%s' % (icon_name)
}
],
'tags': tag_data.get(icon_name) or icon_name.split('-')
}
elif os.path.isfile(logo_svg):
logo_icons.append('"%s":1' % icon_name)
all_icons[icon_name] = {
'icons': [
{
'code': get_code_by_name('logo-%s' % (icon_name)),
'name': 'logo-%s' % (icon_name) or icon_name.split('-')
}
],
'tags': tag_data.get(icon_name) or icon_name.split('-')
}
elif '-outline' in icon_name:
continue
else:
print 'wtf %s' % icon_name
output = '{\n' + ',\n'.join(mode_icons) + '\n}'
f = codecs.open(os.path.join(DATA_PATH, 'mode-icons.json'), 'w', 'utf-8')
f.write(output)
f.close()
output = '{\n' + ',\n'.join(logo_icons) + '\n}'
f = codecs.open(os.path.join(DATA_PATH, 'logo-icons.json'), 'w', 'utf-8')
f.write(output)
f.close()
all_icons = OrderedDict(sorted(all_icons.items(), key=lambda t: t[0]))
f = codecs.open(os.path.join(DATA_PATH, 'ionicons.json'), 'w', 'utf-8')
f.write( json.dumps(all_icons, indent=2, separators=(',', ': ')) )
f.close()
def generate_svg_files():
print "Generate SVG Files"
shutil.rmtree(OUTPUT_SVG_DIR)
if not os.path.exists(OUTPUT_SVG_DIR):
os.makedirs(OUTPUT_SVG_DIR)
cmd = 'svgo -f %s -o %s' % (INPUT_SVG_DIR, OUTPUT_SVG_DIR)
subprocess.call([cmd], shell=True)
def rename_svg_glyph_names(data):
# hacky and slow (but safe) way to rename glyph-name attributes
svg_path = os.path.join(FONTS_FOLDER_PATH, 'ionicons.svg')
svg_file = codecs.open(svg_path, 'r+', 'utf-8')
svg_text = svg_file.read()
svg_file.seek(0)
for ionicon in data['icons']:
# uniF2CA
org_name = 'uni%s' % (ionicon['code'].replace('0x', '').upper())
ion_name = 'ion-%s' % (ionicon['name'])
svg_text = svg_text.replace(org_name, ion_name)
svg_file.write(svg_text)
svg_file.close()
def generate_scss(data):
try:
os.makedirs(OUTPUT_SCSS_FOLDER_PATH)
except OSError as e:
if e.errno != errno.EEXIST:
raise
print "Generate SCSS"
font_name = data['name']
font_version = data['version']
css_prefix = data['prefix']
ionicons_core_file_path_input = os.path.join(INPUT_SCSS_FOLDER_PATH, 'ionicons-core.scss')
ionicons_core_file_path_output = os.path.join(OUTPUT_SCSS_FOLDER_PATH, 'ionicons-core.scss')
shutil.copyfile(ionicons_core_file_path_input, ionicons_core_file_path_output)
ionicons_scc_file_path_input = os.path.join(INPUT_SCSS_FOLDER_PATH, 'ionicons.scss')
ionicons_scc_file_path_output = os.path.join(OUTPUT_SCSS_FOLDER_PATH, 'ionicons.scss')
shutil.copyfile(ionicons_scc_file_path_input, ionicons_scc_file_path_output)
variables_file_path_input = os.path.join(INPUT_SCSS_FOLDER_PATH, 'ionicons-variables.scss')
variables_file_path = os.path.join(OUTPUT_SCSS_FOLDER_PATH, 'ionicons-variables.scss')
shutil.copyfile(variables_file_path_input, variables_file_path)
common_file_path = os.path.join(OUTPUT_SCSS_FOLDER_PATH, 'ionicons-common.scss')
icons_file_path = os.path.join(OUTPUT_SCSS_FOLDER_PATH, 'ionicons-icons.scss')
d = []
d.append('@charset "UTF-8";')
d.append('// Ionicons Variables')
d.append('// --------------------------\n')
d.append('$ionicons-font-path: "../fonts" !default;')
d.append('$ionicons-font-family: "%s" !default;' % (font_name) )
d.append('$ionicons-version: "%s" !default;' % (font_version) )
f = codecs.open(variables_file_path, 'w', 'utf-8')
f.write( u'\n'.join(d) )
f.close()
d = []
d.append('@charset "UTF-8";')
d.append('// Ionicons Common CSS')
d.append('// --------------------------\n')
group = [ '.%s' % (data['name'].lower()) ]
for ionicon in data['icons']:
group.append('.%s%s:before' % (css_prefix, ionicon['name']) )
d.append( ',\n'.join(group) )
d.append('{')
d.append(' @extend .ion;')
d.append('}')
f = codecs.open(common_file_path, 'w', 'utf-8')
f.write( '\n'.join(d) )
f.close()
d = []
d.append('@charset "UTF-8";')
d.append('// Ionicons Icon Font CSS')
d.append('// --------------------------\n')
for ionicon in data['icons']:
chr_code = ionicon['code'].replace('0x', '\\')
d.append('.%s%s:before { content: "%s"; }' % (css_prefix, ionicon['name'], chr_code) )
f = codecs.open(icons_file_path, 'w', 'utf-8')
f.write( '\n'.join(d) )
f.close()
generate_css_from_scss(data)
def generate_css_from_scss(data):
try:
os.makedirs(CSS_FOLDER_PATH)
except OSError as e:
if e.errno != errno.EEXIST:
raise
compile_scss_to_css('ionicons', data)
compile_scss_to_css('ionicons-core', data)
def compile_scss_to_css(filename, data):
scss_file_path = os.path.join(OUTPUT_SCSS_FOLDER_PATH, '%s.scss' % filename)
css_file_path = os.path.join(CSS_FOLDER_PATH, '%s.css' % filename)
css_min_file_path = os.path.join(CSS_FOLDER_PATH, '%s.min.css' % filename)
print "Generate CSS From %s" % filename
cmd = "sass %s %s --style compact" % (scss_file_path, css_file_path)
call(cmd, shell=True)
cmd = "sass %s %s --style compressed" % (scss_file_path, css_min_file_path)
call(cmd, shell=True)
def generate_cheatsheet(data):
print "Generate Cheatsheet"
cheatsheet_file_path = os.path.join(DOCS_PATH, 'cheatsheet.html')
template_path = os.path.join(SRC_PATH, 'cheatsheet', 'template.html')
icon_row_path = os.path.join(SRC_PATH, 'cheatsheet', 'icon-row.html')
f = codecs.open(template_path, 'r', 'utf-8')
template_html = f.read()
f.close()
f = codecs.open(icon_row_path, 'r', 'utf-8')
icon_row_template = f.read()
f.close()
content = []
for ionicon in data['icons']:
css_code = ionicon['code'].replace('0x', '\\')
escaped_html_code = ionicon['code'].replace('0x', '&amp;#x') + ';'
html_code = ionicon['code'].replace('0x', '&#x') + ';'
item_row = icon_row_template
item_row = item_row.replace('{{name}}', ionicon['name'])
item_row = item_row.replace('{{prefix}}', data['prefix'])
item_row = item_row.replace('{{css_code}}', css_code)
item_row = item_row.replace('{{escaped_html_code}}', escaped_html_code)
item_row = item_row.replace('{{html_code}}', html_code)
content.append(item_row)
template_html = template_html.replace("{{title}}", 'Cheatsheet')
template_html = template_html.replace("{{font_name}}", data["name"])
template_html = template_html.replace("{{font_version}}", data["version"])
template_html = template_html.replace("{{icon_count}}", str(len(data["icons"])) )
template_html = template_html.replace("{{content}}", '\n'.join(content) )
f = codecs.open(cheatsheet_file_path, 'w', 'utf-8')
f.write(template_html)
f.close()
def generate_mode_cheatsheet(data):
print "Generate Mode Cheatsheet"
cheatsheet_file_path = os.path.join(DOCS_PATH, 'mode-cheatsheet.html')
template_path = os.path.join(SRC_PATH, 'cheatsheet', 'template.html')
icon_row_path = os.path.join(SRC_PATH, 'cheatsheet', 'mode-icon-row.html')
f = codecs.open(template_path, 'r', 'utf-8')
template_html = f.read()
f.close()
f = codecs.open(icon_row_path, 'r', 'utf-8')
icon_row_template = f.read()
f.close()
content = []
icon_names = []
content.append('''
<div class="mode-row">
<div class="mode-col">
<strong>Icon Name</strong>
</div>
<div class="mode-col align-center">
<strong>iOS</strong>
</div>
<div class="mode-col align-center">
<strong>Material Design</strong>
</div>
</div>
''')
for ionicon in data['icons']:
name = ""
if ionicon['name'].startswith('ios-'):
name = ionicon['name'][4:]
elif ionicon['name'].startswith('md-'):
name = ionicon['name'][3:]
if name not in icon_names and not name.endswith('-outline'):
icon_names.append(name)
for icon_name in icon_names:
item_row = icon_row_template.replace('{{name}}', icon_name)
item_row = item_row.replace('{{prefix}}', data['prefix'])
content.append(item_row)
template_html = template_html.replace("{{title}}", 'Mode Cheatsheet')
template_html = template_html.replace("{{font_name}}", data["name"])
template_html = template_html.replace("{{font_version}}", data["version"])
template_html = template_html.replace("{{icon_count}}", str(len(icon_names)) )
template_html = template_html.replace("{{content}}", '\n'.join(content) )
f = codecs.open(cheatsheet_file_path, 'w', 'utf-8')
f.write(template_html)
f.close()
def generate_icon_comparison(data):
print "Generate Icon Comparison"
comparison_file_path = os.path.join(DOCS_PATH, 'icon-comparison.html')
template_path = os.path.join(SRC_PATH, 'cheatsheet', 'template.html')
icon_row_path = os.path.join(SRC_PATH, 'cheatsheet', 'icon-comparison-row.html')
f = codecs.open(template_path, 'r', 'utf-8')
template_html = f.read()
f.close()
f = codecs.open(icon_row_path, 'r', 'utf-8')
icon_row_template = f.read()
f.close()
content = []
icon_count = 0
content.append('''
<table class="comparison-table">
<tr class="comparison-row">
<td class="comparison-col">
<h2>Source SVG</h2>
</td>
<td class="comparison-col">
<h2>Optimized SVG</h2>
</td>
<td class="comparison-col">
<h2>Custom Element</h2>
</td>
<td class="comparison-col">
<h2>Icon Font</h2>
</td>
<td class="comparison-col">
<h2>PNG, 64x64</h2>
</td>
</tr>
''')
for ionicon in data['icons']:
src_svg_file = os.path.join(INPUT_SVG_DIR, '%s.svg' % (ionicon['name']))
if not os.path.isfile(src_svg_file):
continue
icon_count += 1
item_row = icon_row_template.replace('{{name}}', ionicon['name'])
item_row = item_row.replace('{{prefix}}', data['prefix'])
src_svg = 'build/svg/%s.svg' % (ionicon['name'])
item_row = item_row.replace('{{src_svg}}', src_svg)
optimized_svg = 'build/svg/%s.svg' % (ionicon['name'])
item_row = item_row.replace('{{optimized_svg}}', optimized_svg)
png_64 = 'build/png/64/%s.png' % (ionicon['name'])
item_row = item_row.replace('{{png_64}}', png_64)
content.append(item_row)
content.append('</table>')
template_html = template_html.replace("{{title}}", 'Icon Format Comparison')
template_html = template_html.replace("{{font_name}}", data["name"])
template_html = template_html.replace("{{font_version}}", data["version"])
template_html = template_html.replace("{{icon_count}}", str(icon_count) )
template_html = template_html.replace("{{content}}", '\n'.join(content) )
f = codecs.open(comparison_file_path, 'w', 'utf-8')
f.write(template_html)
f.close()
def get_build_data():
build_data_path = os.path.join(SCRIPTS_PATH, 'build_data.json')
f = codecs.open(build_data_path, 'r', 'utf-8')
data = json.loads(f.read())
f.close()
package_json_path = os.path.join(ROOT_PATH, 'package.json')
f = codecs.open(package_json_path, 'r', 'utf-8')
package_data = json.loads(f.read())
f.close()
data['version'] = package_data['version']
return data
def get_tag_data():
tag_data_path = os.path.join(SCRIPTS_PATH, 'tags.json')
f = codecs.open(tag_data_path, 'r', 'utf-8')
data = json.loads(f.read())
f.close()
return data
if __name__ == "__main__":
main()
File diff suppressed because it is too large Load Diff
-87
View File
@@ -1,87 +0,0 @@
import { PluginConfig } from 'svgo';
const setRootIoniconClass: PluginConfig = {
name: 'addClassesToSVGElement',
params: {
className: 'ionicon',
},
};
const addFillNoneCss: PluginConfig = {
name: 'addFillNoneCss',
fn: () => ({
element: {
enter: (element) => {
if (element.attributes.fill) {
if (element.attributes.fill === 'none') {
element.attributes.class = [...(element.attributes.class?.split(' ') || []), 'ionicon-fill-none'].join(' ');
}
delete element.attributes.fill;
}
if (element.attributes.stroke) {
delete element.attributes.stroke;
}
if (
element.attributes['stroke-width'] &&
(element.attributes['stroke-width'] === '32px' || element.attributes['stroke-width'] === '32')
) {
delete element.attributes['stroke-width'];
element.attributes.class = [...(element.attributes.class?.split(' ') || []), 'ionicon-stroke-width'].join(
' ',
);
}
},
},
}),
};
const forceCurrentColor: PluginConfig = {
name: 'forceCurrentColor',
fn: () => ({
element: {
enter: (element) => {
const attr = element.attributes.stroke || element.attributes.fill;
const attrName = element.attributes.stroke ? 'stroke' : element.attributes.fill ? 'fill' : undefined;
if (attrName) {
if (attr === '#000' || attr === 'currentColor') {
element.attributes[attrName] = 'currentColor';
} else if (attr !== 'none') {
throw new Error(`invalid "${attrName}" value: ${element.attributes[attrName]}`);
}
}
},
},
}),
};
const validatePlugin: PluginConfig = {
name: 'validate',
fn: () => ({
element: {
enter: (element) => {
if (element.attributes.style) {
console.warn(
`Inline style attributed detected: <${element.name} style="${element.attributes.style}">...</${element.name}>`,
);
}
if (element.name === 'style') {
console.warn('Inline style element detected');
}
},
},
}),
};
const basePlugins: PluginConfig[] = [
'removeStyleElement',
'convertStyleToAttrs',
'removeScripts',
'removeDimensions',
setRootIoniconClass,
validatePlugin,
];
export const webComponentPassPlugins: PluginConfig[] = [...basePlugins, addFillNoneCss];
export const sourcePassPlugins: PluginConfig[] = [...basePlugins, forceCurrentColor];
+62
View File
@@ -0,0 +1,62 @@
const fs = require('fs-extra');
const path = require('path');
const svg2png = require('svg2png');
const crypto = require('crypto');
const ROOT_DIR = path.join(__dirname, '..');
const SRC_DIR = path.join(ROOT_DIR, 'src');
const TMP_DIR = path.join(ROOT_DIR, 'tmp');
const DIST_DIR = path.join(ROOT_DIR, 'dist');
const SVG_SRC_DIR = path.join(SRC_DIR, 'svg');
const PNG_DIST_DIR = path.join(DIST_DIR, 'png');
const SIZES = [64];
fs.ensureDirSync(DIST_DIR);
fs.ensureDirSync(TMP_DIR);
fs.emptyDirSync(PNG_DIST_DIR);
SIZES.forEach(size => {
const pngDir = path.join(PNG_DIST_DIR, size.toString());
fs.emptyDirSync(pngDir);
});
var svgFileNames = fs.readdirSync(SVG_SRC_DIR).filter(f => {
return f.split('.').pop() === 'svg';
});
svgFileNames.forEach(svgFileName => {
const svgFilePath = path.join(SVG_SRC_DIR, svgFileName);
const pngFileName = svgFileName.replace('.svg', '.png');
const sourceBuffer = fs.readFileSync(svgFilePath);
const hash = crypto.createHash('sha1')
.update(sourceBuffer.toString())
.digest('base64')
.replace(/\W/g, '');
SIZES.forEach(size => {
generatePng(pngFileName, sourceBuffer, hash, size);
});
});
function generatePng(pngFileName, sourceBuffer, hash, size) {
const cachedFilePath = path.join(TMP_DIR, hash + '.' + size + '.png');
const pngFilePath = path.join(PNG_DIST_DIR, size.toString(), pngFileName);
try {
const cachedFileContent = fs.readFileSync(cachedFilePath);
fs.writeFileSync(pngFilePath, cachedFileContent);
console.log('png from cache', size, pngFileName);
} catch (e) {
const outputBuffer = svg2png.sync(sourceBuffer, { width: size, height: size });
fs.writeFileSync(pngFilePath, outputBuffer);
fs.writeFileSync(cachedFilePath, outputBuffer);
console.log('converted to png', size, pngFileName);
}
}
+14 -25
View File
@@ -1,38 +1,27 @@
# Development and Build Scripts
## Build Instructions
## Updating Icons
This repo already comes with all the files built and ready to go, but can also build the fonts from the source. Requires Python, FontForge, WOFF2, SVGO and Sass:
The `src/svg` directory is the single source of truth for svgs. They should not already be optimized and can be the original svg export straight out of an svg editor. A build step before releasing will optimize the source svgs (remove comments, reduce the size, etc) and ensure they'll work within `ion-icon`.
1) Install FontForge, which is the program that creates the font files from the SVG files:
## Build Locally
$ brew install fontforge ttfautohint
After an svg has been updated, added or deleted from the `src/svg` directory, run:
2) Install Google's WOFF2 font compressor
```sh
npm run build
```
https://github.com/google/woff2
The build command will optimize all of the icons and generate the files to be distributed. After the build command, all of the optimized svgs are saved in `dist/ionicons/svg`. Additionally the `dist` directory contains the distribution files for the `ion-icon` web component.
3) Install [Sass](http://sass-lang.com/)
## Svg Symbols Cheatsheet
$ gem install sass
After a build, a new `www/cheatsheet.html` file will be created. This version uses svg symbols rather than `ion-icon`.
4) Install [SVGO](https://github.com/svg/svgo)
## ion-icon Component Preview
$ npm install -g svgo
To see the `ion-icon` component in action, run:
5) Add or subtract files from the `src/` folder you'd like to be apart of the build.
```sh
npm start
```
6) Modify any settings in the `builder/manifest.json` file. You can change the name of the font-family and CSS classname prefix.
## Release Steps
7) Run the build command:
Releases are automated via GitHub Actions. To trigger a release:
1. Go to the [Release Orchestrator](https://github.com/ionic-team/ionicons/actions/workflows/release-orchestrator.yml) workflow
2. Click "Run workflow"
3. Select the release type:
- **dev** — Creates a pre-release with a timestamp-based version (e.g., `8.0.14-dev.11784821417.1c794397`)
- **production** — Creates a semver release; select `patch`, `minor`, or `major`
4. The workflow will build, publish to NPM, and create a GitHub release (for production releases)
python ./builder/generate.py
+26
View File
@@ -0,0 +1,26 @@
console.log('Build JPML files');
var jpml = require('@ionic/jpml');
var fs = require('fs-extra');
var path = require('path');
const OUT_DIR = path.join(__dirname, '..', 'dist', 'ionicons', 'svg');
fs.emptyDirSync(OUT_DIR);
jpml.generate({
include: ['dist/svg/'],
outDir: OUT_DIR,
filter: function(path) {
return path.toLowerCase().split('.').pop() === 'svg';
},
fileName: function(path) {
return path.replace('.svg', '.js');
},
key: function(path) {
return path.replace('.svg', '');
},
wrapper: function(content, key) {
return "loadIonicon('" + content.replace(/'/g, "\\\'") + "','" + key + "');"
}
});
+1652
View File
File diff suppressed because it is too large Load Diff
-53
View File
@@ -1,53 +0,0 @@
import { PluginConfig } from 'svgo';
export interface SvgData {
/**
* airplane-outline.svg
*/
fileName: string;
/**
* airplane
*/
title: string;
/**
* /src/svg/airplane-outline.svg
*/
srcFilePath: string;
/**
* /dist/ionicons/svg/airplane-outline.svg
*/
optimizedFilePath: string;
/**
* /dist/svg/airplane-outline.svg
*/
distSvgFilePath: string;
/**
* optimized svg content
*/
optimizedSvgContent?: string;
/**
* airplane-outline
*/
iconName: string;
/**
* airplane-outline.mjs
*/
fileNameMjs: string;
/**
* airplane-outline.js
*/
fileNameCjs: string;
/**
* airplaneOutline
*/
exportName: string;
}
+42
View File
@@ -0,0 +1,42 @@
<tr class="comparison-row">
<td class="comparison-col">
<div class="comparison-icon">
<img src="{{src_svg}}">
</div>
<div>
Source SVG: {{name}}
</div>
</td>
<td class="comparison-col">
<div class="comparison-icon">
<img src="{{optimized_svg}}">
</div>
<div>
Optimized SVG: {{name}}
</div>
</td>
<td class="comparison-col">
<div class="comparison-icon">
<ion-icon name="{{name}}"></ion-icon>
</div>
<div>
Custom Element: &lt;ion-icon name="{{name}}"&gt;
</div>
</td>
<td class="comparison-col">
<div class="comparison-icon">
<i class="icon {{prefix}}{{name}}"></i>
</div>
<div>
Icon Font: {{prefix}}{{name}}
</div>
</td>
<td class="comparison-col">
<div class="comparison-icon">
<img src="{{png_64}}">
</div>
<div>
PNG, 64x64: {{name}}
</div>
</td>
</tr>
+38
View File
@@ -0,0 +1,38 @@
<div class="icon-row">
<div class="preview-icon"><span class="step size-12">
<i class="icon {{prefix}}{{name}}"></i>
</span><span class="step size-14">
<i class="icon {{prefix}}{{name}}"></i>
</span><span class="step size-16">
<i class="icon {{prefix}}{{name}}"></i>
</span><span class="step size-18">
<i class="icon {{prefix}}{{name}}"></i>
</span><span class="step size-21">
<i class="icon {{prefix}}{{name}}"></i>
</span><span class="step size-24">
<i class="icon {{prefix}}{{name}}"></i>
</span><span class="step size-32">
<i class="icon {{prefix}}{{name}}"></i>
</span><span class="step size-48">
<i class="icon {{prefix}}{{name}}"></i>
</span><span class="step size-64">
<i class="icon {{prefix}}{{name}}"></i>
</span><span class="step size-96">
<i class="icon {{prefix}}{{name}}"></i>
</span>
</div>
<div class="preview-scale"><span class="step">12</span><span class="step">14</span><span class="step">16</span><span class="step">18</span><span class="step">21</span><span class="step">24</span><span class="step">32</span><span class="step">48</span><span class="step">64</span><span class="step">96</span></div>
<div class="usage">
<label>Classname:</label>
<input class="name" type="text" readonly="readonly" onClick="this.select();" value="{{prefix}}{{name}}" />
<label>Selectable:</label>
<span class="ion">{{html_code}}</span>
<label>Escaped HTML:</label>
<input class="html" type="text" readonly="readonly" onClick="this.select();" value="{{escaped_html_code}}" />
<label>CSS Content:</label>
<input class="css" type="text" readonly="readonly" onClick="this.select();" value="{{css_code}}" />
</div>
</div>
+11
View File
@@ -0,0 +1,11 @@
<div class="mode-row">
<div class="mode-col">
{{name}}
</div>
<div class="mode-col align-center">
<i class="icon {{prefix}}ios-{{name}}"></i>
</div>
<div class="mode-col align-center">
<i class="icon {{prefix}}md-{{name}}"></i>
</div>
</div>
+204
View File
@@ -0,0 +1,204 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{font_name}} {{title}}</title>
<style>
* {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
margin: 0;
padding: 0;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
body {
background: #fff;
color: #444;
font: 16px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif;
}
a, a:visited {
color: #888;
text-decoration: underline;
}
a:hover, a:focus { color: #000; }
header {
border-bottom: 2px solid #ddd;
margin-bottom: 20px;
overflow: hidden;
padding: 20px 0;
}
header h1 {
color: #888;
float: left;
font-size: 36px;
font-weight: 300;
}
header a {
float: right;
font-size: 14px;
}
.container {
margin: 0 auto;
max-width: 1200px;
min-width: 960px;
padding: 0 20px;
width: 95%;
}
.icon-row {
border-bottom: 1px dotted #ccc;
padding: 10px 0 20px;
margin-bottom: 20px;
}
.ion {
-webkit-touch-callout: text;
-webkit-user-select: text;
-khtml-user-select: text;
-moz-user-select: text;
-ms-user-select: text;
user-select: text;
}
.preview-icon { vertical-align: bottom; }
.preview-scale {
color: #888;
font-size: 12px;
margin-top: 5px;
}
.step {
display: inline-block;
line-height: 1;
position: relative;
width: 10%;
}
.step i {
-webkit-transition: opacity .3s;
-moz-transition: opacity .3s;
-ms-transition: opacity .3s;
-o-transition: opacity .3s;
transition: opacity .3s;
}
.step:hover i { opacity: .3; }
.size-12 { font-size: 12px; }
.size-14 { font-size: 14px; }
.size-16 { font-size: 16px; }
.size-18 { font-size: 18px; }
.size-21 { font-size: 21px; }
.size-24 { font-size: 24px; }
.size-32 { font-size: 32px; }
.size-48 { font-size: 48px; }
.size-64 { font-size: 64px; }
.size-96 { font-size: 96px; }
.usage { margin-top: 10px; }
.usage input {
font-family: monospace;
margin-right: 3px;
padding: 2px 5px;
text-align: center;
-webkit-touch-callout: text;
-webkit-user-select: text;
-khtml-user-select: text;
-moz-user-select: text;
-ms-user-select: text;
user-select: text;
}
.usage label {
font-size: 12px;
text-align: right;
padding: 0 3px 0 60px;
}
.usage label:first-child { padding-left: 0; }
.usage .name { width: 180px; }
.usage .html { width: 80px; }
.usage .css { width: 80px; }
.mode-row {
border-bottom: 1px dotted #ccc;
padding: 0 0 10px;
margin-bottom: 10px;
}
.mode-col {
display: inline-block;
width: 25%;
}
.mode-row .icon {
font-size: 32px;
}
.align-center {
text-align: center;
}
.comparison-row {
display: flex;
border-bottom: 1px solid #ddd;
margin-bottom: 10px;
}
.comparison-col {
flex: 1;
text-align: center;
font-size: 12px;
}
.comparison-icon {
height: 136px;
}
.comparison-col img {
width: 100%;
max-width: 128px;
}
.comparison-col .icon {
font-size: 128px;
line-height: 0;
color: black;
}
footer {
color: #888;
font-size: 12px;
padding: 20px 0;
}
</style>
<link href="build/css/ionicons.css" rel="stylesheet" type="text/css">
<script src="build/ionicons.js"></script>
</head>
<body>
<div class="container">
<header>
<h1>{{font_name}} {{title}}, {{icon_count}} icons:</h1>
<p><a href="http://ionicons.com/">Ionicons Homepage</a></p>
</header>
<div class="content">
{{content}}
</div>
<footer>
Made with love by the <a href="http://ionicframework.com/">Ionic Framework</a>
</footer>
</div>
</body>
</html>
-146
View File
@@ -1,146 +0,0 @@
/* eslint-disable */
/* tslint:disable */
/**
* This is an autogenerated file created by the Stencil compiler.
* It contains typing information for all components that exist in this project.
*/
import { HTMLStencilElement, JSXBase } from "@stencil/core/internal";
export namespace Components {
interface IonIcon {
/**
* The color to use for the background of the item.
*/
"color"?: string;
/**
* Specifies whether the icon should horizontally flip when `dir` is `"rtl"`.
*/
"flipRtl"?: boolean;
/**
* A combination of both `name` and `src`. If a `src` url is detected it will set the `src` property. Otherwise it assumes it's a built-in named SVG and set the `name` property.
*/
"icon"?: any;
/**
* Specifies which icon to use on `ios` mode.
*/
"ios"?: string;
/**
* If enabled, ion-icon will be loaded lazily when it's visible in the viewport. Default, `false`.
* @default false
*/
"lazy": boolean;
/**
* Specifies which icon to use on `md` mode.
*/
"md"?: string;
/**
* The mode determines which platform styles to use.
* @default getIonMode()
*/
"mode": string;
/**
* Specifies which icon to use from the built-in set of icons.
*/
"name"?: string;
/**
* When `true`, SVG content, including SVG `data:` URLs, is checked before it renders. SVGs with `<script>` elements, attributes that start with `on` (like `onclick`), `javascript:` URLs, or non-SVG elements aren't rendered, and `<foreignObject>` elements are removed. Only set this to `false` for SVG content from a trusted source.
* @default true
*/
"sanitize": boolean;
/**
* The size of the icon. Available options are: `"small"` and `"large"`.
*/
"size"?: string;
/**
* Specifies the exact `src` of an SVG file to use.
*/
"src"?: string;
}
}
declare global {
interface HTMLIonIconElement extends Components.IonIcon, HTMLStencilElement {
}
var HTMLIonIconElement: {
prototype: HTMLIonIconElement;
new (): HTMLIonIconElement;
};
interface HTMLElementTagNameMap {
"ion-icon": HTMLIonIconElement;
}
}
declare namespace LocalJSX {
interface IonIcon {
/**
* The color to use for the background of the item.
*/
"color"?: string;
/**
* Specifies whether the icon should horizontally flip when `dir` is `"rtl"`.
*/
"flipRtl"?: boolean;
/**
* A combination of both `name` and `src`. If a `src` url is detected it will set the `src` property. Otherwise it assumes it's a built-in named SVG and set the `name` property.
*/
"icon"?: any;
/**
* Specifies which icon to use on `ios` mode.
*/
"ios"?: string;
/**
* If enabled, ion-icon will be loaded lazily when it's visible in the viewport. Default, `false`.
* @default false
*/
"lazy"?: boolean;
/**
* Specifies which icon to use on `md` mode.
*/
"md"?: string;
/**
* The mode determines which platform styles to use.
* @default getIonMode()
*/
"mode"?: string;
/**
* Specifies which icon to use from the built-in set of icons.
*/
"name"?: string;
/**
* When `true`, SVG content, including SVG `data:` URLs, is checked before it renders. SVGs with `<script>` elements, attributes that start with `on` (like `onclick`), `javascript:` URLs, or non-SVG elements aren't rendered, and `<foreignObject>` elements are removed. Only set this to `false` for SVG content from a trusted source.
* @default true
*/
"sanitize"?: boolean;
/**
* The size of the icon. Available options are: `"small"` and `"large"`.
*/
"size"?: string;
/**
* Specifies the exact `src` of an SVG file to use.
*/
"src"?: string;
}
interface IonIconAttributes {
"mode": string;
"color": string;
"ios": string;
"md": string;
"flipRtl": boolean;
"name": string;
"src": string;
"icon": string;
"size": string;
"lazy": boolean;
"sanitize": boolean;
}
interface IntrinsicElements {
"ion-icon": Omit<IonIcon, keyof IonIconAttributes> & { [K in keyof IonIcon & keyof IonIconAttributes]?: IonIcon[K] } & { [K in keyof IonIcon & keyof IonIconAttributes as `attr:${K}`]?: IonIconAttributes[K] } & { [K in keyof IonIcon & keyof IonIconAttributes as `prop:${K}`]?: IonIcon[K] };
}
}
export { LocalJSX as JSX };
declare module "@stencil/core" {
export namespace JSX {
interface IntrinsicElements {
"ion-icon": LocalJSX.IntrinsicElements["ion-icon"] & JSXBase.HTMLAttributes<HTMLIonIconElement>;
}
}
}
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M0 0h24v24H0z" fill="none"/><path d="M20 8h-2.81c-.45-.78-1.07-1.45-1.82-1.96L17 4.41 15.59 3l-2.17 2.17C12.96 5.06 12.49 5 12 5c-.49 0-.96.06-1.41.17L8.41 3 7 4.41l1.62 1.63C7.88 6.55 7.26 7.22 6.81 8H4v2h2.09c-.05.33-.09.66-.09 1v1H4v2h2v1c0 .34.04.67.09 1H4v2h2.81c1.04 1.79 2.97 3 5.19 3s4.15-1.21 5.19-3H20v-2h-2.09c.05-.33.09-.66.09-1v-1h2v-2h-2v-1c0-.34-.04-.67-.09-1H20V8zm-6 8h-4v-2h4v2zm0-4h-4v-2h4v2z"/></svg>

Before

Width:  |  Height:  |  Size: 512 B

-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0V0z"/><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/></svg>

Before

Width:  |  Height:  |  Size: 227 B

-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M12 4H5C3.34 4 2 5.34 2 7v8c0 1.66 1.34 3 3 3l-1 1v1h1l2-2.03L9 18v-5H4V5.98L13 6v2h2V7c0-1.66-1.34-3-3-3zM5 14c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm15.57-4.34c-.14-.4-.52-.66-.97-.66h-7.19c-.46 0-.83.26-.98.66L10 13.77l.01 5.51c0 .38.31.72.69.72h.62c.38 0 .68-.38.68-.76V18h8v1.24c0 .38.31.76.69.76h.61c.38 0 .69-.34.69-.72l.01-1.37v-4.14l-1.43-4.11zm-8.16.34h7.19l1.03 3h-9.25l1.03-3zM12 16c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm8 0c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z"/><path fill="none" d="M0 0h24v24H0z"/></svg>

Before

Width:  |  Height:  |  Size: 641 B

-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24"><defs><path id="a" d="M24 0v24H0V0h24z"/></defs><clipPath id="b"><use xlink:href="#a" overflow="visible"/></clipPath><path d="M10.08 10.86c.05-.33.16-.62.3-.87s.34-.46.59-.62c.24-.15.54-.22.91-.23.23.01.44.05.63.13.2.09.38.21.52.36s.25.33.34.53.13.42.14.64h1.79c-.02-.47-.11-.9-.28-1.29s-.4-.73-.7-1.01-.66-.5-1.08-.66-.88-.23-1.39-.23c-.65 0-1.22.11-1.7.34s-.88.53-1.2.92-.56.84-.71 1.36S8 11.29 8 11.87v.27c0 .58.08 1.12.23 1.64s.39.97.71 1.35.72.69 1.2.91 1.05.34 1.7.34c.47 0 .91-.08 1.32-.23s.77-.36 1.08-.63.56-.58.74-.94.29-.74.3-1.15h-1.79c-.01.21-.06.4-.15.58s-.21.33-.36.46-.32.23-.52.3c-.19.07-.39.09-.6.1-.36-.01-.66-.08-.89-.23-.25-.16-.45-.37-.59-.62s-.25-.55-.3-.88-.08-.67-.08-1v-.27c0-.35.03-.68.08-1.01zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z" clip-path="url(#b)"/></svg>

Before

Width:  |  Height:  |  Size: 1000 B

-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M0 0h24v24H0z" fill="none"/><path d="M18 7l-1.41-1.41-6.34 6.34 1.41 1.41L18 7zm4.24-1.41L11.66 16.17 7.48 12l-1.41 1.41L11.66 19l12-12-1.42-1.41zM.41 13.41L6 19l1.41-1.41L1.83 12 .41 13.41z"/></svg>

Before

Width:  |  Height:  |  Size: 292 B

-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M0 0h24v24H0z" fill="none"/><path d="M12 17c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm6-9h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6h1.9c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm0 12H6V10h12v10z"/></svg>

Before

Width:  |  Height:  |  Size: 369 B

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><script>alert('got ya')</script><path d="M0 0h24v24H0z" fill="none"/><path d="M20 8h-2.81c-.45-.78-1.07-1.45-1.82-1.96L17 4.41 15.59 3l-2.17 2.17C12.96 5.06 12.49 5 12 5c-.49 0-.96.06-1.41.17L8.41 3 7 4.41l1.62 1.63C7.88 6.55 7.26 7.22 6.81 8H4v2h2.09c-.05.33-.09.66-.09 1v1H4v2h2v1c0 .34.04.67.09 1H4v2h2.81c1.04 1.79 2.97 3 5.19 3s4.15-1.21 5.19-3H20v-2h-2.09c.05-.33.09-.66.09-1v-1h2v-2h-2v-1c0-.34-.04-.67-.09-1H20V8zm-6 8h-4v-2h4v2zm0-4h-4v-2h4v2z"/></svg>

Before

Width:  |  Height:  |  Size: 544 B

-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><script>alert('got ya')</script><path d="M0 0h24v24H0z" fill="none"/><path d="M20 8h-2.81c-.45-.78-1.07-1.45-1.82-1.96L17 4.41 15.59 3l-2.17 2.17C12.96 5.06 12.49 5 12 5c-.49 0-.96.06-1.41.17L8.41 3 7 4.41l1.62 1.63C7.88 6.55 7.26 7.22 6.81 8H4v2h2.09c-.05.33-.09.66-.09 1v1H4v2h2v1c0 .34.04.67.09 1H4v2h2.81c1.04 1.79 2.97 3 5.19 3s4.15-1.21 5.19-3H20v-2h-2.09c.05-.33.09-.66.09-1v-1h2v-2h-2v-1c0-.34-.04-.67-.09-1H20V8zm-6 8h-4v-2h4v2zm0-4h-4v-2h4v2z"/></svg>

Before

Width:  |  Height:  |  Size: 544 B

-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M15 4c-4.42 0-8 3.58-8 8s3.58 8 8 8 8-3.58 8-8-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6z"/><path fill="none" d="M0 0h24v24H0V0z"/><path d="M3 12c0-2.61 1.67-4.83 4-5.65V4.26C3.55 5.15 1 8.27 1 12s2.55 6.85 6 7.74v-2.09c-2.33-.82-4-3.04-4-5.65z"/></svg>

Before

Width:  |  Height:  |  Size: 372 B

-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M19 4H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.89-2-2-2zm0 14H5V8h14v10z"/><path fill="none" d="M0 0h24v24H0z"/></svg>

Before

Width:  |  Height:  |  Size: 233 B

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill-rule="evenodd" clip-rule="evenodd" d="M14 6V4h-4v2h4zM4 8v11h16V8H4zm16-2c1.11 0 2 .89 2 2v11c0 1.11-.89 2-2 2H4c-1.11 0-2-.89-2-2l.01-11c0-1.11.88-2 1.99-2h4V4c0-1.11.89-2 2-2h4c1.11 0 2 .89 2 2v2h4z"/><path fill="none" d="M0 0h24v24H0z"/></svg>

Before

Width:  |  Height:  |  Size: 340 B

-161
View File
@@ -1,161 +0,0 @@
:host {
display: inline-block;
width: 1em;
height: 1em;
font-size: 1em;
contain: layout style;
fill: currentColor;
box-sizing: content-box !important;
}
:host .ionicon {
stroke: currentColor;
}
.ionicon-fill-none {
fill: none;
}
.ionicon-stroke-width {
stroke-width: var(--ionicon-stroke-width, 32px);
}
.icon-inner {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
}
.ionicon,
svg {
display: block;
height: 100%;
width: 100%;
}
/* Slotted Content
* -----------------------------------------------------------
*/
::slotted(*) {
font-size: inherit !important;
}
/* Icon RTL
* -----------------------------------------------------------
*/
/**
* Safari <16.4 incorrectly reports
* that it supports :dir(rtl) when it does not.
* This @supports statement lets us target
* WebKit browsers to apply the RTL fallback.
* -webkit-named-image only exists on WebKit.
* For WebKit browsers that do support :dir(rtl)
* (i.e. Safari >= 16.4) then the :dir(rtl)
* code farther down on the page will take
* effect and override this fallback.
*/
@supports (background: -webkit-named-image(i)) {
:host(.icon-rtl) .icon-inner {
transform: scaleX(-1);
}
}
/**
* Fallback for browsers that support
* neither :host-context nor :dir.
* The icon will not react to dir
* changes, but it will at least
* respect the dir on component load.
*/
@supports not selector(:dir(rtl)) and selector(:host-context([dir='rtl'])) {
:host(.icon-rtl) .icon-inner {
transform: scaleX(-1);
}
}
/* :host-context is supported in chromium; :dir is supported in safari & firefox */
:host(.flip-rtl):host-context([dir='rtl']) .icon-inner {
transform: scaleX(-1);
}
@supports selector(:dir(rtl)) {
:host(.flip-rtl:dir(rtl)) .icon-inner {
transform: scaleX(-1);
}
/**
* This is needed for WebKit otherwise the fallback
* will always cause the icon to be flipped if the document
* loads in RTL.
*/
:host(.flip-rtl:dir(ltr)) .icon-inner {
transform: scaleX(1);
}
}
/* Icon Sizes
* -----------------------------------------------------------
*/
:host(.icon-small) {
font-size: 1.125rem !important;
}
:host(.icon-large) {
font-size: 2rem !important;
}
/* Icon Colors
* -----------------------------------------------------------
*/
:host(.ion-color) {
color: var(--ion-color-base) !important;
}
:host(.ion-color-primary) {
--ion-color-base: var(--ion-color-primary, #3880ff);
}
:host(.ion-color-secondary) {
--ion-color-base: var(--ion-color-secondary, #0cd1e8);
}
:host(.ion-color-tertiary) {
--ion-color-base: var(--ion-color-tertiary, #f4a942);
}
:host(.ion-color-success) {
--ion-color-base: var(--ion-color-success, #10dc60);
}
:host(.ion-color-warning) {
--ion-color-base: var(--ion-color-warning, #ffce00);
}
:host(.ion-color-danger) {
--ion-color-base: var(--ion-color-danger, #f14141);
}
:host(.ion-color-light) {
--ion-color-base: var(--ion-color-light, #f4f5f8);
}
:host(.ion-color-medium) {
--ion-color-base: var(--ion-color-medium, #989aa2);
}
:host(.ion-color-dark) {
--ion-color-base: var(--ion-color-dark, #222428);
}
+177 -220
View File
@@ -1,255 +1,212 @@
import { Build, Component, Element, Host, Prop, State, Watch, h } from '@stencil/core';
import { getCacheKey, getSvgContent, ioniconContent } from './request';
import { getName, getUrl, inheritAttributes, isRTL } from './utils';
import { Component, Prop, State } from '@stencil/core';
@Component({
tag: 'ion-icon',
assetsDirs: ['svg'],
styleUrl: 'icon.css',
shadow: true,
host: {
theme: 'icon'
},
assetsDir: 'svg'
})
export class Icon {
private io?: IntersectionObserver;
private iconName: string | null = null;
private inheritedAttributes: { [k: string]: any } = {};
private didLoadIcon = false;
@Element() el!: HTMLElement;
@State() private svgContent?: string;
@State() private isVisible = false;
@Prop({ context: 'mode' }) mode: string;
/**
* The mode determines which platform styles to use.
* @input {string} Specifies the label to use for accessibility. Defaults to the icon name.
*/
@Prop({ mutable: true }) mode = getIonMode();
@Prop() ariaLabel: string = '';
/**
* The color to use for the background of the item.
* @input {string} Specifies which icon to use. The appropriate icon will be used based on the mode.
* For more information, see [Ionicons](/docs/ionicons/).
*/
@Prop() color?: string;
@Prop() name: string = '';
/**
* Specifies which icon to use on `ios` mode.
* @input {string} Specifies which icon to use on `ios` mode.
*/
@Prop() ios?: string;
@Prop() ios: string = '';
/**
* Specifies which icon to use on `md` mode.
* @input {string} Specifies which icon to use on `md` mode.
*/
@Prop() md?: string;
@Prop() md: string = '';
/**
* Specifies whether the icon should horizontally flip when `dir` is `"rtl"`.
*/
@Prop() flipRtl?: boolean;
/**
* Specifies which icon to use from the built-in set of icons.
*/
@Prop({ reflect: true }) name?: string;
@Prop({ context: 'isServer'}) private isServer: boolean;
/**
* Specifies the exact `src` of an SVG file to use.
*/
@Prop() src?: string;
/**
* A combination of both `name` and `src`. If a `src` url is detected
* it will set the `src` property. Otherwise it assumes it's a built-in named
* SVG and set the `name` property.
*/
@Prop() icon?: any;
@State() private svgContent: string = null;
/**
* The size of the icon.
* Available options are: `"small"` and `"large"`.
*/
@Prop() size?: string;
/**
* If enabled, ion-icon will be loaded lazily when it's visible in the viewport.
* Default, `false`.
*/
@Prop() lazy = false;
/**
* When `true`, SVG content, including SVG `data:` URLs, is checked before it
* renders. SVGs with `<script>` elements, attributes that start with `on`
* (like `onclick`), `javascript:` URLs, or non-SVG elements aren't rendered,
* and `<foreignObject>` elements are removed. Only set this to `false` for
* SVG content from a trusted source.
* @default true
*/
@Prop() sanitize = true;
componentWillLoad() {
this.inheritedAttributes = inheritAttributes(this.el, ['aria-label']);
}
connectedCallback() {
/**
* purposely do not return the promise here because loading
* the svg file should not hold up loading the app
* only load the svg if it's visible
*/
this.waitUntilVisible(this.el, '50px', () => {
this.isVisible = true;
this.loadIcon();
});
}
/**
* Loads the icon after the component has finished rendering.
*/
componentDidLoad() {
/**
* Addresses an Angular issue where property values are assigned after the 'connectedCallback' but prior to the registration of watchers.
* This enhancement ensures the loading of an icon when the component has finished rendering and the icon has yet to apply the SVG data.
* This modification pertains to the usage of Angular's binding syntax:
* `<ion-icon [name]="myIconName"></ion-icon>`
*/
if (!this.didLoadIcon) {
this.loadIcon();
}
}
/**
* Disconnect the IntersectionObserver.
*/
disconnectedCallback() {
if (this.io) {
this.io.disconnect();
this.io = undefined;
}
}
/**
* Wait until the icon is visible in the viewport.
* @param el - The element to observe.
* @param rootMargin - The root margin of the observer.
* @param cb - The callback to call when the element is visible.
*/
private waitUntilVisible(el: HTMLElement, rootMargin: string, cb: () => void) {
/**
* IntersectionObserver is a browser API that allows you to observe
* the visibility of an element relative to a root element. It is
* supported in all modern browsers, except IE and when server-side
* rendering.
*/
const hasIntersectionObserverSupport = Boolean(
Build.isBrowser && this.lazy && typeof window !== 'undefined' && window.IntersectionObserver,
);
/**
* browser doesn't support IntersectionObserver
* so just fallback to always show it
*/
if (!hasIntersectionObserverSupport) {
return cb();
private get iconName() {
// if no name was passed set iconName to null
if (!this.name) {
return null;
}
const io = (this.io = new window.IntersectionObserver(
(data: IntersectionObserverEntry[]) => {
if (data[0].isIntersecting) {
io.disconnect();
this.io = undefined;
cb();
}
},
{ rootMargin },
));
let iconName = this.name.toLowerCase();
io.observe(el);
}
/**
* Watch for changes to the icon name, src, icon, ios, or md properties.
* When a change is detected, the icon will be loaded.
*/
@Watch('name')
@Watch('src')
@Watch('icon')
@Watch('ios')
@Watch('md')
loadIcon() {
if (Build.isBrowser && this.isVisible) {
const url = getUrl(this);
if (url) {
const cacheKey = getCacheKey(url, this.sanitize);
if (ioniconContent.has(cacheKey)) {
// sync if it's already loaded
this.svgContent = ioniconContent.get(cacheKey);
} else {
// async if it hasn't been loaded
getSvgContent(url, this.sanitize).then(() => (this.svgContent = ioniconContent.get(cacheKey)));
}
this.didLoadIcon = true;
}
}
this.iconName = getName(this.name, this.icon, this.mode, this.ios, this.md);
}
render() {
const { flipRtl, iconName, inheritedAttributes, el } = this;
// default to "md" if somehow the mode wasn't set
const mode = this.mode || 'md';
/**
* we have designated that arrows & chevrons should automatically flip (unless flip-rtl
* is set to false) because "back" is left in ltr and right in rtl, and "forward" is the opposite
*/
const shouldAutoFlip = iconName
? (iconName.includes('arrow') || iconName.includes('chevron')) && flipRtl !== false
: false;
if (!(/^md-|^ios-|^logo-/.test(iconName))) {
// this does not have one of the defaults
// so lets auto add in the mode prefix for them
iconName = mode + '-' + iconName;
/**
* if shouldBeFlippable is true, the icon should change direction when `dir` changes
*/
const shouldBeFlippable = flipRtl || shouldAutoFlip;
} else if (this.ios && mode === 'ios') {
// if an icon was passed in using the ios or md attributes
// set the iconName to whatever was passed in
// when we're also on that mode
// basically, use the ios attribute when you're on ios
iconName = this.ios;
return (
<Host
role="img"
class={{
[mode]: true,
...createColorClasses(this.color),
[`icon-${this.size}`]: !!this.size,
'flip-rtl': shouldBeFlippable,
'icon-rtl': shouldBeFlippable && isRTL(el),
}}
{...inheritedAttributes}
>
{Build.isBrowser && this.svgContent ? (
<div class="icon-inner" innerHTML={this.svgContent}></div>
) : (
<div class="icon-inner">
<slot></slot>
</div>
)}
</Host>
);
} else if (this.md && mode === 'md') {
// use the md attribute when you're in md mode
// and the md attribute has been set
iconName = this.md;
}
// only allow alpha characters and dash
const invalidChars = iconName.replace(/[a-z]|-|\d/g, '');
if (invalidChars !== '') {
console.error(`invalid characters in ion-icon name: ${invalidChars}`);
return null;
}
return iconName;
}
hostData() {
const attrs: {[attrName: string]: string} = {
'role': 'img'
};
if (this.ariaLabel) {
// user provided label
attrs['aria-label'] = this.ariaLabel;
} else {
// come up with the label based on the icon name
const iconName = this.iconName;
if (iconName) {
attrs['aria-label'] = iconName
.replace('ios-', '')
.replace('md-', '')
.replace(/\-/g, ' ');
}
}
return {
attrs
};
}
render() {
if (this.isServer) {
return <div class="icon-inner">{/* ssr */}</div>;
}
const iconName = this.iconName;
if (!iconName) {
// we don't have good data
return <div class="icon-inner">{/* invalid svg */}</div>;
}
const svgContent = svgContents[iconName];
if (svgContent === this.svgContent) {
// we've already loaded up this svg at one point
// and the svg content we've loaded and assigned checks out
// render this svg!!
return <div class="icon-inner" innerHTML={svgContent}></div>;
}
// haven't loaded this svg yet
// start the request
loadSvgContent(iconName, loadedSvgContent => {
// we're finished loading the svg content!
// set to this.svgContent so we do another render
this.svgContent = loadedSvgContent;
});
// actively requesting the svg, so let's just render a div for now
return <div class="icon-inner">{/* loading svg */}</div>;
}
}
/**
* Get the mode of the document.
* @returns The mode of the document.
*/
const getIonMode = () =>
(Build.isBrowser && typeof document !== 'undefined' && document.documentElement.getAttribute('mode')) || 'md';
/**
* Create color classes for the icon.
* @param color - The color of the icon.
* @returns The color classes for the icon.
*/
const createColorClasses = (color: string | undefined) => {
return color
? {
'ion-color': true,
[`ion-color-${color}`]: true,
}
: null;
function loadSvgContent(iconName: string, callback: {(loadedSvgContent: string): void}) {
// static since all IonIcons use this same function and pointing at global/shared data
// passed in callback will have instance info
// add to the list of callbacks to fiure when this url is finished loading
(loadCallbacks[iconName] = loadCallbacks[iconName] || []).push(callback);
if (activeRequests[iconName]) {
// already requesting this icon, don't bother kicking off another
return;
}
// add this icons to our list of active requests
activeRequests[iconName] = true;
// kick off the request for the external svg file
// create a script element to add to the document.head
var scriptElm = document.createElement('script');
scriptElm.charset = 'utf-8';
scriptElm.async = true;
scriptElm.src = `${publicPath}svg/${iconName}.js`;
// create a fallback timeout if something goes wrong
var tmrId = setTimeout(onScriptComplete, 120000);
function onScriptComplete() {
clearTimeout(tmrId);
scriptElm.onerror = scriptElm.onload = null;
scriptElm.parentNode.removeChild(scriptElm);
// remove from our list of active requests
delete activeRequests[iconName];
}
// add script completed listener to this script element
scriptElm.onerror = scriptElm.onload = onScriptComplete;
// inject a script tag in the head
// kick off the actual request
document.head.appendChild(scriptElm);
}
const activeRequests: {[iconName: string]: boolean} = {};
const loadCallbacks: {[iconName: string]: {(loadedSvgContent: string): void}[]} = [] as any;
const svgContents: {[iconName: string]: string} = {};
// add a jsonp handler to the window
// as svg jsonp files are requested
// once they load they'll call this method
(window as any).loadIonicon = function loadIonicon(svgContent: string, iconName: string) {
// awesome, we've finished loading the svg file
// remove this url from the active requests
delete activeRequests[iconName];
svgContents[iconName] = svgContent
// find any callbacks waiting on this icon
const svgLoadCallbacks = loadCallbacks[iconName];
if (svgLoadCallbacks) {
// loop through all the callbacks that are waiting on the svg content
svgLoadCallbacks.forEach(cb => {
// fire off this callback which was provided by an instance
cb(svgContent);
});
delete loadCallbacks[iconName];
}
};
-27
View File
@@ -1,27 +0,0 @@
# ion-icon
<!-- Auto Generated Below -->
## Properties
| Property | Attribute | Description | Type | Default |
| ---------- | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- | -------------- |
| `color` | `color` | The color to use for the background of the item. | `string \| undefined` | `undefined` |
| `flipRtl` | `flip-rtl` | Specifies whether the icon should horizontally flip when `dir` is `"rtl"`. | `boolean \| undefined` | `undefined` |
| `icon` | `icon` | A combination of both `name` and `src`. If a `src` url is detected it will set the `src` property. Otherwise it assumes it's a built-in named SVG and set the `name` property. | `any` | `undefined` |
| `ios` | `ios` | Specifies which icon to use on `ios` mode. | `string \| undefined` | `undefined` |
| `lazy` | `lazy` | If enabled, ion-icon will be loaded lazily when it's visible in the viewport. Default, `false`. | `boolean` | `false` |
| `md` | `md` | Specifies which icon to use on `md` mode. | `string \| undefined` | `undefined` |
| `mode` | `mode` | The mode determines which platform styles to use. | `string` | `getIonMode()` |
| `name` | `name` | Specifies which icon to use from the built-in set of icons. | `string \| undefined` | `undefined` |
| `sanitize` | `sanitize` | When `true`, SVG content, including SVG `data:` URLs, is checked before it renders. SVGs with `<script>` elements, attributes that start with `on` (like `onclick`), `javascript:` URLs, or non-SVG elements aren't rendered, and `<foreignObject>` elements are removed. Only set this to `false` for SVG content from a trusted source. | `boolean` | `true` |
| `size` | `size` | The size of the icon. Available options are: `"small"` and `"large"`. | `string \| undefined` | `undefined` |
| `src` | `src` | Specifies the exact `src` of an SVG file to use. | `string \| undefined` | `undefined` |
----------------------------------------------
*Built with [StencilJS](https://stenciljs.com/)*
-111
View File
@@ -1,111 +0,0 @@
import { isEncodedDataUrl, isSvgDataUrl, validateContent } from './validate';
export const ioniconContent = new Map<string, string>();
const requests = new Map<string, Promise<any>>();
let parser: DOMParser;
/**
* Unsanitized content gets its own key so it's never served to an icon that
* sanitizes.
*/
export const getCacheKey = (url: string, sanitize: boolean) =>
`${sanitize !== false ? 'sanitized' : 'unsanitized'}:${url}`;
/**
* Warns when the whole icon is rejected so it doesn't silently render nothing.
*/
const sanitizeSvg = (url: string, svgContent: string) =>
validateContent(svgContent, () => {
const source = url.length > 100 ? `${url.slice(0, 100)}...` : url;
console.warn(
`[Ionicons Warning]: The SVG from "${source}" was not rendered because it failed sanitization. Only set sanitize="false" for SVG content from a trusted source.`,
);
});
/**
* Safely fallback to an empty svg
*/
function safeFallback(cacheKey: string) {
const svg = '';
ioniconContent.set(cacheKey, svg);
return svg;
}
export const getSvgContent = (url: string, sanitize: boolean): Promise<string> => {
const cacheKey = getCacheKey(url, sanitize);
/**
* See if we already have a request for this url
*/
const req = requests.get(cacheKey);
if (req) {
return req;
}
if (typeof fetch !== 'undefined' && typeof document !== 'undefined') {
/**
* If the url is a data url of an svg, then try to parse it
* with the DOMParser. This works with content security policies enabled.
*/
if (isSvgDataUrl(url) && isEncodedDataUrl(url)) {
return Promise.resolve(getSvgByUrl(url, sanitize));
}
return fetchSvg(url, sanitize);
}
return Promise.resolve(safeFallback(cacheKey));
};
function getSvgByUrl(url: string, sanitize: boolean): string {
if (!parser) {
/**
* Create an instance of the DOM parser. This creates a single
* parser instance for the entire app, which is more efficient.
*/
parser = new DOMParser();
}
const doc = parser.parseFromString(url, 'text/html');
const svg = doc.querySelector('svg');
if (svg) {
const svgContent = sanitize !== false ? sanitizeSvg(url, svg.outerHTML) : svg.outerHTML;
ioniconContent.set(getCacheKey(url, sanitize), svgContent);
return svgContent;
}
throw new Error(`Could not parse svg from ${url}`);
}
function fetchSvg(url: string, sanitize: boolean): Promise<string> {
const cacheKey = getCacheKey(url, sanitize);
/**
* We don't already have a request
*/
const req = fetch(url)
.then((rsp) => {
/**
* When fetching from a file:// URL, some browsers return
* a 0 status code even when the request succeeds so don't
* rely on rsp.ok as the only signal of success.
*/
return rsp
.text()
.then((svgContent) => {
if (svgContent && sanitize !== false) {
svgContent = sanitizeSvg(url, svgContent);
}
const svg = svgContent || '';
ioniconContent.set(cacheKey, svg);
return svg;
})
.catch(() => safeFallback(cacheKey));
})
.catch(() => safeFallback(cacheKey));
/**
* Cache for the same requests
*/
requests.set(cacheKey, req);
return req;
}
+1
View File
@@ -1,4 +1,5 @@
# this gitignore file is used as a placeholder
# for this directory. The directory itself will
# contain files generated during a build step.
*
!.gitignore
-15
View File
@@ -1,15 +0,0 @@
import { expect } from '@playwright/test';
import { test } from '@utils/test/playwright';
import { AxeBuilder } from '@axe-core/playwright';
test.describe('icon: a11y', () => {
test('should pass accessibility checks', async ({ page }) => {
await page.goto(`/icon/test/a11y/`);
await page.waitForLoadState('networkidle');
const results = await new AxeBuilder({ page }).analyze();
expect(results.violations).toEqual([]);
});
});
-59
View File
@@ -1,59 +0,0 @@
<!doctype html>
<html dir="ltr" lang="en" mode="ios">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0" />
<title>Icon - Accessibility</title>
<script type="module" src="/build/ionicons.esm.js"></script>
<script nomodule src="/build/ionicons.js"></script>
<link rel="stylesheet" href="../styles.css" />
<script src="../header.js"></script>
<!-- Font Awesome Icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css" />
</head>
<body>
<test-header></test-header>
<main>
<h1>Icon - Accessibility</h1>
<h2>SVG icon with aria-label</h2>
<ion-icon name="cellular" aria-label="Mobile data"></ion-icon>
<h2>Button with aria-label and SVG icon</h2>
<button aria-label="Mobile data">
<ion-icon name="cellular" aria-hidden="true"></ion-icon>
</button>
<h2>SVG icon with aria-hidden</h2>
<ion-icon name="cellular" aria-hidden="true"></ion-icon>
<hr />
<h2>Font icon with aria-label</h2>
<ion-icon aria-label="Mobile data">
<i class="fa fa-home"></i>
</ion-icon>
<h2>Button with aria-label and font icon</h2>
<button aria-label="Mobile data">
<ion-icon aria-hidden="true">
<i class="fa fa-home"></i>
</ion-icon>
</button>
<h2>Font icon with aria-hidden</h2>
<ion-icon aria-hidden="true">
<i class="fa fa-home"></i>
</ion-icon>
</main>
<style>
ion-icon {
font-size: 32px;
}
</style>
</body>
</html>
@@ -1,13 +0,0 @@
import { expect } from '@playwright/test';
import { test } from '@utils/test/playwright';
test.describe('icon: basic', () => {
test('should not have visual regressions', async ({ page }) => {
await page.goto(`/icon/test/basic/`);
// Wait for all SVGs to be lazily loaded before taking screenshots
await page.waitForLoadState('networkidle');
await expect(page).toHaveScreenshot(`icon-basic.png`, { fullPage: true });
});
});
Binary file not shown.

Before

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 68 KiB

-101
View File
@@ -1,101 +0,0 @@
<!doctype html>
<html dir="ltr" lang="en" mode="ios">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0" />
<title>Icon - Basic</title>
<script type="module" src="/build/ionicons.esm.js"></script>
<script nomodule src="/build/ionicons.js"></script>
<link rel="stylesheet" href="../styles.css" />
<script src="../header.js"></script>
</head>
<body>
<test-header></test-header>
<main>
<h1>Icon - Basic</h1>
<h2>Default</h2>
<ion-icon name="cellular"></ion-icon>
<ion-icon name="at"></ion-icon>
<ion-icon name="call"></ion-icon>
<ion-icon name="football"></ion-icon>
<ion-icon name="analytics"></ion-icon>
<ion-icon name="grid"></ion-icon>
<ion-icon name="funnel"></ion-icon>
<ion-icon name="watch"></ion-icon>
<ion-icon name="add-circle-outline"></ion-icon>
<h2>Mode from html ios mode attribute</h2>
<ion-icon md="logo-android" ios="logo-apple"></ion-icon>
<ion-icon md="logo-android" ios="logo-apple"></ion-icon>
<h2>Mode set on icon</h2>
<ion-icon mode="ios" md="logo-android" ios="logo-apple"></ion-icon>
<ion-icon mode="md" md="logo-android" ios="logo-apple"></ion-icon>
<h2>Colors</h2>
<ion-icon color="primary" name="cellular"></ion-icon>
<ion-icon color="secondary" name="at"></ion-icon>
<ion-icon color="tertiary" name="call"></ion-icon>
<ion-icon color="success" name="football"></ion-icon>
<ion-icon color="warning" name="analytics"></ion-icon>
<ion-icon color="danger" name="grid"></ion-icon>
<ion-icon color="light" name="funnel"></ion-icon>
<ion-icon color="medium" name="watch"></ion-icon>
<ion-icon color="dark" name="toggle"></ion-icon>
<h2>Stroke width</h2>
<ion-icon name="heart-outline" style="--ionicon-stroke-width: 8px"></ion-icon>
<h2>Font size</h2>
<ion-icon name="book" style="font-size: 50px"></ion-icon>
<ion-icon src="../../assets/bug_report.svg" style="font-size: 50px"></ion-icon>
<h2>Custom SVGs</h2>
<ion-icon src="../../assets/bug_report.svg"></ion-icon>
<ion-icon src="../../assets/chat.svg"></ion-icon>
<ion-icon src="../../assets/commute.svg"></ion-icon>
<ion-icon src="../../assets/copyright.svg"></ion-icon>
<ion-icon src="../../assets/done_all.svg"></ion-icon>
<ion-icon src="../../assets/lock_open.svg"></ion-icon>
<ion-icon src="../../assets/toll.svg"></ion-icon>
<ion-icon src="../../assets/web_asset.svg"></ion-icon>
<ion-icon src="../../assets/work_outline.svg"></ion-icon>
<h2>Custom SVGs: colors</h2>
<ion-icon color="primary" src="../../assets/bug_report.svg"></ion-icon>
<ion-icon color="secondary" src="../../assets/chat.svg"></ion-icon>
<ion-icon color="tertiary" src="../../assets/commute.svg"></ion-icon>
<ion-icon color="success" src="../../assets/copyright.svg"></ion-icon>
<ion-icon color="warning" src="../../assets/done_all.svg"></ion-icon>
<ion-icon color="danger" src="../../assets/lock_open.svg"></ion-icon>
<ion-icon color="light" src="../../assets/toll.svg"></ion-icon>
<ion-icon color="medium" src="../../assets/web_asset.svg"></ion-icon>
<ion-icon color="dark" src="../../assets/work_outline.svg"></ion-icon>
<h2>Custom CSS</h2>
<ion-icon class="custom" name="grid"></ion-icon>
<ion-icon class="custom" name="funnel"></ion-icon>
<ion-icon class="custom" name="watch"></ion-icon>
<ion-icon class="custom" name="logo-react"></ion-icon>
<ion-icon class="custom" name="logo-javascript"></ion-icon>
<ion-icon class="custom" name="logo-angular"></ion-icon>
<ion-icon class="custom" src="../../assets/done_all.svg"></ion-icon>
<ion-icon class="custom" src="../../assets/web_asset.svg"></ion-icon>
<ion-icon class="custom" src="../../assets/work_outline.svg"></ion-icon>
</main>
<style>
ion-icon {
font-size: 32px;
}
.custom {
stroke: red;
fill: blue;
}
</style>
</body>
</html>
-13
View File
@@ -1,13 +0,0 @@
import { expect } from '@playwright/test';
import { test } from '@utils/test/playwright';
test.describe('icon: csp', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/icon/test/csp');
});
test('should load svg', async ({ page }) => {
const svg = page.locator('ion-icon#icon-usage svg');
await expect(svg).toBeVisible();
});
});
-52
View File
@@ -1,52 +0,0 @@
<!doctype html>
<html dir="ltr" lang="en" mode="ios">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0" />
<meta
http-equiv="Content-Security-Policy"
content="default-src 'none'; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com/*; img-src 'self'; connect-src 'self'; font-src https://fonts.gstatic.com/*'"
/>
<title>Icon - Content Security Policy</title>
<script type="module" src="/build/ionicons.esm.js"></script>
<script nomodule src="/build/ionicons.js"></script>
<link rel="stylesheet" href="../styles.css" />
<script src="../header.js"></script>
</head>
<body>
<test-header></test-header>
<main>
<h1>Icon - Content Security Policy</h1>
<h2>Default</h2>
<ion-icon src="/assets/chat.svg"></ion-icon>
<ion-icon name="add"></ion-icon>
<ion-icon
id="icon-usage"
icon="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><title>Watch</title><rect x='136' y='136' width='240' height='240' rx='8' ry='8'/><path d='M384 96h-48V16H176v80h-48a32 32 0 00-32 32v256a32 32 0 0032 32h48v80h160v-80h48a32 32 0 0032-32V128a32 32 0 00-32-32zm8 272a24 24 0 01-24 24H144a24 24 0 01-24-24V144a24 24 0 0124-24h224a24 24 0 0124 24z'/></svg>"
>
</ion-icon>
<ion-icon
class="custom"
icon="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><title>Watch</title><rect x='136' y='136' width='240' height='240' rx='8' ry='8'/><path d='M384 96h-48V16H176v80h-48a32 32 0 00-32 32v256a32 32 0 0032 32h48v80h160v-80h48a32 32 0 0032-32V128a32 32 0 00-32-32zm8 272a24 24 0 01-24 24H144a24 24 0 01-24-24V144a24 24 0 0124-24h224a24 24 0 0124 24z'/></svg>"
>
</ion-icon>
</main>
</body>
<style>
ion-icon {
font-size: 32px;
}
.custom {
stroke: red;
fill: goldenrod;
color: black;
}
</style>
</html>
@@ -1,16 +0,0 @@
import { expect } from '@playwright/test';
import { test } from '@utils/test/playwright';
test.describe('icon: dynamic type', () => {
test.beforeEach(async ({ page }) => {
await page.goto(`/icon/test/dynamic-type/`);
});
test('should scale text on larger font sizes', async ({ page }) => {
// Wait for all SVGs to be lazily loaded before taking screenshots
await page.waitForLoadState('networkidle');
const main = page.locator('main');
await expect(main).toHaveScreenshot(`icon-dynamic-type.png`);
});
});
Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

@@ -1,45 +0,0 @@
<!doctype html>
<html dir="ltr" lang="en" mode="ios">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0" />
<title>Icon - Dynamic Type</title>
<script type="module" src="/build/ionicons.esm.js"></script>
<script nomodule src="/build/ionicons.js"></script>
<link rel="stylesheet" href="../styles.css" />
<script src="../header.js"></script>
<!-- Font Awesome Icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css" />
</head>
<body>
<test-header></test-header>
<main>
<h1>Icon - Dynamic Type</h1>
<h2>Default Icons</h2>
<ion-icon name="star"></ion-icon>
<ion-icon name="star" size="small"></ion-icon>
<ion-icon name="star" size="large"></ion-icon>
<h2>Font Icons</h2>
<ion-icon>
<i class="fa fa-star"></i>
</ion-icon>
<ion-icon size="small">
<i class="fa fa-star"></i>
</ion-icon>
<ion-icon size="large">
<i class="fa fa-star"></i>
</ion-icon>
</main>
<style>
html {
font-size: 28px;
}
</style>
</body>
</html>
-14
View File
@@ -1,14 +0,0 @@
class TestHeader extends HTMLElement {
connectedCallback() {
const header = document.createElement('header');
header.innerHTML = `
<a href="/" class="back-button">
<ion-icon name="arrow-back" aria-hidden="true"></ion-icon>
Back
</a>
`;
this.appendChild(header);
}
}
customElements.define('test-header', TestHeader);
-202
View File
@@ -1,202 +0,0 @@
import { newSpecPage } from 'jest-stencil-runner';
import { Icon } from '../icon';
describe('icon', () => {
describe('basic rendering', () => {
it('renders', async () => {
const { root } = await newSpecPage({
components: [Icon],
html: '<ion-icon></ion-icon>',
});
expect(root).toEqualHtml(`
<ion-icon class="md" role="img">
<mock:shadow-root>
<div class="icon-inner">
<slot></slot>
</div>
</mock:shadow-root>
</ion-icon>
`);
});
it('renders rtl with aria-hidden', async () => {
const { root } = await newSpecPage({
components: [Icon],
direction: 'rtl',
html: `<ion-icon name="chevron-forward" aria-hidden="true"></ion-icon>`,
});
expect(root).toEqualHtml(`
<ion-icon class="md flip-rtl icon-rtl" name="chevron-forward" role="img" aria-hidden="true">
<mock:shadow-root>
<div class="icon-inner">
<slot></slot>
</div>
</mock:shadow-root>
</ion-icon>
`);
});
it('renders custom aria-label', async () => {
const { root } = await newSpecPage({
components: [Icon],
html: `<ion-icon name="star" aria-label="custom label"></ion-icon>`,
});
expect(root).toEqualHtml(`
<ion-icon class="md" name="star" role="img" aria-label="custom label">
<mock:shadow-root>
<div class="icon-inner">
<slot></slot>
</div>
</mock:shadow-root>
</ion-icon>
`);
});
});
describe('dynamic rendering', () => {
it('renders custom label after changing source', async () => {
const page = await newSpecPage({
components: [Icon],
html: `<ion-icon name="chevron-forward" aria-label="custom label"></ion-icon>`,
});
const icon = page.root;
expect(icon).toEqualHtml(`
<ion-icon class="flip-rtl md" name="chevron-forward" role="img" aria-label="custom label">
<mock:shadow-root>
<div class="icon-inner">
<slot></slot>
</div>
</mock:shadow-root>
</ion-icon>
`);
if (icon) {
icon.name = 'trash';
}
await page.waitForChanges();
expect(icon).toEqualHtml(`
<ion-icon class="md" name="trash" role="img" aria-label="custom label">
<mock:shadow-root>
<div class="icon-inner">
<slot></slot>
</div>
</mock:shadow-root>
</ion-icon>
`);
});
});
describe('svg rendering scenarios', () => {
it('svgContent=true: renders svg without slot', async () => {
const page = await newSpecPage({
components: [Icon],
html: `<ion-icon aria-hidden="true" part="close-icon" class="close-icon"></ion-icon>`,
});
const icon = page.root as any;
const instance = page.rootInstance as any;
instance.svgContent = '<svg><circle cx="50" cy="50" r="40"/></svg>';
await page.waitForChanges();
const shadowRoot = icon.shadowRoot;
const iconInner = shadowRoot?.querySelector('.icon-inner');
// Should have no slot
const slot = iconInner?.querySelector('slot');
expect(slot).toBeNull();
// SVG should be a direct child of icon-inner,
// not nested in another div
expect(iconInner?.children.length).toBe(1);
const firstChild = iconInner?.children[0];
expect((firstChild as any)?.tagName?.toLowerCase()).toBe('svg');
expect(firstChild?.querySelector('circle')).not.toBeNull();
});
it('svgContent=false: renders slot for custom content', async () => {
const page = await newSpecPage({
components: [Icon],
html: `<ion-icon aria-hidden="true" part="close-icon" class="close-icon"></ion-icon>`,
});
const icon = page.root as any;
const shadowRoot = icon.shadowRoot;
const iconInner = shadowRoot?.querySelector('.icon-inner');
const slot = iconInner?.querySelector('slot');
const svg = iconInner?.querySelector('svg');
expect(slot).not.toBeNull();
expect(svg).toBeNull();
});
});
describe('slotted content', () => {
it('renders slotted font icon (Font Awesome)', async () => {
const { root } = await newSpecPage({
components: [Icon],
html: `
<ion-icon>
<i class="fa fa-home"></i>
</ion-icon>
`,
});
expect(root).toEqualHtml(`
<ion-icon class="md" role="img">
<mock:shadow-root>
<div class="icon-inner">
<slot></slot>
</div>
</mock:shadow-root>
<i class="fa fa-home"></i>
</ion-icon>
`);
});
it('renders slotted font icon with color', async () => {
const { root } = await newSpecPage({
components: [Icon],
html: `
<ion-icon color="primary">
<i class="fa fa-heart"></i>
</ion-icon>
`,
});
expect(root).toEqualHtml(`
<ion-icon class="md ion-color ion-color-primary" color="primary" role="img">
<mock:shadow-root>
<div class="icon-inner">
<slot></slot>
</div>
</mock:shadow-root>
<i class="fa fa-heart"></i>
</ion-icon>
`);
});
it('renders slotted font icon with custom style', async () => {
const { root } = await newSpecPage({
components: [Icon],
html: `
<ion-icon style="font-size: 48px">
<i class="fa fa-star"></i>
</ion-icon>
`,
});
expect(root).toEqualHtml(`
<ion-icon class="md" role="img" style="font-size: 48px">
<mock:shadow-root>
<div class="icon-inner">
<slot></slot>
</div>
</mock:shadow-root>
<i class="fa fa-star"></i>
</ion-icon>
`);
});
});
});
-66
View File
@@ -1,66 +0,0 @@
<!doctype html>
<html dir="ltr" lang="en" mode="ios">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0" />
<title>Icon Tests</title>
<script type="module" src="/build/ionicons.esm.js"></script>
<script nomodule src="/build/ionicons.js"></script>
<link rel="stylesheet" href="./icon/test/styles.css" />
<script src="./icon/test/header.js"></script>
</head>
<body>
<main>
<h1>Icon Tests</h1>
<p>Select a test category to view the icon component tests.</p>
<div class="grid">
<a href="/icon/test/a11y/" class="card">
<h3>Accessibility</h3>
<p>ARIA labels and accessible icon patterns</p>
</a>
<a href="/icon/test/basic/" class="card">
<h3>Basic</h3>
<p>Default SVG icons, modes, colors, sizes, and custom SVGs</p>
</a>
<a href="/icon/test/cheatsheet/" class="card">
<h3>Cheatsheet</h3>
<p>Visual reference of all available ionicons</p>
</a>
<a href="/icon/test/csp/" class="card">
<h3>Content Security Policy</h3>
<p>SVG content loading with Content Security Policy</p>
</a>
<a href="/icon/test/dynamic-type/" class="card">
<h3>Dynamic Type</h3>
<p>Font size scaling and dynamic text sizing behavior</p>
</a>
<a href="/icon/test/rtl/" class="card">
<h3>RTL</h3>
<p>Right-to-left text direction and icon flipping behavior</p>
</a>
<a href="/icon/test/sanitization/" class="card">
<h3>Sanitization</h3>
<p>SVG content sanitization and security</p>
</a>
<a href="/icon/test/size/" class="card">
<h3>Size</h3>
<p>Size prop with small and large variants for native and slotted icons</p>
</a>
<a href="/icon/test/slotted/" class="card">
<h3>Slotted Content</h3>
<p>Font Awesome, Material, Phosphor, Bootstrap, and custom SVGs</p>
</a>
</div>
</main>
</body>
</html>

Some files were not shown because too many files have changed in this diff Show More