├── .all-contributorsrc
├── .gitignore
├── .husky
├── commit-msg
└── pre-commit
├── .npmignore
├── .prettierrc
├── .releaserc
├── .travis.yml
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── LICENSE
├── README.md
├── builders.json
├── commitlint.config.js
├── jest.config.js
├── package-lock.json
├── package.json
├── schematics
├── collection.json
├── ng-add
│ ├── index.spec.ts
│ └── index.ts
└── ng-generate-icon-lib
│ ├── files
│ └── __name@dasherize__
│ │ ├── __name@dasherize__-registry.service.spec.ts
│ │ ├── __name@dasherize__-registry.service.ts
│ │ ├── __name@dasherize__.component.spec.ts
│ │ ├── __name@dasherize__.component.ts
│ │ └── __name@dasherize__.module.ts
│ ├── index.ts
│ ├── schema.json
│ └── schema.model.ts
├── svg-icons-builder
├── constants
│ ├── index.spec.ts
│ └── index.ts
├── files
│ ├── index.spec.ts
│ └── index.ts
├── object
│ ├── index.spec.ts
│ └── index.ts
├── schema.json
└── test-helpers.ts
├── tsconfig.json
└── tsconfig.spec.json
/.all-contributorsrc:
--------------------------------------------------------------------------------
1 | {
2 | "projectName": "@angular-extensions/svg-icons-builder",
3 | "projectOwner": "@angular-extensions",
4 | "repoType": "github",
5 | "repoHost": "https://github.com",
6 | "files": [
7 | "README.md"
8 | ],
9 | "imageSize": 100,
10 | "commit": true,
11 | "commitConvention": "angular",
12 | "contributors": [
13 | {
14 | "login": "kaltepeter",
15 | "name": "Kayla Altepeter",
16 | "avatar_url": "https://avatars1.githubusercontent.com/u/5103752?v=4",
17 | "profile": "http://www.kaylaaltepeter.com/",
18 | "contributions": [
19 | "code",
20 | "bug",
21 | "doc",
22 | "ideas",
23 | "test"
24 | ]
25 | },
26 | {
27 | "login": "kreuzerk",
28 | "name": "Kevin Kreuzer",
29 | "avatar_url": "https://avatars0.githubusercontent.com/u/5468954?v=4",
30 | "profile": "https://medium.com/@kevinkreuzer",
31 | "contributions": [
32 | "code",
33 | "bug",
34 | "doc",
35 | "ideas",
36 | "test"
37 | ]
38 | }
39 | ],
40 | "contributorsPerLine": 7
41 | }
42 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 | lerna-debug.log*
8 |
9 | # Diagnostic reports (https://nodejs.org/api/report.html)
10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
11 |
12 | # Runtime data
13 | pids
14 | *.pid
15 | *.seed
16 | *.pid.lock
17 |
18 | # Directory for instrumented libs generated by jscoverage/JSCover
19 | lib-cov
20 |
21 | # Coverage directory used by tools like istanbul
22 | coverage
23 | *.lcov
24 |
25 | # nyc test coverage
26 | .nyc_output
27 |
28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
29 | .grunt
30 |
31 | # Bower dependency directory (https://bower.io/)
32 | bower_components
33 |
34 | # node-waf configuration
35 | .lock-wscript
36 |
37 | # Compiled binary addons (https://nodejs.org/api/addons.html)
38 | build/Release
39 |
40 | # Dependency directories
41 | node_modules/
42 | jspm_packages/
43 |
44 | # TypeScript v1 declaration files
45 | typings/
46 |
47 | # TypeScript cache
48 | *.tsbuildinfo
49 |
50 | # Optional npm cache directory
51 | .npm
52 |
53 | # Optional eslint cache
54 | .eslintcache
55 |
56 | # Microbundle cache
57 | .rpt2_cache/
58 | .rts2_cache_cjs/
59 | .rts2_cache_es/
60 | .rts2_cache_umd/
61 |
62 | # Optional REPL history
63 | .node_repl_history
64 |
65 | # Output of 'npm pack'
66 | *.tgz
67 |
68 | # Yarn Integrity file
69 | .yarn-integrity
70 |
71 | # dotenv environment variables file
72 | .env
73 | .env.test
74 |
75 | # parcel-bundler cache (https://parceljs.org/)
76 | .cache
77 |
78 | # Next.js build output
79 | .next
80 |
81 | # Nuxt.js build / generate output
82 | .nuxt
83 | dist
84 |
85 | # Gatsby files
86 | .cache/
87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js
88 | # https://nextjs.org/blog/next-9-1#public-directory-support
89 | # public
90 |
91 | # vuepress build output
92 | .vuepress/dist
93 |
94 | # Serverless directories
95 | .serverless/
96 |
97 | # FuseBox cache
98 | .fusebox/
99 |
100 | # DynamoDB Local files
101 | .dynamodb/
102 |
103 | # TernJS port file
104 | .tern-port
105 |
106 | # IDEs
107 | .idea/
108 | jsconfig.json
109 | .vscode/
110 |
111 | # Misc
112 | node_modules/
113 | npm-debug.log*
114 | yarn-error.log*
115 |
116 | # Mac OSX Finder files.
117 | **/.DS_Store
118 | .DS_Store
119 |
--------------------------------------------------------------------------------
/.husky/commit-msg:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 | . "$(dirname -- "$0")/_/husky.sh"
3 |
4 | npx commitlint --edit $1
5 |
--------------------------------------------------------------------------------
/.husky/pre-commit:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 | . "$(dirname -- "$0")/_/husky.sh"
3 |
4 | npx pretty-quick --staged --pattern ./**/*.ts
5 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | # Ignores TypeScript files, but keeps definitions.
2 | *.ts
3 | !*.d.ts
4 | packgage-lock.json
5 | tsconfig.json
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "singleQuote": true,
3 | "printWidth": 120,
4 | "tabWidth": 2
5 | }
6 |
--------------------------------------------------------------------------------
/.releaserc:
--------------------------------------------------------------------------------
1 | {
2 | "pkgRoot": "dist",
3 | "branches": ["main"],
4 | "plugins": [
5 | "@semantic-release/commit-analyzer",
6 | "@semantic-release/release-notes-generator",
7 | "@semantic-release/changelog",
8 | "@semantic-release/npm",
9 | ["@semantic-release/exec", {
10 | "prepareCmd": "VERSION=${nextRelease.version} npm run bump-version"
11 | }],
12 | ["@semantic-release/git", {
13 | "assets": ["package.json", "CHANGELOG.md"],
14 | "message": "chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"
15 | }],
16 | "@semantic-release/github"
17 | ]
18 | }
19 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | dist: trusty
2 | sudo: required
3 | language: node_js
4 | node_js:
5 | - '14'
6 |
7 | os:
8 | - linux
9 |
10 | jobs:
11 | include:
12 | - stage: install
13 | script: npm install
14 | skip_cleanup: true
15 | - stage: test
16 | script: npm run test
17 | skip_cleanup: true
18 | - stage: Build & publish
19 | script:
20 | - npm run build
21 | - npx semantic-release
22 | if: branch = main
23 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # [3.0.0](https://github.com/angular-extensions/svg-icons-builder/compare/v2.0.0...v3.0.0) (2021-12-02)
2 |
3 |
4 | ### Features
5 |
6 | * 🎸 (deps) update svg-to-ts to v7 ([a376f9d](https://github.com/angular-extensions/svg-icons-builder/commit/a376f9d8c1df8574eac7f9ecabdd63bbaf2cd082))
7 |
8 |
9 | ### BREAKING CHANGES
10 |
11 | * 🧨 Update svg-to-ts to v7
12 |
13 | # [2.0.0](https://github.com/angular-extensions/svg-icons-builder/compare/v1.1.0...v2.0.0) (2021-08-19)
14 |
15 |
16 | ### Features
17 |
18 | * 🎸 (deps) update svg-to-ts to v6 ([3d06fed](https://github.com/angular-extensions/svg-icons-builder/commit/3d06fedb9491b514d7a0b9c33f0c05a5b86a6325))
19 |
20 |
21 | ### BREAKING CHANGES
22 |
23 | * 🧨 Update svg-to-ts to v6
24 |
25 | # [1.1.0](https://github.com/angular-extensions/svg-icons-builder/compare/v1.0.0...v1.1.0) (2021-01-18)
26 |
27 |
28 | ### Bug Fixes
29 |
30 | * 🐛 adjust schema.json ([cfb1a76](https://github.com/angular-extensions/svg-icons-builder/commit/cfb1a76dce128af4645a77e34522061a1b5d969c))
31 |
32 |
33 | ### Features
34 |
35 | * 🎸 add scheamtics to generate an icon library ([43e19f9](https://github.com/angular-extensions/svg-icons-builder/commit/43e19f927ec6263e8eee9cda4e77e778d3feeff7))
36 |
37 | # 1.0.0 (2020-11-16)
38 |
39 | ### Bug Fixes
40 |
41 | - 🐛 adjust path in builders.json ([ef69a21](https://github.com/angular-extensions/svg-icons-builder/commit/ef69a212830b1722ef4cf7487e5a0f9f1f560a28))
42 | - **tests:** fixing tests, WIP ([437ca77](https://github.com/angular-extensions/svg-icons-builder/commit/437ca773c1968b1be940e1f62dec64d74b49a4b7))
43 |
44 | ### Features
45 |
46 | - **builder:** creating ([58a4b7d](https://github.com/angular-extensions/svg-icons-builder/commit/58a4b7d0fd7d4de007cda64903e491ad0a8e146f))
47 | - **ng:** generate blank schematics ([578fe84](https://github.com/angular-extensions/svg-icons-builder/commit/578fe8461bf0ee4fc349ec54bf592afc1b9bbe73))
48 | - **ng-add:** integrate with ng-add ([0988b19](https://github.com/angular-extensions/svg-icons-builder/commit/0988b1964a6c5ccac9ee460817dcad8cd060a93d))
49 | - **schemas:** extend schema and split builders ([4d3171b](https://github.com/angular-extensions/svg-icons-builder/commit/4d3171b7f7f96c74b538eb2eb5651eec356f7045))
50 | - 🎸 enrich options with default options ([94bd99f](https://github.com/angular-extensions/svg-icons-builder/commit/94bd99f865318c8d2390d8ff265fb4cd8ef512b9))
51 | - **test:** fix the structure for tests and build ([fed021e](https://github.com/angular-extensions/svg-icons-builder/commit/fed021e6066d7f3c83e557142e4e67bb3fbc1553))
52 | - 🎸 handle exception and quit process ([801c734](https://github.com/angular-extensions/svg-icons-builder/commit/801c734575b079c24b18535d3d20b8f18828af6f))
53 | - fix tests ([8816187](https://github.com/angular-extensions/svg-icons-builder/commit/8816187eb3b51bbe72e3c1daf7304ea3ba783989))
54 | - **ng-add:** generate ([bb5a94e](https://github.com/angular-extensions/svg-icons-builder/commit/bb5a94ea9ff237768f15436fd70c557356a0cf82))
55 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | Contributor Covenant Code of Conduct
2 | Our Pledge
3 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
4 |
5 | Our Standards
6 | Examples of behavior that contributes to creating a positive environment include:
7 |
8 | Using welcoming and inclusive language
9 | Being respectful of differing viewpoints and experiences
10 | Gracefully accepting constructive criticism
11 | Focusing on what is best for the community
12 | Showing empathy towards other community members
13 | Examples of unacceptable behavior by participants include:
14 |
15 | The use of sexualized language or imagery and unwelcome sexual attention or advances
16 | Trolling, insulting/derogatory comments, and personal or political attacks
17 | Public or private harassment
18 | Publishing others' private information, such as a physical or electronic address, without explicit permission
19 | Other conduct which could reasonably be considered inappropriate in a professional setting
20 | Our Responsibilities
21 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
22 |
23 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
24 |
25 | Scope
26 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
27 |
28 | Enforcement
29 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at kevin.kreuzer90@icloud.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
30 |
31 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
32 |
33 | Attribution
34 | This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at http://contributor-covenant.org/version/1/4
35 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 Angular eXtensions
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # svg-icons-builder
2 |
3 |
4 |
5 | [](#contributors-)
6 |
7 |
8 |
9 | The svg-icons-builder is a Angular builder for the [svg-to-ts](https://github.com/kreuzerk/svg-to-ts) project. It can be used to convert SVG icons inside an Angular library or SPA to an object, to constants or even to individual TypeScript or JavaScript files.
10 | Find out more on the official [svg-to-ts docs](https://github.com/kreuzerk/svg-to-ts).
11 |
12 | ## Usage
13 |
14 | ### Installation
15 |
16 | NPM: `npm install @angular-extensions/svg-icons-builder`
17 |
18 | Angular CLI: `ng add @angular-extensions/svg-icons-builder`
19 |
20 | ### Configure the builder
21 |
22 | To use the builder you need to add a new entry to your `architect` object inside your `angular.json`.
23 |
24 | A valid [svg-to-ts configuration](https://github.com/kreuzerk/svg-to-ts). ⚠️ the options depend on the `conversionType` and may therefore vary. Means, a configuration for the `convesionType: "files"` will look different than configuration for the `conversionType: "constants"`. Each `conversionType` has it's own builder.
25 |
26 | In our example we call it `generate-icons`. You then need to specify the following properties:
27 |
28 | ## `conversionType: constants`
29 |
30 | - **Builder**: `"@angular-extensions/svg-icons-builder:svg-icons-constants-builder"`
31 | - **Config**: [svg-to-ts constants config](https://github.com/kreuzerk/svg-to-ts#2-multiple-constants---treeshakable-and-typesafe-with-one-file-conversiontypeconstants)
32 |
33 | ```json
34 | "generate-icons": {
35 | "builder": "@angular-extensions/svg-icons-builder:svg-icons-constants-builder",
36 | "options": {
37 | "conversionType": "constants",
38 | "fileName": "myIcons",
39 | "generateType": false,
40 | "generateTypeObject": false,
41 | "generateCompleteIconSet": true,
42 | "srcFiles": ["./src/icons/*.svg"],
43 | "outputDirectory": "./dist/icons",
44 | "interfaceName": "DinosaurIcon",
45 | "typeName": "dinosaurIcon",
46 | "prefix": "dinosaurIcon",
47 | "svgoConfig": {
48 | "plugins": ["cleanupAttrs"]
49 | }
50 | }
51 | }
52 | ```
53 |
54 | ## `conversionType: files`
55 |
56 | - **Builder**: `"@angular-extensions/svg-icons-builder:svg-icons-files-builder"`
57 | - **Config**: [svg-to-ts files config](https://github.com/kreuzerk/svg-to-ts#3-tree-shakable-and-optimized-for-lazy-loading-conversiontypefiles)
58 |
59 | ```json
60 | "generate-icons": {
61 | "builder": "@angular-extensions/svg-icons-builder:svg-icons-files-builder",
62 | "options": {
63 | "conversionType": "files",
64 | "srcFiles": ["./projects/dinosaur-icons/icons/**/*.svg"],
65 | "outputDirectory": "./dist/dinosaur-icons/icons",
66 | "interfaceName": "DinosaurIcon",
67 | "generateType": false,
68 | "generateTypeObject": false,
69 | "generateCompleteIconSet": false,
70 | "exportCompleteIconSet": false,
71 | "fileName": "dinosaur-icons",
72 | "iconsFolderName": "dinosaur-icons",
73 | "objectName": "dinosaur-icons",
74 | "typeName": "dinosaurIcon",
75 | "prefix": "dinosaurIcon",
76 | "modelFileName": "dinosaur-icons",
77 | "barrelFileName": "index",
78 | "svgoConfig": {
79 | "plugins": ["cleanupAttrs"]
80 | },
81 | "compileSources": true
82 | }
83 | }
84 | ```
85 |
86 | ## `conversionType: object`
87 |
88 | - **Builder**: `"@angular-extensions/svg-icons-builder:svg-icons-object-builder"`
89 | - **Config**: [svg-to-ts object config](https://github.com/kreuzerk/svg-to-ts#1-converting-to-a-single-object-conversiontypeobject)
90 |
91 | ```json
92 | "generate-icons": {
93 | "builder": "@angular-extensions/svg-icons-builder:svg-icons-object-builder",
94 | "options": {
95 | "conversionType": "object",
96 | "srcFiles": ["./projects/dinosaur-icons/icons/**/*.svg"],
97 | "outputDirectory": "./dist/dinosaur-icons/icons",
98 | "fileName": "dinosaur-icons",
99 | "objectName": "dinosaur-icons",
100 | "svgoConfig": {
101 | "plugins": ["cleanupAttrs"]
102 | },
103 | "compileSources": true
104 | }
105 | }
106 | ```
107 |
108 | ### Run the builder
109 |
110 | In order to run the builder you have to add a new npm script to your `package.json`. Replace `name-of-your-app` with the name of your application 😉.
111 |
112 | ```json
113 | "genrate-icons": "ng run name-of-your-app:generate-icons"
114 | ```
115 |
116 | ## Core Team ✨
117 |
118 | Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
119 |
120 |
121 |
122 |
123 |
129 |
130 |
131 |
132 |
133 |
134 |
135 | This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
136 |
--------------------------------------------------------------------------------
/builders.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "./node_modules/@angular-devkit/architect/src/builders-schema.json",
3 | "builders": {
4 | "svg-icons-constants-builder": {
5 | "implementation": "./svg-icons-builder/constants",
6 | "schema": "./svg-icons-builder/schema.json",
7 | "description": "Build SVG icons using `constants` conversion type."
8 | },
9 | "svg-icons-object-builder": {
10 | "implementation": "./svg-icons-builder/object",
11 | "schema": "./svg-icons-builder/schema.json",
12 | "description": "Build SVG icons using `objects` conversion type."
13 | },
14 | "svg-icons-files-builder": {
15 | "implementation": "./svg-icons-builder/files",
16 | "schema": "./svg-icons-builder/schema.json",
17 | "description": "Build SVG icons using `files` conversion type."
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/commitlint.config.js:
--------------------------------------------------------------------------------
1 | module.exports = { extends: ['@commitlint/config-conventional'] };
2 |
--------------------------------------------------------------------------------
/jest.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | globals: {
3 | 'ts-jest': {
4 | tsconfig: 'tsconfig.spec.json',
5 | },
6 | },
7 | roots: ['/schematics', '/svg-icons-builder'],
8 | transform: {
9 | '^.+\\.tsx?$': 'ts-jest',
10 | },
11 | testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
12 | testPathIgnorePatterns: ['/node_modules/', '.*/files/.*.spec.ts'],
13 | moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
14 | };
15 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@angular-extensions/svg-icons-builder",
3 | "version": "11.0.0",
4 | "description": "The svg-icons-builder is a Angular builder for the svg-to-ts project",
5 | "keywords": [
6 | "Angular builder",
7 | "schematics",
8 | "SVG icons"
9 | ],
10 | "homepage": "https://github.com/angular-extensions/svg-icons-builder",
11 | "repository": "https://github.com/angular-extensions/svg-icons-builder",
12 | "bugs": "https://github.com/angular-extensions/svg-icons-builder/issues",
13 | "contributors": [
14 | "Kayla Altepeter",
15 | "Kevin Kreuzer"
16 | ],
17 | "license": "MIT",
18 | "schematics": "./schematics/collection.json",
19 | "ng-add": {
20 | "save": "devDependencies"
21 | },
22 | "builders": "./builders.json",
23 | "scripts": {
24 | "build": "tsc -p tsconfig.json && npm run copy:generate-icon-lib-templates && npm run copy:build-assets",
25 | "build:watch": "tsc -p tsconfig.json --watch && && npm run copy:generate-icon-lib-templates && npm run copy:build-assets",
26 | "bump-version": "rjp package.json version $VERSION",
27 | "copy:build-assets": "copyfiles package.json dist && cp builders.json dist && cp README.md dist",
28 | "copy:generate-icon-lib-templates": "copyfiles schematics/ng-generate-icon-lib/files/**/*.ts dist/schematics/ng-generate-icon-lib/files/_name@dasherize_ -f",
29 | "format:write": "prettier --write ./**/*.ts",
30 | "test": "jest",
31 | "test:watch": "jest --watch"
32 | },
33 | "dependencies": {
34 | "@angular-devkit/core": "13.3.9",
35 | "@angular-devkit/schematics": "13.3.9",
36 | "@schematics/angular": "13.3.11",
37 | "svg-to-ts": "^11.0.0",
38 | "typescript": "4.9.4"
39 | },
40 | "devDependencies": {
41 | "@angular-devkit/architect": "0.1303.9",
42 | "@commitlint/cli": "^17.6.1",
43 | "@commitlint/config-conventional": "^17.6.1",
44 | "@semantic-release/changelog": "^6.0.3",
45 | "@semantic-release/exec": "^6.0.3",
46 | "@semantic-release/git": "^10.0.0",
47 | "@types/jest": "^26.0.15",
48 | "@types/node": "16.11.7",
49 | "all-contributors-cli": "^6.25.0",
50 | "copyfiles": "^2.4.1",
51 | "husky": "^8.0.0",
52 | "jest": "^26.6.1",
53 | "prettier": "^2.8.8",
54 | "pretty-quick": "^3.1.3",
55 | "replace-json-property": "^1.6.3",
56 | "ts-jest": "^26.4.2",
57 | "ts-node": "^10.8.1"
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/schematics/collection.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json",
3 | "schematics": {
4 | "ng-add": {
5 | "description": "Add svg-to-ts to a project",
6 | "factory": "./ng-add/index#ngAdd",
7 | "aliases": ["install"]
8 | },
9 | "ng-generate-icon-lib": {
10 | "description": "Scaffold Angular icon library code in your project",
11 | "factory": "./ng-generate-icon-lib/index#generateIconLibrary",
12 | "schema": "./ng-generate-icon-lib/schema.json"
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/schematics/ng-add/index.spec.ts:
--------------------------------------------------------------------------------
1 | import { Tree } from '@angular-devkit/schematics';
2 | import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing';
3 | import * as path from 'path';
4 |
5 | const collectionPath = path.join(__dirname, '../collection.json');
6 | const runner = new SchematicTestRunner('schematics', collectionPath);
7 |
8 | describe('ng-add', () => {
9 | let appTree: UnitTestTree;
10 |
11 | beforeEach(() => {
12 | appTree = new UnitTestTree(Tree.empty());
13 | appTree.create('/package.json', JSON.stringify({ devDependencies: {} }));
14 | });
15 |
16 | it('should update package.json', async () => {
17 | const tree = await runner.runSchematicAsync('ng-add', { preserveAngularCLILayout: true }, appTree).toPromise();
18 |
19 | const result = JSON.parse(tree.readContent('/package.json')).devDependencies;
20 | expect(result['svg-to-ts']).toBeDefined();
21 | });
22 |
23 | it('should error if no package.json is present', async () => {
24 | appTree.delete('package.json');
25 | try {
26 | await runner.runSchematicAsync('ng-add', { name: 'myApp' }, appTree).toPromise();
27 | fail('should throw');
28 | } catch (e) {
29 | expect(e.message).toContain('Cannot find package.json');
30 | }
31 | });
32 | });
33 |
--------------------------------------------------------------------------------
/schematics/ng-add/index.ts:
--------------------------------------------------------------------------------
1 | import { Rule, SchematicContext, Tree } from '@angular-devkit/schematics';
2 | import { NodePackageInstallTask } from '@angular-devkit/schematics/tasks';
3 |
4 | const svgToTsVersion = '^7.1.0';
5 |
6 | export function ngAdd(_options: any): Rule {
7 | return (tree: Tree, _context: SchematicContext) => {
8 | addPackageToPackageJson(tree, 'svg-to-ts', `${svgToTsVersion}`);
9 | _context.logger.log('info', `Installing added packages...`);
10 | _context.addTask(new NodePackageInstallTask());
11 | return tree;
12 | };
13 | }
14 |
15 | export function addPackageToPackageJson(host: Tree, pkg: string, version: string): Tree {
16 | if (host.exists('package.json')) {
17 | const sourceText = host.read('package.json')!.toString('utf-8');
18 | const json = JSON.parse(sourceText);
19 |
20 | if (!json.devDependencies) {
21 | json.devDependencies = {};
22 | }
23 |
24 | if (!json.devDependencies[pkg]) {
25 | json.devDependencies[pkg] = version;
26 | json.devDependencies = sortObjectByKeys(json.devDependencies);
27 | }
28 |
29 | host.overwrite('package.json', JSON.stringify(json, null, 2));
30 | } else {
31 | throw new Error(`Cannot find package.json`);
32 | }
33 |
34 | return host;
35 | }
36 |
37 | function sortObjectByKeys(obj: any) {
38 | return Object.keys(obj)
39 | .sort()
40 | .reduce((result: any, key) => {
41 | result[key] = obj[key];
42 | return result;
43 | }, {});
44 | }
45 |
--------------------------------------------------------------------------------
/schematics/ng-generate-icon-lib/files/__name@dasherize__/__name@dasherize__-registry.service.spec.ts:
--------------------------------------------------------------------------------
1 | import { <%= capitalize(camelize(name)) %>Registry } from './<%= dasherize(name) %>-registry.service';
2 |
3 | describe('<%= capitalize(camelize(name)) %>Registry', () => {
4 | let sut: <%=capitalize(camelize(name)) %>Registry;
5 |
6 | beforeEach(() => (sut = new <%=capitalize(camelize(name)) %>Registry()));
7 |
8 | it('should add icons to the registry', () => {
9 | const iconName = 'someicon' as any;
10 | const iconData = 'some data' as any;
11 | const someIcon = { name: iconName, data: iconData };
12 |
13 | sut.registerIcons([someIcon]);
14 | expect(sut.getIcon(iconName)).toEqual(iconData);
15 | });
16 |
17 | it('should add multiple icons to the registry', () => {
18 | const iconOneName = 'barIcon' as any;
19 | const iconTwoName = 'fooIcon' as any;
20 | const iconOneData = 'iconOneData';
21 | const iconTwoData = 'iconTwoData';
22 | const iconOne = { name: iconOneName, data: iconOneData };
23 | const iconTwo = { name: iconTwoName, data: iconTwoData };
24 |
25 | sut.registerIcons([iconOne, iconTwo]);
26 | expect(sut.getIcon(iconOneName)).toEqual(iconOneData);
27 | expect(sut.getIcon(iconTwoName)).toEqual(iconTwoData);
28 | });
29 |
30 | it('should print a warning if an icon is not in the registry', () => {
31 | spyOn(console, 'warn');
32 | const iconName = 'someIcon' as any;
33 | sut.getIcon(iconName);
34 | expect(console.warn).toHaveBeenCalledWith(
35 | `👀 we could not find the Icon with the name ${iconName}, did you add it to the Icon registry?`
36 | );
37 | });
38 | });
39 |
--------------------------------------------------------------------------------
/schematics/ng-generate-icon-lib/files/__name@dasherize__/__name@dasherize__-registry.service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@angular/core';
2 |
3 | import { <%= iconType %>, <%= iconInterface %> } from '<%= iconImportPath %>';
4 |
5 | @Injectable({
6 | providedIn: 'any'
7 | })
8 | export class <%= capitalize(camelize(name)) %>Registry {
9 | private registry = new Map<<%= iconType %>, string>();
10 |
11 | public registerIcons(icons: <%= iconInterface %>[]): void {
12 | icons.forEach((icon: any) => this.registry.set(icon.name, icon.data));
13 | }
14 |
15 | public getIcon(iconName: <%= iconType %>): string | undefined {
16 | if (!this.registry.has(iconName)) {
17 | console.warn(
18 | `👀 we could not find the Icon with the name ${iconName}, did you add it to the Icon registry?`
19 | );
20 | }
21 | return this.registry.get(iconName);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/schematics/ng-generate-icon-lib/files/__name@dasherize__/__name@dasherize__.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { <%= capitalize(camelize(name)) %>Component } from './<%= dasherize(name) %>.component';
2 |
3 | describe('<%= capitalize(camelize(name)) %>Component', () => {
4 |
5 | let sut;
6 |
7 | const elementMock = {
8 | nativeElement: {
9 | removeChild: jasmine.createSpy(),
10 | appendChild: jasmine.createSpy()
11 | }
12 | };
13 |
14 | const iconRegistryMock = {
15 | getIcon: jasmine.createSpy()
16 | } as any;
17 |
18 | beforeEach(() => sut = new <%= capitalize(camelize(name)) %>Component(elementMock, iconRegistryMock, document));
19 |
20 | it('should append an SVG element to the ElementRef', () => {
21 | const iconName = 'my-awesome-icon';
22 | const svgData = '';
23 | const div = document.createElement('DIV');
24 | div.innerHTML = svgData;
25 |
26 | iconRegistryMock.getIcon.and.callFake((name) => name === iconName ? svgData : null);
27 |
28 | sut.name = iconName;
29 | expect(elementMock.nativeElement.appendChild).toHaveBeenCalledWith(div.querySelector('svg'));
30 | });
31 |
32 | it('should remove the previous element if we want to append a new one', () => {
33 | const iconName = 'my-awesome-icon';
34 | const svgData = '';
35 | const div = document.createElement('DIV');
36 | div.innerHTML = svgData;
37 |
38 | iconRegistryMock.getIcon.and.callFake((name) => name === iconName ? svgData : null);
39 |
40 | sut.name = iconName;
41 | expect(elementMock.nativeElement.appendChild).toHaveBeenCalledWith(div.querySelector('svg'));
42 |
43 | sut.name = 'anotherIcon';
44 | expect(elementMock.nativeElement.removeChild).toHaveBeenCalled();
45 | });
46 | });
47 |
--------------------------------------------------------------------------------
/schematics/ng-generate-icon-lib/files/__name@dasherize__/__name@dasherize__.component.ts:
--------------------------------------------------------------------------------
1 | import { ChangeDetectionStrategy, Component, ElementRef, Inject, Input, Optional } from '@angular/core';
2 | import { DOCUMENT } from '@angular/common';
3 | import { <%= iconInterface %> } from '<%= iconImportPath %>';
4 |
5 | import { <%= capitalize(camelize(name)) %>Registry } from './<%= dasherize(name) %>-registry.service';
6 |
7 | @Component({
8 | selector: '<%= dasherize(name) %>',
9 | template: `
10 |
11 | `,
12 | styles: [':host::ng-deep svg{width: <%= defaultIconSize %>px; height: <%= defaultIconSize %>px}'],
13 | changeDetection: ChangeDetectionStrategy.OnPush
14 | })
15 | export class <%= capitalize(camelize(name)) %>Component {
16 | private svgIcon: SVGElement;
17 |
18 | @Input()
19 | set name(iconName: <%= iconType %>) {
20 | if (this.svgIcon) {
21 | this.element.nativeElement.removeChild(this.svgIcon);
22 | }
23 | const svgData = this.<%= camelize(name) %>Registry.getIcon(iconName);
24 |
25 | if(svgData) {
26 | this.svgIcon = this.svgElementFromString(svgData);
27 | this.element.nativeElement.appendChild(this.svgIcon);
28 | }
29 | }
30 |
31 | constructor(private element: ElementRef, private <%= camelize(name) %>Registry: <%= capitalize(camelize(name)) %>Registry,
32 | @Optional() @Inject(DOCUMENT) private document: any) {
33 | }
34 |
35 | private svgElementFromString(svgContent: string): SVGElement {
36 | const div = this.document.createElement('DIV');
37 | div.innerHTML = svgContent;
38 | return div.querySelector('svg') || this.document.createElementNS('http://www.w3.org/2000/svg', 'path');
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/schematics/ng-generate-icon-lib/files/__name@dasherize__/__name@dasherize__.module.ts:
--------------------------------------------------------------------------------
1 | import { NgModule } from '@angular/core';
2 | import { CommonModule } from '@angular/common';
3 |
4 | import { <%= capitalize(camelize(name)) %>Component } from './<%= dasherize(name) %>.component';
5 |
6 | @NgModule({
7 | declarations: [<%= capitalize(camelize(name)) %>Component],
8 | exports: [<%= capitalize(camelize(name)) %>Component],
9 | imports: [CommonModule]
10 | })
11 | export class <%= capitalize(camelize(name)) %>Module {}
12 |
--------------------------------------------------------------------------------
/schematics/ng-generate-icon-lib/index.ts:
--------------------------------------------------------------------------------
1 | import {
2 | url,
3 | move,
4 | apply,
5 | chain,
6 | template,
7 | mergeWith,
8 | Tree,
9 | Rule,
10 | SchematicContext,
11 | SchematicsException,
12 | } from '@angular-devkit/schematics';
13 | import { strings } from '@angular-devkit/core';
14 | import { parseName } from '@schematics/angular/utility/parse-name';
15 | import { NodePackageInstallTask } from '@angular-devkit/schematics/tasks';
16 |
17 | // You don't have to export the function as default. You can also have more than one rule factory
18 | // per file.
19 | export function generateIconLibrary(options: any): Rule {
20 | return (tree: Tree, _context: SchematicContext) => {
21 | const workspaceAsBuffer = tree.read('angular.json');
22 | if (!workspaceAsBuffer) {
23 | throw new SchematicsException('Not and Angular CLI workspace');
24 | }
25 |
26 | const workspace = JSON.parse(workspaceAsBuffer.toString());
27 |
28 | const projectName = options.project || workspace.defaultProject;
29 | const project = workspace.projects[projectName];
30 |
31 | if (project.projectType === 'application') {
32 | throw new SchematicsException(
33 | 'The "generateLibrary" schematics works only for the "library" projects, please specify correct project using --project flag'
34 | );
35 | }
36 |
37 | const path = options.path || `${project.sourceRoot}/lib`;
38 | const parsed = parseName(path, options.name);
39 | options.name = parsed.name;
40 | const sourceTemplate = url('./files');
41 |
42 | const sourceTemplateParametrized = apply(sourceTemplate, [
43 | template({
44 | ...options,
45 | ...strings,
46 | }),
47 | move(parsed.path),
48 | ]);
49 |
50 | const rules = [mergeWith(sourceTemplateParametrized)];
51 |
52 | if (options.installLibrary) {
53 | _context.addTask(
54 | new NodePackageInstallTask({
55 | packageName: options.iconImportPath,
56 | })
57 | );
58 | }
59 | return chain(rules);
60 | };
61 | }
62 |
--------------------------------------------------------------------------------
/schematics/ng-generate-icon-lib/schema.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "http://json-schema.org/schema",
3 | "id": "SVGIconsBuilderGenerateIconLib",
4 | "title": "Angular Icon library options Schema",
5 | "type": "object",
6 | "description": "Creates a new icon library module in the given or default project.",
7 |
8 | "properties": {
9 | "name": {
10 | "type": "string",
11 | "description": "The name of the icon library module.",
12 | "x-prompt": "What name would you like to use for your icon module?"
13 | },
14 | "iconType": {
15 | "type": "string",
16 | "description": "The name of the icon type generated by svg-to-ts.",
17 | "x-prompt": "What's the name of the icon type generated by svg-to-ts?",
18 | "default": "any"
19 | },
20 | "iconInterface": {
21 | "type": "string",
22 | "description": "The name of the icon interface generated by svg-to-ts.",
23 | "x-prompt": "What's the name of the icon interface generated by svg-to-ts?"
24 | },
25 | "iconImportPath": {
26 | "type": "string",
27 | "description": "The path where the icon library should be imported from (either relative path or npm package name)",
28 | "x-prompt": "What's the name of the icon library?"
29 | },
30 | "defaultIconSize": {
31 | "type": "string",
32 | "description": "The default size of your icons",
33 | "x-prompt": "What's the default size of your icons (in px)?"
34 | },
35 | "installLibrary": {
36 | "type": "boolean",
37 | "description": "Should we install your icon library from the provided iconImportPath?",
38 | "x-prompt": "Do you want us to automatically install the library from the provided path?",
39 | "default": true
40 | },
41 | "project": {
42 | "type": "string",
43 | "description": "The name of the project.",
44 | "$default": {
45 | "$source": "projectName"
46 | }
47 | },
48 | "path": {
49 | "type": "string",
50 | "format": "path",
51 | "description": "The path at which to create the icon module files, relative to the current workspace.",
52 | "visible": false
53 | }
54 | },
55 | "required": ["name", "iconType", "iconInterface", "iconImportPath", "installLibrary"]
56 | }
57 |
--------------------------------------------------------------------------------
/schematics/ng-generate-icon-lib/schema.model.ts:
--------------------------------------------------------------------------------
1 | export interface Schema {
2 | name: string;
3 | defaultIconSize: number;
4 | iconType: string;
5 | iconInterface: string;
6 | iconImportPath?: string;
7 | installLibrary: boolean;
8 | path?: string;
9 | project?: string;
10 | }
11 |
--------------------------------------------------------------------------------
/svg-icons-builder/constants/index.spec.ts:
--------------------------------------------------------------------------------
1 | import { Architect } from '@angular-devkit/architect';
2 | import { TestingArchitectHost } from '@angular-devkit/architect/testing';
3 | import { logging, schema } from '@angular-devkit/core';
4 | import { ConversionType } from 'svg-to-ts';
5 | import { defaultCommonOptions } from '../test-helpers';
6 | const { join } = require('path');
7 |
8 | describe('svg-icons-builder', () => {
9 | let architect: Architect;
10 | let architectHost: TestingArchitectHost;
11 |
12 | beforeEach(async () => {
13 | const registry = new schema.CoreSchemaRegistry();
14 | registry.addPostTransform(schema.transforms.addUndefinedDefaults);
15 | const workspaceRoot = join(__dirname, '..', '..');
16 |
17 | architectHost = new TestingArchitectHost('/root', '/root');
18 | architect = new Architect(architectHost, registry);
19 |
20 | await architectHost.addBuilderFromPackage(workspaceRoot);
21 | });
22 |
23 | it('generates `constants` for icons', async () => {
24 | const logger = new logging.Logger('');
25 | const logs: string[] = [];
26 | logger.subscribe((ev) => logs.push(ev.message));
27 |
28 | const run = await architect.scheduleBuilder(
29 | '@angular-extensions/svg-icons-builder:svg-icons-constants-builder',
30 | {
31 | ...defaultCommonOptions(),
32 | conversionType: ConversionType.CONSTANTS,
33 | fileName: 'dinosaur-icons',
34 | typeName: 'dinosaurIcon',
35 | generateType: true,
36 | generateTypeObject: true,
37 | generateCompleteIconSet: true,
38 | prefix: 'dinosaurIcon',
39 | interfaceName: 'DinosaurIcon',
40 | },
41 | { logger }
42 | );
43 |
44 | expect(await run.result).toEqual(
45 | expect.objectContaining({
46 | success: true,
47 | })
48 | );
49 |
50 | await run.stop();
51 |
52 | expect(logs).toContain('We are using the conversion type "constants"');
53 | });
54 | });
55 |
--------------------------------------------------------------------------------
/svg-icons-builder/constants/index.ts:
--------------------------------------------------------------------------------
1 | import { BuilderContext, BuilderOutput, createBuilder } from '@angular-devkit/architect';
2 | import { JsonObject } from '@angular-devkit/core';
3 | import { ConstantsConversionOptions, convertToConstants } from 'svg-to-ts';
4 |
5 | interface Options extends ConstantsConversionOptions {
6 | conversionType: string
7 | }
8 |
9 | // Using `Options & JsonObject` instead of extending JsonObject because of optional boolean
10 | export default createBuilder((options: Options, context: BuilderContext) => {
11 | return new Promise(async (resolve, reject) => {
12 | try {
13 | if (options.conversionType !== 'constants') {
14 | reject(new Error(`This builder only supports constants conversionType.`));
15 | }
16 |
17 | context.logger.info('We are using the conversion type "constants"');
18 | await convertToConstants((options as unknown) as ConstantsConversionOptions);
19 |
20 | resolve({ success: true });
21 | context.reportStatus(`Done.`);
22 | } catch (error) {
23 | context.reportStatus(`Error: ${error.message}`);
24 | reject(error);
25 | process.disconnect();
26 | process.exit(1);
27 | }
28 | });
29 | });
30 |
--------------------------------------------------------------------------------
/svg-icons-builder/files/index.spec.ts:
--------------------------------------------------------------------------------
1 | import { Architect } from '@angular-devkit/architect';
2 | import { TestingArchitectHost } from '@angular-devkit/architect/testing';
3 | import { logging, schema } from '@angular-devkit/core';
4 | import { defaultCommonOptions } from '../test-helpers';
5 | const { join } = require('path');
6 |
7 | describe('svg-icons-builder', () => {
8 | let architect: Architect;
9 | let architectHost: TestingArchitectHost;
10 |
11 | beforeEach(async () => {
12 | const registry = new schema.CoreSchemaRegistry();
13 | registry.addPostTransform(schema.transforms.addUndefinedDefaults);
14 | const workspaceRoot = join(__dirname, '..', '..');
15 |
16 | architectHost = new TestingArchitectHost('/root', '/root');
17 | architect = new Architect(architectHost, registry);
18 |
19 | await architectHost.addBuilderFromPackage(workspaceRoot);
20 | console.log('#', Array.from((architectHost as any)._builderMap.keys()));
21 | });
22 |
23 | it('generates `files` for icons', async () => {
24 | const logger = new logging.Logger('');
25 | const logs: string[] = [];
26 | logger.subscribe((ev) => logs.push(ev.message));
27 |
28 | const run = await architect.scheduleBuilder(
29 | '@angular-extensions/svg-icons-builder:svg-icons-files-builder',
30 | {
31 | ...defaultCommonOptions(),
32 | conversionType: 'files',
33 | typeName: 'dinosaurIcon',
34 | generateType: true,
35 | generateTypeObject: true,
36 | exportCompleteIconSet: true,
37 | prefix: 'dinosaurIcon',
38 | interfaceName: 'DinosaurIcon',
39 | modelFileName: 'dinosaur-icons.model',
40 | iconsFolderName: 'build',
41 | compileSources: true,
42 | barrelFileName: 'index',
43 | },
44 | { logger }
45 | );
46 |
47 | expect(await run.result).toEqual(
48 | expect.objectContaining({
49 | success: true,
50 | })
51 | );
52 |
53 | await run.stop();
54 |
55 | expect(logs).toContain('We are using the conversion type "files"');
56 | });
57 | });
58 |
--------------------------------------------------------------------------------
/svg-icons-builder/files/index.ts:
--------------------------------------------------------------------------------
1 | import { BuilderContext, BuilderOutput, createBuilder } from '@angular-devkit/architect';
2 | import { JsonObject } from '@angular-devkit/core';
3 | import { FilesConversionOptions, convertToFiles } from 'svg-to-ts';
4 |
5 | interface Options extends FilesConversionOptions {
6 | conversionType: string
7 | }
8 |
9 | // Using `Options & JsonObject` instead of extending JsonObject because of optional boolean
10 | export default createBuilder((options: Options, context: BuilderContext) => {
11 | return new Promise(async (resolve, reject) => {
12 | try {
13 | if (options.conversionType !== 'files') {
14 | reject(new Error(`This builder only supports files conversionType.`));
15 | }
16 |
17 | context.logger.info('We are using the conversion type "files"');
18 | await convertToFiles((options as unknown) as FilesConversionOptions);
19 |
20 | resolve({ success: true });
21 | context.reportStatus(`Done.`);
22 | } catch (error) {
23 | context.reportStatus(`Error: ${error.message}`);
24 | reject(error);
25 | process.disconnect();
26 | process.exit(1);
27 | }
28 | });
29 | });
30 |
--------------------------------------------------------------------------------
/svg-icons-builder/object/index.spec.ts:
--------------------------------------------------------------------------------
1 | import { Architect } from '@angular-devkit/architect';
2 | import { TestingArchitectHost } from '@angular-devkit/architect/testing';
3 | import { logging, schema } from '@angular-devkit/core';
4 | import { defaultCommonOptions } from '../test-helpers';
5 | const { join } = require('path');
6 |
7 | describe('svg-icons-builder', () => {
8 | let architect: Architect;
9 | let architectHost: TestingArchitectHost;
10 |
11 | beforeEach(async () => {
12 | const registry = new schema.CoreSchemaRegistry();
13 | registry.addPostTransform(schema.transforms.addUndefinedDefaults);
14 | const workspaceRoot = join(__dirname, '..', '..');
15 |
16 | // TestingArchitectHost() takes workspace and current directories.
17 | // Since we don't use those, both are the same in this case.
18 | architectHost = new TestingArchitectHost('/root', '/root');
19 | architect = new Architect(architectHost, registry);
20 |
21 | // This will either take a Node package name, or a path to the directory
22 | // for the package.json file.
23 | await architectHost.addBuilderFromPackage(workspaceRoot);
24 | console.log('#', Array.from((architectHost as any)._builderMap.keys()));
25 | });
26 |
27 | it('generates `object` for icons', async () => {
28 | const logger = new logging.Logger('');
29 | const logs: string[] = [];
30 | logger.subscribe((ev) => logs.push(ev.message));
31 |
32 | // A "run" can have multiple outputs, and contains progress information.
33 | const run = await architect.scheduleBuilder(
34 | '@angular-extensions/svg-icons-builder:svg-icons-object-builder',
35 | {
36 | ...defaultCommonOptions(),
37 | conversionType: 'object',
38 | fileName: 'dinosaur-icons',
39 | objectName: 'dinosaurIcons',
40 | },
41 | { logger }
42 | ); // We pass the logger for checking later.
43 |
44 | // The "result" member (of type BuilderOutput) is the next output.
45 | expect(await run.result).toEqual(
46 | expect.objectContaining({
47 | success: true,
48 | })
49 | );
50 |
51 | await run.stop();
52 |
53 | expect(logs).toContain('We are using the conversion type "object"');
54 | });
55 | });
56 |
--------------------------------------------------------------------------------
/svg-icons-builder/object/index.ts:
--------------------------------------------------------------------------------
1 | import { BuilderContext, BuilderOutput, createBuilder } from '@angular-devkit/architect';
2 | import { ObjectConversionOptions, convertToSingleObject } from 'svg-to-ts';
3 |
4 | interface Options extends ObjectConversionOptions {
5 | conversionType: string
6 | }
7 |
8 | export default createBuilder((options: Options, context: BuilderContext) => {
9 | return new Promise(async (resolve, reject) => {
10 | try {
11 | if (options.conversionType !== 'object') {
12 | reject(new Error(`This builder only supports object conversionType.`));
13 | }
14 |
15 | if (options.conversionType === 'object') {
16 | context.logger.info('We are using the conversion type "object"');
17 | await convertToSingleObject(options);
18 | }
19 |
20 | resolve({ success: true });
21 | context.reportStatus(`Done.`);
22 | } catch (error) {
23 | context.reportStatus('Error');
24 | process.disconnect();
25 | process.exit(1);
26 | }
27 | });
28 | });
29 |
--------------------------------------------------------------------------------
/svg-icons-builder/schema.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "http://json-schema.org/schema",
3 | "type": "object",
4 | "title": "SvgToTsBuilder",
5 | "description": "The svg-icons-builder is a Angular builder for the svg-to-ts project. It can be used to convert SVG icons inside an Angular library or SPA to an object, to constants or even to individual TypeScript or JavaScript files",
6 | "properties": {
7 | "conversionType": {
8 | "type": "string",
9 | "description": "Converting your icons to a single object, converting your icons to constants or converting your icons to single files.",
10 | "default": "constants",
11 | "enum": [
12 | "object",
13 | "constants",
14 | "files"
15 | ]
16 | }
17 | },
18 | "allOf": [
19 | {
20 | "if": {
21 | "properties": {
22 | "conversionType": {
23 | "const": "constants"
24 | }
25 | }
26 | },
27 | "then": {
28 | "allOf": [
29 | {
30 | "$ref": "#/definitions/baseOptions"
31 | },
32 | {
33 | "properties": {
34 | "fileName": {
35 | "type": "string",
36 | "description": "File name of the generated constants file.",
37 | "default": "my-icons"
38 | },
39 | "typeName": {
40 | "type": "string",
41 | "description": "Name of the generated type.",
42 | "default": "myIcons"
43 | },
44 | "generateType": {
45 | "type": "boolean",
46 | "description": "Prevent generating enumeration type.",
47 | "default": false
48 | },
49 | "generateTypeObject": {
50 | "type": "boolean",
51 | "description": "Generate type object.",
52 | "default": false
53 | },
54 | "exportCompleteIconSet": {
55 | "type": "boolean",
56 | "description": "Specifies if the complete icon set should be exported or not (can be very handy for showcases)",
57 | "default": false
58 | },
59 | "prefix": {
60 | "type": "string",
61 | "description": "Prefix for the generated svg constants.",
62 | "default": "myIcon"
63 | },
64 | "interfaceName": {
65 | "type": "string",
66 | "description": "Name for the generated interface.",
67 | "default": "MyIcon"
68 | }
69 | },
70 | "required": [
71 | "fileName",
72 | "typeName",
73 | "generateType",
74 | "generateTypeObject",
75 | "prefix",
76 | "interfaceName"
77 | ]
78 | }
79 | ]
80 | }
81 | },
82 | {
83 | "if": {
84 | "properties": {
85 | "conversionType": {
86 | "const": "object"
87 | }
88 | }
89 | },
90 | "then": {
91 | "allOf": [
92 | {
93 | "$ref": "#/definitions/baseOptions"
94 | },
95 | {
96 | "properties": {
97 | "fileName": {
98 | "type": "string",
99 | "description": "File name of the generated constants file.",
100 | "default": "my-icons"
101 | },
102 | "objectName": {
103 | "type": "string",
104 | "description": "Name of the exported const - if nothing is set - default export will be used.",
105 | "default": "icons"
106 | }
107 | },
108 | "required": [
109 | "fileName",
110 | "objectName"
111 | ]
112 | }
113 | ]
114 | }
115 | },
116 | {
117 | "if": {
118 | "properties": {
119 | "conversionType": {
120 | "const": "files"
121 | }
122 | }
123 | },
124 | "then": {
125 | "allOf": [
126 | {
127 | "$ref": "#/definitions/baseOptions"
128 | },
129 | {
130 | "properties": {
131 | "typeName": {
132 | "type": "string",
133 | "description": "Name of the generated type.",
134 | "default": "myIcons"
135 | },
136 | "generateType": {
137 | "type": "boolean",
138 | "description": "Prevent generating enumeration type.",
139 | "default": false
140 | },
141 | "generateTypeObject": {
142 | "type": "boolean",
143 | "description": "Generate type object.",
144 | "default": false
145 | },
146 | "exportCompleteIconSet": {
147 | "type": "boolean",
148 | "description": "Specifies if the complete icon set should be exported or not (can be very handy for showcases)",
149 | "default": false
150 | },
151 | "prefix": {
152 | "type": "string",
153 | "description": "Prefix for the generated svg constants.",
154 | "default": "myIcon"
155 | },
156 | "interfaceName": {
157 | "type": "string",
158 | "description": "Name for the generated interface.",
159 | "default": "MyIcon"
160 | },
161 | "modelFileName": {
162 | "type": "string",
163 | "description": "File name of the generated file.",
164 | "default": "my-icons.model"
165 | },
166 | "additionalModelOutputPath": {
167 | "type": "string",
168 | "description": "If a path is specified we will generate an additional file containing interface and type to this path - can be useful to improve type safety"
169 | },
170 | "iconsFolderName": {
171 | "type": "string",
172 | "description": "Name of the folder we will build the TypeScript files to",
173 | "default": "build"
174 | },
175 | "compileSources": {
176 | "type": "boolean",
177 | "description": "If set to false, we generate a TypeScript file for each SVG. If set to true we will allready compile those TypeScript files and generate JavaScript files and declaration files.",
178 | "default": false
179 | },
180 | "barrelFileName": {
181 | "type": "string",
182 | "description": "Name of the generated type",
183 | "default": "index"
184 | }
185 | },
186 | "required": [
187 | "typeName",
188 | "generateType",
189 | "generateTypeObject",
190 | "exportCompleteIconSet",
191 | "prefix",
192 | "interfaceName",
193 | "modelFileName",
194 | "iconsFolderName",
195 | "compileSources",
196 | "barrelFileName"
197 | ]
198 | }
199 | ]
200 | }
201 | }
202 | ],
203 | "required": [
204 | "conversionType"
205 | ],
206 | "definitions": {
207 | "baseOptions": {
208 | "type": "object",
209 | "properties": {
210 | "srcFiles": {
211 | "type": "array",
212 | "description": "Input files matching the given filename pattern.",
213 | "items": [
214 | {
215 | "type": "string"
216 | }
217 | ],
218 | "default": "['*.svg']"
219 | },
220 | "outputDirectory": {
221 | "type": "string",
222 | "description": "Name of the output directory.",
223 | "default": "\"./dist\""
224 | },
225 | "svgoConfig": {
226 | "type": "object",
227 | "description": "A path to your svgoConfiguration JSON file or an inline configuration object."
228 | },
229 | "delimiter": {
230 | "type": "string",
231 | "description": "Delimiter which is used to generate the types and name properties.",
232 | "default": "SNAKE",
233 | "enum": [
234 | "CAMEL",
235 | "KEBAB",
236 | "SNAKE",
237 | "UPPER"
238 | ]
239 | },
240 | "verbose": {
241 | "type": "boolean",
242 | "default": "false",
243 | "description": "Defines if the log should contain additional information. Can be useful for debugging."
244 | }
245 | }
246 | }
247 | }
248 | }
--------------------------------------------------------------------------------
/svg-icons-builder/test-helpers.ts:
--------------------------------------------------------------------------------
1 | import { Delimiter } from 'svg-to-ts/src/lib/generators/code-snippet-generators';
2 |
3 | export const defaultCommonOptions = () => ({
4 | srcFiles: ['./dinosaur-icons/icons/**/*.svg'],
5 | outputDirectory: './dist/test/dinosaur-icons',
6 | delimiter: Delimiter.CAMEL,
7 | verbose: false,
8 | svgoConfig: {
9 | plugins: ['cleanupAttrs'],
10 | },
11 | });
12 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "baseUrl": ".",
4 | "lib": ["es2018", "dom"],
5 | "declaration": true,
6 | "module": "commonjs",
7 | "moduleResolution": "node",
8 | "noEmitOnError": true,
9 | "noFallthroughCasesInSwitch": true,
10 | "noImplicitAny": true,
11 | "noImplicitThis": true,
12 | "noUnusedParameters": true,
13 | "noUnusedLocals": true,
14 | "outDir": "dist",
15 | "resolveJsonModule": true,
16 | "skipDefaultLibCheck": true,
17 | "skipLibCheck": true,
18 | "sourceMap": true,
19 | "strictNullChecks": true,
20 | "target": "es6",
21 | "types": ["node"]
22 | },
23 | "include": ["schematics/**/*", "schematics/**/*.json", "svg-icons-builder", "svg-icons-builder/**/*.json"],
24 | "exclude": ["svg-icons-builder/*/files/**/*", "schematics/*/files/**/*", "**/*.spec.ts"]
25 | }
26 |
--------------------------------------------------------------------------------
/tsconfig.spec.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "./tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "./out-tsc/spec",
5 | "types": ["jest", "node"]
6 | },
7 | "include": ["**/*.spec.ts", "schematics/**/*.d.ts", "svg-icons-builder/**/*.d.ts"]
8 | }
9 |
--------------------------------------------------------------------------------