├── .editorconfig ├── .eslintignore ├── .eslintrc.js ├── .gitattributes ├── .github ├── CONTRIBUTING.md ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ ├── ci-cd.yml │ ├── commitlint.yml │ └── signature-assistant.yml ├── .gitignore ├── .husky ├── .gitattributes └── commit-msg ├── .npmignore ├── .nvmrc ├── CHANGELOG.md ├── LICENSE ├── README.md ├── TRADEMARK ├── commitlint.config.js ├── package-lock.json ├── package.json ├── release.config.js ├── renovate.json5 ├── src ├── bitmap-adapter.js ├── fixup-svg-string.js ├── font-converter.js ├── font-inliner.js ├── index.js ├── load-svg-string.js ├── playground │ └── index.html ├── sanitize-svg.js ├── serialize-svg-to-string.js ├── svg-element.js ├── svg-renderer.js ├── transform-applier.js └── util │ └── log.js ├── test ├── bitmapAdapter_getResized.js ├── fixtures │ ├── css-import.sanitized.svg │ ├── css-import.svg │ ├── embedded-cat-foo.sanitized.svg │ ├── embedded-cat-foo.svg │ ├── embedded-cat-xlink.svg │ ├── hearts.svg │ ├── invalid-cloud.svg │ ├── metadata-body.svg │ ├── metadata-onload.sanitized.svg │ ├── metadata-onload.svg │ ├── onload-script.svg │ ├── red-and-white-carousel-pound-in-href.sanitized.svg │ ├── red-and-white-carousel-pound-in-href.svg │ ├── reserved-namespace.sanitized.svg │ ├── reserved-namespace.svg │ ├── scratch_cat_bitmap_within_svg.sanitized.svg │ ├── scratch_cat_bitmap_within_svg.svg │ ├── script.sanitized.svg │ ├── script.svg │ └── svg-tag-prefixes.svg ├── fixup-svg-string.js ├── sanitize-svg.js ├── test-output │ └── transform-applier-test.html └── transform-applier.js └── webpack.config.js /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | charset = utf-8 7 | indent_size = 4 8 | trim_trailing_whitespace = true 9 | 10 | [*.{js}] 11 | indent_style = space 12 | 13 | [*.{json,json5}] 14 | indent_style = space 15 | indent_size = 2 16 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | dist/* 2 | node_modules/* 3 | playground/* 4 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: ['scratch', 'scratch/es6', 'scratch/node'], 3 | globals: { 4 | document: true, 5 | window: true, 6 | DOMParser: true, 7 | Image: true, 8 | XMLSerializer: true 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Set the default behavior, in case people don't have core.autocrlf set. 2 | * text=auto 3 | 4 | # Explicitly specify line endings for as many files as possible. 5 | # People who (for example) rsync between Windows and Linux need this. 6 | 7 | # File types which we know are binary 8 | *.sb2 binary 9 | 10 | # Prefer LF for most file types 11 | *.css text eol=lf 12 | *.frag text eol=lf 13 | *.htm text eol=lf 14 | *.html text eol=lf 15 | *.iml text eol=lf 16 | *.js text eol=lf 17 | *.js.map text eol=lf 18 | *.json text eol=lf 19 | *.json5 text eol=lf 20 | *.md text eol=lf 21 | *.vert text eol=lf 22 | *.xml text eol=lf 23 | *.yml text eol=lf 24 | 25 | # Prefer LF for these files 26 | .editorconfig text eol=lf 27 | .eslintignore text eol=lf 28 | .eslintrc text eol=lf 29 | .gitattributes text eol=lf 30 | .gitignore text eol=lf 31 | .gitmodules text eol=lf 32 | .npmignore text eol=lf 33 | LICENSE text eol=lf 34 | Makefile text eol=lf 35 | README text eol=lf 36 | TRADEMARK text eol=lf 37 | 38 | # Use CRLF for Windows-specific file types 39 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Contributing 2 | The development of Scratch is an ongoing process, and we love to have people in the Scratch and open source communities help us along the way. 3 | 4 | ### Ways to Help 5 | 6 | * **Documenting bugs** 7 | * If you've identified a bug in Scratch you should first check to see if it's been filed as an issue, if not you can file one. Make sure you follow the issue template. 8 | * It's important that we can consistently reproduce issues. When writing an issue, be sure to follow our [reproduction step guidelines](https://github.com/LLK/scratch-gui/wiki/Writing-good-repro-steps). 9 | * Some issues are marked "Needs Repro". Adding a comment with good reproduction steps to those issues is a great way to help. 10 | * If you don't have an issue in mind already, you can look through the [Bugs & Glitches forum.](https://scratch.mit.edu/discuss/3/) Look for users reporting problems, reproduce the problem yourself, and file new issues following our guidelines. 11 | 12 | * **Fixing bugs** 13 | * You can request to fix a bug in a comment on the issue if you at mention the repo coordinator, who for this repo is @fsih. 14 | * If the issue is marked "Help Wanted" you can go ahead and start working on it! 15 | * **We will only accept Pull Requests for bugs that have an issue filed that has a priority label** 16 | * If you're interested in fixing a bug with no issue, file the issue first and wait for it to have a priority added to it. 17 | 18 | * We are not looking for Pull Requests ("PR") for every issue and may deny a PR if it doesn't fit our criteria. 19 | * We are far more likely to accept a PR if it is for an issue marked with Help Wanted. 20 | * We will not accept PRs for issues marked with "Needs Discussion" or "Needs Design." 21 | * Wait until the Repo Coordinator assigns the issue to you before you begin work or submit a PR. 22 | 23 | ### Learning Git and Github 24 | 25 | If you want to work on fixing issues, you should be familiar with Git and Github. 26 | 27 | * [Learn Git branching](https://learngitbranching.js.org/) includes an introduction to basic git commands and useful branching features. 28 | * Here's a general introduction to [contributing to an open source project](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github). 29 | 30 | **Important:** we follow the [Github Flow process](https://guides.github.com/introduction/flow/) as our development process. 31 | 32 | ### How to Fix Bugs 33 | 1. Identify which Github issue you are working on. Leave a comment on the issue to let us (and other contributors) know you're working on it. 34 | 2. Make sure you have a fork of this repo (see [Github's forking a repo](https://help.github.com/en/github/getting-started-with-github/fork-a-repo) for details) 35 | 3. Switch to the `develop` branch, and pull down the latest changes from upstream 36 | 4. Run the code, and reproduce the problem 37 | 5. Create your branch from the `develop` branch 38 | 6. Make code changes to fix the problem 39 | 7. Run `npm test` to make sure that your changes pass our tests 40 | 8. Commit your changes 41 | 9. Push your branch to your fork 42 | 10. Create your pull request 43 | 1. Make sure to follow the template in the PR description 44 | 1. Remember to check the “[Allow edits from maintainers](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/allowing-changes-to-a-pull-request-branch-created-from-a-fork)” box 45 | 46 | When submitting pull requests keep in mind: 47 | * please be patient -- it can take a while to find time to review them 48 | * try to change the least amount of code necessary to fix the bug 49 | * the code can't be radically changed without significant coordination with the Scratch Team, so these types of changes should be avoided 50 | * if you find yourself changing a substantial amount of code or considering radical changes, please ask for clarification -- we may have envisioned a different approach, or underestimated the amount of effort 51 | 52 | ### Suggestions 53 | ![Block sketch](https://user-images.githubusercontent.com/3431616/77192550-1dcebe00-6ab3-11ea-9606-8ecd8500c958.png) 54 | 55 | Please note: **_we are unlikely to accept PRs with new features that haven't been thought through and discussed as a group_**. 56 | 57 | Why? Because we have a strong belief in the value of keeping things simple for new users. It's been said that the Scratch Team spends about one hour of design discussion for every pixel in Scratch. To learn more about our design philosophy, see [the Scratch Developers page](https://scratch.mit.edu/developers), or [this paper](http://web.media.mit.edu/~mres/papers/Scratch-CACM-final.pdf). 58 | 59 | We welcome suggestions! If you want to suggest a feature, please post in our [suggestions forum](https://scratch.mit.edu/discuss/1/). Your suggestion will be helped if you include a mockup design; this can be simple, even hand-drawn. 60 | 61 | ### Other resources 62 | Beyond this repo, there are also some other resources that you might want to take a look at: 63 | * [Community Guidelines](https://github.com/LLK/scratch-www/wiki/Community-Guidelines) (we find it important to maintain a constructive and welcoming community, just like on Scratch) 64 | * [Open Source forum](https://scratch.mit.edu/discuss/49/) on Scratch 65 | * [Suggestions forum](https://scratch.mit.edu/discuss/1/) on Scratch 66 | * [Bugs & Glitches forum](https://scratch.mit.edu/discuss/3/) on Scratch 67 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### Expected Behavior 2 | 3 | _Please describe what should happen_ 4 | 5 | ### Actual Behavior 6 | 7 | _Describe what actually happens_ 8 | 9 | ### Steps to Reproduce 10 | 11 | _Explain what someone needs to do in order to see what's described in *Actual behavior* above_ 12 | 13 | ### Operating System and Browser 14 | 15 | _e.g. Mac OS 10.11.6 Safari 10.0_ 16 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### Resolves 2 | 3 | _What Github issue does this resolve (please include link)?_ 4 | 5 | ### Proposed Changes 6 | 7 | _Describe what this Pull Request does_ 8 | 9 | ### Reason for Changes 10 | 11 | _Explain why these changes should be made_ 12 | 13 | ### Test Coverage 14 | 15 | _Please show how you have added tests to cover your changes_ 16 | -------------------------------------------------------------------------------- /.github/workflows/ci-cd.yml: -------------------------------------------------------------------------------- 1 | name: CI/CD 2 | 3 | on: 4 | workflow_dispatch: # Allows you to run this workflow manually from the Actions tab 5 | pull_request: # Runs whenever a pull request is created or updated 6 | push: # Runs whenever a commit is pushed to the repository 7 | branches: [master, develop, hotfix/*] 8 | 9 | concurrency: 10 | group: "${{ github.workflow }} @ ${{ github.event.pull_request.head.label || github.head_ref || github.ref }}" 11 | cancel-in-progress: true 12 | 13 | permissions: 14 | contents: write # publish a GitHub release 15 | pages: write # deploy to GitHub Pages 16 | issues: write # comment on released issues 17 | pull-requests: write # comment on released pull requests 18 | 19 | jobs: 20 | ci-cd: 21 | runs-on: ubuntu-latest 22 | env: 23 | TRIGGER_DEPLOY: ${{ startsWith(github.ref, 'refs/heads/master') || startsWith(github.ref, 'refs/heads/hotfix') || startsWith(github.ref, 'refs/heads/develop') }} 24 | steps: 25 | - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4 26 | - uses: wagoid/commitlint-github-action@5ce82f5d814d4010519d15f0552aec4f17a1e1fe # v5 27 | if: github.event_name == 'pull_request' 28 | - uses: actions/setup-node@26961cf329f22f6837d5f54c3efd76b480300ace # v4 29 | with: 30 | cache: "npm" 31 | node-version-file: ".nvmrc" 32 | 33 | - name: Info 34 | run: | 35 | cat < 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # scratch-svg-renderer 2 | 3 | [![CI/CD](https://github.com/scratchfoundation/scratch-svg-renderer/actions/workflows/ci-cd.yml/badge.svg)](https://github.com/scratchfoundation/scratch-svg-renderer/actions/workflows/ci-cd.yml) 4 | 5 | A class built for importing SVGs into [Scratch](https://github.com/scratchfoundation/scratch-gui). Imports an SVG 6 | string to a DOM element or an HTML canvas. Handles some of the quirks with Scratch 2.0 SVGs, which sometimes misreport 7 | their width, height and view box. 8 | 9 | ## Installation 10 | 11 | This requires you to have Git and Node.js installed. 12 | 13 | To install as a dependency for your own application: 14 | 15 | ```bash 16 | npm install scratch-svg-renderer 17 | ``` 18 | 19 | To set up a development environment to edit scratch-svg-renderer yourself: 20 | 21 | ```bash 22 | git clone https://github.com/scratchfoundation/scratch-svg-renderer.git 23 | cd scratch-svg-renderer 24 | npm install 25 | ``` 26 | 27 | ## How to include in a Node.js App 28 | 29 | ```js 30 | import SvgRenderer from 'scratch-svg-renderer'; 31 | 32 | const svgRenderer = new SvgRenderer(); 33 | 34 | const svgData = "..."; 35 | const scale = 1; 36 | const quirksMode = false; // If true, emulate Scratch 2.0 SVG rendering "quirks" 37 | function doSomethingWith(canvas) {...}; 38 | 39 | svgRenderer.loadSVG(svgData, quirksMode, () => { 40 | svgRenderer.draw(scale); 41 | doSomethingWith(svgRenderer.canvas); 42 | }); 43 | ``` 44 | 45 | ## How to run locally as part of scratch-gui 46 | 47 | To run scratch-svg-renderer locally as part of scratch-gui, for development: 48 | 49 | 1. Set up local repositories (or pull updated code): 50 | 1. scratch-svg-renderer (this repo) 51 | 2. [scratch-render](https://github.com/scratchfoundation/scratch-render) 52 | 3. [scratch-paint](https://github.com/scratchfoundation/scratch-paint) 53 | 4. [scratch-gui](https://github.com/scratchfoundation/scratch-gui) 54 | 2. In each of the local repos above, run `npm install` 55 | 3. Run `npm link` in each of these local repos: 56 | 1. scratch-svg-renderer 57 | 2. scratch-render 58 | 3. scratch-paint 59 | 4. Run `npm link scratch-svg-renderer` in each of these local repos: 60 | 1. scratch-render 61 | 2. scratch-paint 62 | 3. scratch-gui 63 | 5. In your local scratch-gui repo: 64 | 1. run `npm link scratch-render` 65 | 2. run `npm link scratch-paint` 66 | 6. In scratch-gui, follow its instructions to run it or build its code 67 | 68 | ## Donate 69 | 70 | We provide [Scratch](https://scratch.mit.edu) free of charge, and want to keep it that way! Please consider making a 71 | [donation](https://secure.donationpay.org/scratchfoundation/) to support our continued engineering, design, community, 72 | and resource development efforts. Donations of any size are appreciated. Thank you! 73 | 74 | ## Committing 75 | 76 | This project uses [semantic release](https://github.com/semantic-release/semantic-release) to ensure version bumps 77 | follow semver so that projects depending on it don't break unexpectedly. 78 | 79 | In order to automatically determine version updates, semantic release expects commit messages to follow the 80 | [conventional-changelog](https://github.com/bcoe/conventional-changelog-standard/blob/master/convention.md) 81 | specification. 82 | 83 | You can use the [commitizen CLI](https://github.com/commitizen/cz-cli) to make commits formatted in this way: 84 | 85 | ```bash 86 | npm install -g commitizen@latest cz-conventional-changelog@latest 87 | ``` 88 | 89 | Now you're ready to make commits using `git cz`. 90 | -------------------------------------------------------------------------------- /TRADEMARK: -------------------------------------------------------------------------------- 1 | The Scratch trademarks, including the Scratch name, logo, the Scratch Cat, Gobo, Pico, Nano, Tera and Giga graphics (the "Marks"), are property of the Massachusetts Institute of Technology (MIT). Marks may not be used to endorse or promote products derived from this software without specific prior written permission. 2 | -------------------------------------------------------------------------------- /commitlint.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: ['@commitlint/config-conventional'], 3 | ignores: [message => message.startsWith('chore(release):')] 4 | }; 5 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "scratch-svg-renderer", 3 | "version": "3.0.125", 4 | "description": "SVG renderer for Scratch", 5 | "main": "./dist/node/scratch-svg-renderer.js", 6 | "browser": "./dist/web/scratch-svg-renderer.js", 7 | "exports": { 8 | "webpack": "./src/index.js", 9 | "browser": "./dist/web/scratch-svg-renderer.js", 10 | "node": "./dist/node/scratch-svg-renderer.js", 11 | "default": "./src/index.js" 12 | }, 13 | "scripts": { 14 | "build": "npm run clean && webpack", 15 | "clean": "rimraf ./dist", 16 | "prepare": "husky install", 17 | "start": "webpack-dev-server", 18 | "test": "npm run test:lint && npm run test:unit", 19 | "test:lint": "eslint . --ext .js", 20 | "test:unit": "tap ./test/*.js", 21 | "watch": "webpack --watch" 22 | }, 23 | "author": "Massachusetts Institute of Technology", 24 | "license": "AGPL-3.0-only", 25 | "homepage": "https://github.com/scratchfoundation/scratch-svg-renderer#readme", 26 | "repository": { 27 | "type": "git", 28 | "url": "https://github.com/scratchfoundation/scratch-svg-renderer.git" 29 | }, 30 | "peerDependencies": { 31 | "scratch-render-fonts": "^1.0.0" 32 | }, 33 | "dependencies": { 34 | "base64-js": "^1.2.1", 35 | "base64-loader": "^1.0.0", 36 | "css-tree": "^1.1.3", 37 | "fastestsmallesttextencoderdecoder": "^1.0.22", 38 | "isomorphic-dompurify": "^2.4.0", 39 | "minilog": "^3.1.0", 40 | "transformation-matrix": "^1.15.0" 41 | }, 42 | "devDependencies": { 43 | "@babel/core": "7.27.3", 44 | "@babel/eslint-parser": "7.27.1", 45 | "@babel/preset-env": "7.27.2", 46 | "@commitlint/cli": "18.6.1", 47 | "@commitlint/config-conventional": "18.6.3", 48 | "babel-loader": "9.2.1", 49 | "copy-webpack-plugin": "4.6.0", 50 | "eslint": "8.57.1", 51 | "eslint-config-scratch": "9.0.9", 52 | "eslint-plugin-import": "2.31.0", 53 | "husky": "8.0.3", 54 | "jsdom": "13.2.0", 55 | "json": "9.0.6", 56 | "mkdirp": "2.1.6", 57 | "rimraf": "3.0.2", 58 | "scratch-render-fonts": "1.0.198", 59 | "scratch-semantic-release-config": "3.0.0", 60 | "scratch-webpack-configuration": "3.0.0", 61 | "semantic-release": "19.0.5", 62 | "tap": "11.1.5", 63 | "webpack": "5.99.9", 64 | "webpack-cli": "5.1.4", 65 | "webpack-dev-server": "3.11.3", 66 | "xmldom": "0.1.31" 67 | }, 68 | "browserslist": [ 69 | "Chrome >= 63", 70 | "Edge >= 15", 71 | "Firefox >= 57", 72 | "Safari >= 11" 73 | ], 74 | "config": { 75 | "commitizen": { 76 | "path": "cz-conventional-changelog" 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /release.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: 'scratch-semantic-release-config', 3 | branches: [ 4 | { 5 | name: 'develop' 6 | // default channel 7 | }, 8 | { 9 | name: 'hotfix/*', 10 | channel: 'hotfix', 11 | prerelease: 'hotfix' 12 | } 13 | ] 14 | }; 15 | -------------------------------------------------------------------------------- /renovate.json5: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | 4 | "extends": [ 5 | "github>scratchfoundation/scratch-renovate-config:js-lib-bundled" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /src/bitmap-adapter.js: -------------------------------------------------------------------------------- 1 | const base64js = require('base64-js'); 2 | 3 | /** 4 | * Adapts Scratch 2.0 bitmaps for use in scratch 3.0 5 | */ 6 | class BitmapAdapter { 7 | /** 8 | * @param {?function} makeImage HTML image constructor. Tests can provide this. 9 | * @param {?function} makeCanvas HTML canvas constructor. Tests can provide this. 10 | */ 11 | constructor (makeImage, makeCanvas) { 12 | this._makeImage = makeImage ? makeImage : () => new Image(); 13 | this._makeCanvas = makeCanvas ? makeCanvas : () => document.createElement('canvas'); 14 | } 15 | 16 | /** 17 | * Return a canvas with the resized version of the given image, done using nearest-neighbor interpolation 18 | * @param {CanvasImageSource} image The image to resize 19 | * @param {int} newWidth The desired post-resize width of the image 20 | * @param {int} newHeight The desired post-resize height of the image 21 | * @returns {HTMLCanvasElement} A canvas with the resized image drawn on it. 22 | */ 23 | resize (image, newWidth, newHeight) { 24 | // We want to always resize using nearest-neighbor interpolation. However, canvas implementations are free to 25 | // use linear interpolation (or other "smooth" interpolation methods) when downscaling: 26 | // https://bugzilla.mozilla.org/show_bug.cgi?id=1360415 27 | // It seems we can get around this by resizing in two steps: first width, then height. This will always result 28 | // in nearest-neighbor interpolation, even when downscaling. 29 | const stretchWidthCanvas = this._makeCanvas(); 30 | stretchWidthCanvas.width = newWidth; 31 | stretchWidthCanvas.height = image.height; 32 | let context = stretchWidthCanvas.getContext('2d'); 33 | context.imageSmoothingEnabled = false; 34 | context.drawImage(image, 0, 0, stretchWidthCanvas.width, stretchWidthCanvas.height); 35 | const stretchHeightCanvas = this._makeCanvas(); 36 | stretchHeightCanvas.width = newWidth; 37 | stretchHeightCanvas.height = newHeight; 38 | context = stretchHeightCanvas.getContext('2d'); 39 | context.imageSmoothingEnabled = false; 40 | context.drawImage(stretchWidthCanvas, 0, 0, stretchHeightCanvas.width, stretchHeightCanvas.height); 41 | return stretchHeightCanvas; 42 | } 43 | 44 | /** 45 | * Scratch 2.0 had resolution 1 and 2 bitmaps. All bitmaps in Scratch 3.0 are equivalent 46 | * to resolution 2 bitmaps. Therefore, converting a resolution 1 bitmap means doubling 47 | * it in width and height. 48 | * @param {!string} dataURI Base 64 encoded image data of the bitmap 49 | * @param {!function} callback Node-style callback that returns updated dataURI if conversion succeeded 50 | */ 51 | convertResolution1Bitmap (dataURI, callback) { 52 | const image = this._makeImage(); 53 | image.src = dataURI; 54 | image.onload = () => { 55 | callback(null, this.resize(image, image.width * 2, image.height * 2).toDataURL()); 56 | }; 57 | image.onerror = () => { 58 | callback('Image load failed'); 59 | }; 60 | } 61 | 62 | /** 63 | * Given width/height of an uploaded item, return width/height the image will be resized 64 | * to in Scratch 3.0 65 | * @param {!number} oldWidth original width 66 | * @param {!number} oldHeight original height 67 | * @return {object} Array of new width, new height 68 | */ 69 | getResizedWidthHeight (oldWidth, oldHeight) { 70 | const STAGE_WIDTH = 480; 71 | const STAGE_HEIGHT = 360; 72 | const STAGE_RATIO = STAGE_WIDTH / STAGE_HEIGHT; 73 | 74 | // If both dimensions are smaller than or equal to corresponding stage dimension, 75 | // double both dimensions 76 | if ((oldWidth <= STAGE_WIDTH) && (oldHeight <= STAGE_HEIGHT)) { 77 | return {width: oldWidth * 2, height: oldHeight * 2}; 78 | } 79 | 80 | // If neither dimension is larger than 2x corresponding stage dimension, 81 | // this is an in-between image, return it as is 82 | if ((oldWidth <= STAGE_WIDTH * 2) && (oldHeight <= STAGE_HEIGHT * 2)) { 83 | return {width: oldWidth, height: oldHeight}; 84 | } 85 | 86 | const imageRatio = oldWidth / oldHeight; 87 | // Otherwise, figure out how to resize 88 | if (imageRatio >= STAGE_RATIO) { 89 | // Wide Image 90 | return {width: STAGE_WIDTH * 2, height: STAGE_WIDTH * 2 / imageRatio}; 91 | } 92 | // In this case we have either: 93 | // - A wide image, but not with as big a ratio between width and height, 94 | // making it so that fitting the width to double stage size would leave 95 | // the height too big to fit in double the stage height 96 | // - A square image that's still larger than the double at least 97 | // one of the stage dimensions, so pick the smaller of the two dimensions (to fit) 98 | // - A tall image 99 | // In any of these cases, resize the image to fit the height to double the stage height 100 | return {width: STAGE_HEIGHT * 2 * imageRatio, height: STAGE_HEIGHT * 2}; 101 | } 102 | 103 | /** 104 | * Given bitmap data, resize as necessary. 105 | * @param {ArrayBuffer | string} fileData Base 64 encoded image data of the bitmap 106 | * @param {string} fileType The MIME type of this file 107 | * @returns {Promise} Resolves to resized image data Uint8Array 108 | */ 109 | importBitmap (fileData, fileType) { 110 | let dataURI = fileData; 111 | if (fileData instanceof ArrayBuffer) { 112 | dataURI = this.convertBinaryToDataURI(fileData, fileType); 113 | } 114 | return new Promise((resolve, reject) => { 115 | const image = this._makeImage(); 116 | image.src = dataURI; 117 | image.onload = () => { 118 | const newSize = this.getResizedWidthHeight(image.width, image.height); 119 | if (newSize.width === image.width && newSize.height === image.height) { 120 | // No change 121 | resolve(this.convertDataURIToBinary(dataURI)); 122 | } else { 123 | const resizedDataURI = this.resize(image, newSize.width, newSize.height).toDataURL(); 124 | resolve(this.convertDataURIToBinary(resizedDataURI)); 125 | } 126 | }; 127 | image.onerror = () => { 128 | // TODO: reject with an Error (breaking API change!) 129 | // eslint-disable-next-line prefer-promise-reject-errors 130 | reject('Image load failed'); 131 | }; 132 | }); 133 | } 134 | 135 | // TODO consolidate with scratch-vm/src/util/base64-util.js 136 | // From https://gist.github.com/borismus/1032746 137 | convertDataURIToBinary (dataURI) { 138 | const BASE64_MARKER = ';base64,'; 139 | const base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length; 140 | const base64 = dataURI.substring(base64Index); 141 | const raw = window.atob(base64); 142 | const rawLength = raw.length; 143 | const array = new Uint8Array(new ArrayBuffer(rawLength)); 144 | 145 | for (let i = 0; i < rawLength; i++) { 146 | array[i] = raw.charCodeAt(i); 147 | } 148 | return array; 149 | } 150 | 151 | convertBinaryToDataURI (arrayBuffer, contentType) { 152 | return `data:${contentType};base64,${base64js.fromByteArray(new Uint8Array(arrayBuffer))}`; 153 | } 154 | } 155 | 156 | module.exports = BitmapAdapter; 157 | -------------------------------------------------------------------------------- /src/fixup-svg-string.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Fixup svg string prior to parsing. 3 | * @param {!string} svgString String of the svg to fix. 4 | * @returns {!string} fixed svg that should be parseable. 5 | */ 6 | module.exports = function (svgString) { 7 | // Add root svg namespace if it does not exist. 8 | const svgAttrs = svgString.match(/]*>/); 9 | if (svgAttrs && svgAttrs[0].indexOf('xmlns=') === -1) { 10 | svgString = svgString.replace(']+?xlink:href=["'])data:img\/png/g, 27 | // use the captured ]+?xmlns:(?!xml=)[^ ]+=)"http:\/\/www.w3.org\/XML\/1998\/namespace"/g; 37 | if (svgString.match(xmlnsRegex) !== null) { 38 | svgString = svgString.replace( 39 | // capture the entire attribute 40 | xmlnsRegex, 41 | // use the captured attribute name; replace only the URL 42 | ($0, $1) => `${$1}"http://dummy.namespace"` 43 | ); 44 | } 45 | 46 | // Strip `svg:` prefix (sometimes added by Inkscape) from all tags. They interfere with DOMPurify (prefixed tag 47 | // names are not recognized) and the paint editor. 48 | // This matches opening and closing tags--the capture group captures the slash if it exists, and it is reinserted 49 | // in the replacement text. 50 | svgString = svgString.replace(/<(\/?)\s*svg:/g, '<$1'); 51 | 52 | // The element is not needed for rendering and sometimes contains 53 | // unparseable garbage from Illustrator :( Empty out the contents. 54 | // Note: [\s\S] matches everything including newlines, which .* does not 55 | svgString = svgString.replace(/[\s\S]*<\/metadata>/, ''); 56 | 57 | // Empty script tags and javascript executing 58 | svgString = svgString.replace(/[\s\S]*<\/script>/, ''); 59 | 60 | return svgString; 61 | }; 62 | -------------------------------------------------------------------------------- /src/font-converter.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileOverview Convert 2.0 fonts to 3.0 fonts. 3 | */ 4 | 5 | /** 6 | * Given an SVG, replace Scratch 2.0 fonts with new 3.0 fonts. Add defaults where there are none. 7 | * @param {SVGElement} svgTag The SVG dom object 8 | * @return {void} 9 | */ 10 | const convertFonts = function (svgTag) { 11 | // Collect all text elements into a list. 12 | const textElements = []; 13 | const collectText = domElement => { 14 | if (domElement.localName === 'text') { 15 | textElements.push(domElement); 16 | } 17 | for (let i = 0; i < domElement.childNodes.length; i++) { 18 | collectText(domElement.childNodes[i]); 19 | } 20 | }; 21 | collectText(svgTag); 22 | // If there's an old font-family, switch to the new one. 23 | for (const textElement of textElements) { 24 | // If there's no font-family provided, provide one. 25 | if (!textElement.getAttribute('font-family') || 26 | textElement.getAttribute('font-family') === 'Helvetica') { 27 | textElement.setAttribute('font-family', 'Sans Serif'); 28 | } else if (textElement.getAttribute('font-family') === 'Mystery') { 29 | textElement.setAttribute('font-family', 'Curly'); 30 | } else if (textElement.getAttribute('font-family') === 'Gloria') { 31 | textElement.setAttribute('font-family', 'Handwriting'); 32 | } else if (textElement.getAttribute('font-family') === 'Donegal') { 33 | textElement.setAttribute('font-family', 'Serif'); 34 | } 35 | } 36 | }; 37 | 38 | module.exports = convertFonts; 39 | -------------------------------------------------------------------------------- /src/font-inliner.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileOverview Import bitmap data into Scratch 3.0, resizing image as necessary. 3 | */ 4 | const getFonts = require('scratch-render-fonts'); 5 | 6 | /** 7 | * Given SVG data, inline the fonts. This allows them to be rendered correctly when set 8 | * as the source of an HTMLImageElement. Here is a note from tmickel: 9 | * // Inject fonts that are needed. 10 | * // It would be nice if there were another way to get the SVG-in-canvas 11 | * // to render the correct font family, but I couldn't find any other way. 12 | * // Other things I tried: 13 | * // Just injecting the font-family into the document: no effect. 14 | * // External stylesheet linked to by SVG: no effect. 15 | * // Using a or to link to font-family 16 | * // injected into the document: no effect. 17 | * @param {string} svgString The string representation of the svg to modify 18 | * @return {string} The svg with any needed fonts inlined 19 | */ 20 | const inlineSvgFonts = function (svgString) { 21 | const FONTS = getFonts(); 22 | // Make it clear that this function only operates on strings. 23 | // If we don't explicitly throw this here, the function silently fails. 24 | if (typeof svgString !== 'string') { 25 | throw new Error('SVG to be inlined is not a string'); 26 | } 27 | 28 | // Collect fonts that need injection. 29 | const fontsNeeded = new Set(); 30 | const fontRegex = /font-family="([^"]*)"/g; 31 | let matches = fontRegex.exec(svgString); 32 | while (matches) { 33 | fontsNeeded.add(matches[1]); 34 | matches = fontRegex.exec(svgString); 35 | } 36 | if (fontsNeeded.size > 0) { 37 | let str = ''; 44 | svgString = svgString.replace(/]*>/, `$&${str}`); 45 | return svgString; 46 | } 47 | return svgString; 48 | }; 49 | 50 | module.exports = inlineSvgFonts; 51 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | const SVGRenderer = require('./svg-renderer'); 2 | const BitmapAdapter = require('./bitmap-adapter'); 3 | const inlineSvgFonts = require('./font-inliner'); 4 | const loadSvgString = require('./load-svg-string'); 5 | const sanitizeSvg = require('./sanitize-svg'); 6 | const serializeSvgToString = require('./serialize-svg-to-string'); 7 | const SvgElement = require('./svg-element'); 8 | const convertFonts = require('./font-converter'); 9 | // /** 10 | // * Export for NPM & Node.js 11 | // * @type {RenderWebGL} 12 | // */ 13 | module.exports = { 14 | BitmapAdapter: BitmapAdapter, 15 | convertFonts: convertFonts, 16 | inlineSvgFonts: inlineSvgFonts, 17 | loadSvgString: loadSvgString, 18 | sanitizeSvg: sanitizeSvg, 19 | serializeSvgToString: serializeSvgToString, 20 | SvgElement: SvgElement, 21 | SVGRenderer: SVGRenderer 22 | }; 23 | -------------------------------------------------------------------------------- /src/load-svg-string.js: -------------------------------------------------------------------------------- 1 | const DOMPurify = require('isomorphic-dompurify'); 2 | const SvgElement = require('./svg-element'); 3 | const convertFonts = require('./font-converter'); 4 | const fixupSvgString = require('./fixup-svg-string'); 5 | const transformStrokeWidths = require('./transform-applier'); 6 | 7 | /** 8 | * @param {SVGElement} svgTag the tag to search within 9 | * @param {string} [tagName] svg tag to search for (or collect all elements if not given) 10 | * @return {Array} a list of elements with the given tagname 11 | */ 12 | const collectElements = (svgTag, tagName) => { 13 | const elts = []; 14 | const collectElementsInner = domElement => { 15 | if ((domElement.localName === tagName || typeof tagName === 'undefined') && domElement.getAttribute) { 16 | elts.push(domElement); 17 | } 18 | for (let i = 0; i < domElement.childNodes.length; i++) { 19 | collectElementsInner(domElement.childNodes[i]); 20 | } 21 | }; 22 | collectElementsInner(svgTag); 23 | return elts; 24 | }; 25 | 26 | /** 27 | * Fix SVGs to comply with SVG spec. Scratch 2 defaults to x2 = 0 when x2 is missing, but 28 | * SVG defaults to x2 = 1 when missing. 29 | * @param {SVGSVGElement} svgTag the SVG tag to apply the transformation to 30 | */ 31 | const transformGradients = svgTag => { 32 | const linearGradientElements = collectElements(svgTag, 'linearGradient'); 33 | 34 | // For each gradient element, supply x2 if necessary. 35 | for (const gradientElement of linearGradientElements) { 36 | if (!gradientElement.getAttribute('x2')) { 37 | gradientElement.setAttribute('x2', '0'); 38 | } 39 | } 40 | }; 41 | 42 | /** 43 | * Fix SVGs to match appearance in Scratch 2, which used nearest neighbor scaling for bitmaps 44 | * within SVGs. 45 | * @param {SVGSVGElement} svgTag the SVG tag to apply the transformation to 46 | */ 47 | const transformImages = svgTag => { 48 | const imageElements = collectElements(svgTag, 'image'); 49 | 50 | // For each image element, set image rendering to pixelated 51 | const pixelatedImages = 'image-rendering: optimizespeed; image-rendering: pixelated;'; 52 | for (const elt of imageElements) { 53 | if (elt.getAttribute('style')) { 54 | elt.setAttribute('style', 55 | `${pixelatedImages} ${elt.getAttribute('style')}`); 56 | } else { 57 | elt.setAttribute('style', pixelatedImages); 58 | } 59 | } 60 | }; 61 | 62 | /** 63 | * Transforms an SVG's text elements for Scratch 2.0 quirks. 64 | * These quirks include: 65 | * 1. `x` and `y` properties are removed/ignored. 66 | * 2. Alignment is set to `text-before-edge`. 67 | * 3. Line-breaks are converted to explicit elements. 68 | * 4. Any required fonts are injected. 69 | * @param {SVGSVGElement} svgTag the SVG tag to apply the transformation to 70 | */ 71 | const transformText = svgTag => { 72 | // Collect all text elements into a list. 73 | const textElements = []; 74 | const collectText = domElement => { 75 | if (domElement.localName === 'text') { 76 | textElements.push(domElement); 77 | } 78 | for (let i = 0; i < domElement.childNodes.length; i++) { 79 | collectText(domElement.childNodes[i]); 80 | } 81 | }; 82 | collectText(svgTag); 83 | convertFonts(svgTag); 84 | // For each text element, apply quirks. 85 | for (const textElement of textElements) { 86 | // Remove x and y attributes - they are not used in Scratch. 87 | textElement.removeAttribute('x'); 88 | textElement.removeAttribute('y'); 89 | // Set text-before-edge alignment: 90 | // Scratch renders all text like this. 91 | textElement.setAttribute('alignment-baseline', 'text-before-edge'); 92 | textElement.setAttribute('xml:space', 'preserve'); 93 | // If there's no font size provided, provide one. 94 | if (!textElement.getAttribute('font-size')) { 95 | textElement.setAttribute('font-size', '18'); 96 | } 97 | let text = textElement.textContent; 98 | 99 | // Fix line breaks in text, which are not natively supported by SVG. 100 | // Only fix if text does not have child tspans. 101 | // @todo this will not work for font sizes with units such as em, percent 102 | // However, text made in scratch 2 should only ever export size 22 font. 103 | const fontSize = parseFloat(textElement.getAttribute('font-size')); 104 | const tx = 2; 105 | let ty = 0; 106 | let spacing = 1.2; 107 | // Try to match the position and spacing of Scratch 2.0's fonts. 108 | // Different fonts seem to use different line spacing. 109 | // Scratch 2 always uses alignment-baseline=text-before-edge 110 | // However, most SVG readers don't support this attribute 111 | // or don't support it alongside use of tspan, so the translations 112 | // here are to make up for that. 113 | if (textElement.getAttribute('font-family') === 'Handwriting') { 114 | spacing = 2; 115 | ty = -11 * fontSize / 22; 116 | } else if (textElement.getAttribute('font-family') === 'Scratch') { 117 | spacing = 0.89; 118 | ty = -3 * fontSize / 22; 119 | } else if (textElement.getAttribute('font-family') === 'Curly') { 120 | spacing = 1.38; 121 | ty = -6 * fontSize / 22; 122 | } else if (textElement.getAttribute('font-family') === 'Marker') { 123 | spacing = 1.45; 124 | ty = -6 * fontSize / 22; 125 | } else if (textElement.getAttribute('font-family') === 'Sans Serif') { 126 | spacing = 1.13; 127 | ty = -3 * fontSize / 22; 128 | } else if (textElement.getAttribute('font-family') === 'Serif') { 129 | spacing = 1.25; 130 | ty = -4 * fontSize / 22; 131 | } 132 | 133 | if (textElement.transform.baseVal.numberOfItems === 0) { 134 | const transform = svgTag.createSVGTransform(); 135 | textElement.transform.baseVal.appendItem(transform); 136 | } 137 | 138 | // Right multiply matrix by a translation of (tx, ty) 139 | const mtx = textElement.transform.baseVal.getItem(0).matrix; 140 | mtx.e += (mtx.a * tx) + (mtx.c * ty); 141 | mtx.f += (mtx.b * tx) + (mtx.d * ty); 142 | 143 | if (text && textElement.childElementCount === 0) { 144 | textElement.textContent = ''; 145 | const lines = text.split('\n'); 146 | text = ''; 147 | for (const line of lines) { 148 | const tspanNode = SvgElement.create('tspan'); 149 | tspanNode.setAttribute('x', '0'); 150 | tspanNode.setAttribute('style', 'white-space: pre'); 151 | tspanNode.setAttribute('dy', `${spacing}em`); 152 | tspanNode.textContent = line ? line : ' '; 153 | textElement.appendChild(tspanNode); 154 | } 155 | } 156 | } 157 | }; 158 | 159 | /** 160 | * Find the largest stroke width in the svg. If a shape has no 161 | * `stroke` property, it has a stroke-width of 0. If it has a `stroke`, 162 | * it is by default a stroke-width of 1. 163 | * This is used to enlarge the computed bounding box, which doesn't take 164 | * stroke width into account. 165 | * @param {SVGSVGElement} rootNode The root SVG node to traverse. 166 | * @return {number} The largest stroke width in the SVG. 167 | */ 168 | const findLargestStrokeWidth = rootNode => { 169 | let largestStrokeWidth = 0; 170 | const collectStrokeWidths = domElement => { 171 | if (domElement.getAttribute) { 172 | if (domElement.getAttribute('stroke')) { 173 | largestStrokeWidth = Math.max(largestStrokeWidth, 1); 174 | } 175 | if (domElement.getAttribute('stroke-width')) { 176 | largestStrokeWidth = Math.max( 177 | largestStrokeWidth, 178 | Number(domElement.getAttribute('stroke-width')) || 0 179 | ); 180 | } 181 | } 182 | for (let i = 0; i < domElement.childNodes.length; i++) { 183 | collectStrokeWidths(domElement.childNodes[i]); 184 | } 185 | }; 186 | collectStrokeWidths(rootNode); 187 | return largestStrokeWidth; 188 | }; 189 | 190 | /** 191 | * Transform the measurements of the SVG. 192 | * In Scratch 2.0, SVGs are drawn without respect to the width, 193 | * height, and viewBox attribute on the tag. The exporter 194 | * does output these properties - but they appear to be incorrect often. 195 | * To address the incorrect measurements, we append the DOM to the 196 | * document, and then use SVG's native `getBBox` to find the real 197 | * drawn dimensions. This ensures things drawn in negative dimensions, 198 | * outside the given viewBox, etc., are all eventually drawn to the canvas. 199 | * I tried to do this several other ways: stripping the width/height/viewBox 200 | * attributes and then drawing (Firefox won't draw anything), 201 | * or inflating them and then measuring a canvas. But this seems to be 202 | * a natural and performant way. 203 | * @param {SVGSVGElement} svgTag the SVG tag to apply the transformation to 204 | */ 205 | const transformMeasurements = svgTag => { 206 | // Append the SVG dom to the document. 207 | // This allows us to use `getBBox` on the page, 208 | // which returns the full bounding-box of all drawn SVG 209 | // elements, similar to how Scratch 2.0 did measurement. 210 | const svgSpot = document.createElement('span'); 211 | // Since we're adding user-provided SVG to document.body, 212 | // sanitizing is required. This should not affect bounding box calculation. 213 | // outerHTML is attribute of Element (and not HTMLElement), so use it instead of 214 | // calling serializer or toString() 215 | // NOTE: svgTag remains untouched! 216 | const rawValue = svgTag.outerHTML; 217 | const sanitizedValue = DOMPurify.sanitize(rawValue, { 218 | // Use SVG profile (no HTML elements) 219 | USE_PROFILES: {svg: true}, 220 | // Remove some tags that Scratch does not use. 221 | FORBID_TAGS: ['a', 'audio', 'canvas', 'video'], 222 | // Allow data URI in image tags (e.g. SVGs converted from bitmap) 223 | ADD_DATA_URI_TAGS: ['image'] 224 | }); 225 | let bbox; 226 | try { 227 | // Insert sanitized value. 228 | svgSpot.innerHTML = sanitizedValue; 229 | document.body.appendChild(svgSpot); 230 | // Take the bounding box. We have to get elements via svgSpot 231 | // because we added it via innerHTML. 232 | bbox = svgSpot.children[0].getBBox(); 233 | } finally { 234 | // Always destroy the element, even if, for example, getBBox throws. 235 | document.body.removeChild(svgSpot); 236 | } 237 | 238 | // Enlarge the bbox from the largest found stroke width 239 | // This may have false-positives, but at least the bbox will always 240 | // contain the full graphic including strokes. 241 | // If the width or height is zero however, don't enlarge since 242 | // they won't have a stroke width that needs to be enlarged. 243 | let halfStrokeWidth; 244 | if (bbox.width === 0 || bbox.height === 0) { 245 | halfStrokeWidth = 0; 246 | } else { 247 | halfStrokeWidth = findLargestStrokeWidth(svgTag) / 2; 248 | } 249 | const width = bbox.width + (halfStrokeWidth * 2); 250 | const height = bbox.height + (halfStrokeWidth * 2); 251 | const x = bbox.x - halfStrokeWidth; 252 | const y = bbox.y - halfStrokeWidth; 253 | 254 | // Set the correct measurements on the SVG tag 255 | svgTag.setAttribute('width', width); 256 | svgTag.setAttribute('height', height); 257 | svgTag.setAttribute('viewBox', 258 | `${x} ${y} ${width} ${height}`); 259 | }; 260 | 261 | /** 262 | * Find all instances of a URL-referenced `stroke` in the svg. In 2.0, all gradient strokes 263 | * have a round `stroke-linejoin` and `stroke-linecap`... for some reason. 264 | * @param {SVGSVGElement} svgTag the SVG tag to apply the transformation to 265 | */ 266 | const setGradientStrokeRoundedness = svgTag => { 267 | const elements = collectElements(svgTag); 268 | 269 | for (const elt of elements) { 270 | if (!elt.style) continue; 271 | const stroke = elt.style.stroke || elt.getAttribute('stroke'); 272 | if (stroke && stroke.match(/^url\(#.*\)$/)) { 273 | elt.style['stroke-linejoin'] = 'round'; 274 | elt.style['stroke-linecap'] = 'round'; 275 | } 276 | } 277 | }; 278 | 279 | /** 280 | * In-place, convert passed SVG to something consistent that will be rendered the way we want them to be. 281 | * @param {SVGSvgElement} svgTag root SVG node to operate upon 282 | * @param {boolean} [fromVersion2] True if we should perform conversion from version 2 to version 3 svg. 283 | */ 284 | const normalizeSvg = (svgTag, fromVersion2) => { 285 | if (fromVersion2) { 286 | // Fix gradients. Scratch 2 exports no x2 when x2 = 0, but 287 | // SVG default is that x2 is 1. This must be done before 288 | // transformStrokeWidths since transformStrokeWidths affects 289 | // gradients. 290 | transformGradients(svgTag); 291 | } 292 | transformStrokeWidths(svgTag, window); 293 | transformImages(svgTag); 294 | if (fromVersion2) { 295 | // Transform all text elements. 296 | transformText(svgTag); 297 | // Transform measurements. 298 | transformMeasurements(svgTag); 299 | // Fix stroke roundedness. 300 | setGradientStrokeRoundedness(svgTag); 301 | } else if (!svgTag.getAttribute('viewBox')) { 302 | // Renderer expects a view box. 303 | transformMeasurements(svgTag); 304 | } else if (!svgTag.getAttribute('width') || !svgTag.getAttribute('height')) { 305 | svgTag.setAttribute('width', svgTag.viewBox.baseVal.width); 306 | svgTag.setAttribute('height', svgTag.viewBox.baseVal.height); 307 | } 308 | }; 309 | 310 | /** 311 | * Load an SVG string and normalize it. All the steps before drawing/measuring. 312 | * Currently, this will normalize stroke widths (see transform-applier.js) and render all embedded images pixelated. 313 | * The returned SVG will be guaranteed to always have a `width`, `height` and `viewBox`. 314 | * In addition, if the `fromVersion2` parameter is `true`, several "quirks-mode" transformations will be applied which 315 | * mimic Scratch 2.0's SVG rendering. 316 | * @param {!string} svgString String of SVG data to draw in quirks-mode. 317 | * @param {boolean} [fromVersion2] True if we should perform conversion from version 2 to version 3 svg. 318 | * @return {SVGSVGElement} The normalized SVG element. 319 | */ 320 | const loadSvgString = (svgString, fromVersion2) => { 321 | // Parse string into SVG XML. 322 | const parser = new DOMParser(); 323 | svgString = fixupSvgString(svgString); 324 | const svgDom = parser.parseFromString(svgString, 'text/xml'); 325 | if (svgDom.childNodes.length < 1 || 326 | svgDom.documentElement.localName !== 'svg') { 327 | throw new Error('Document does not appear to be SVG.'); 328 | } 329 | const svgTag = svgDom.documentElement; 330 | normalizeSvg(svgTag, fromVersion2); 331 | return svgTag; 332 | }; 333 | 334 | module.exports = loadSvgString; 335 | -------------------------------------------------------------------------------- /src/playground/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Scratch SVG rendering playground 6 | 18 | 19 | 20 |

21 | 22 |

23 |

24 | 25 | 26 | 27 |

28 |

29 | 30 | 34 |

35 | 36 |
37 |
38 |
Rendered Result
39 | 40 |
41 |
42 |
Reference
43 | 44 |
45 |
46 |
47 |
48 |
Rendered Content
49 | 50 |
51 |
52 |
Reference
53 | 54 | 55 |
56 |
57 | 58 | 59 | 131 | 132 | 133 | -------------------------------------------------------------------------------- /src/sanitize-svg.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileOverview Sanitize the content of an SVG aggressively, to make it as safe 3 | * as possible 4 | */ 5 | const fixupSvgString = require('./fixup-svg-string'); 6 | const {generate, parse, walk} = require('css-tree'); 7 | const DOMPurify = require('isomorphic-dompurify'); 8 | 9 | const sanitizeSvg = {}; 10 | 11 | DOMPurify.addHook( 12 | 'beforeSanitizeAttributes', 13 | currentNode => { 14 | 15 | if (currentNode && currentNode.href && currentNode.href.baseVal) { 16 | const href = currentNode.href.baseVal.replace(/\s/g, ''); 17 | // "data:" and "#" are valid hrefs 18 | if ((href.slice(0, 5) !== 'data:') && (href.slice(0, 1) !== '#')) { 19 | 20 | if (currentNode.attributes.getNamedItem('xlink:href')) { 21 | currentNode.attributes.removeNamedItem('xlink:href'); 22 | delete currentNode['xlink:href']; 23 | } 24 | if (currentNode.attributes.getNamedItem('href')) { 25 | currentNode.attributes.removeNamedItem('href'); 26 | delete currentNode.href; 27 | } 28 | } 29 | } 30 | return currentNode; 31 | } 32 | ); 33 | 34 | DOMPurify.addHook( 35 | 'uponSanitizeElement', 36 | (node, data) => { 37 | if (data.tagName === 'style') { 38 | const ast = parse(node.textContent); 39 | let isModified = false; 40 | // Remove any @import rules as it could leak HTTP requests 41 | walk(ast, (astNode, item, list) => { 42 | if (astNode.type === 'Atrule' && astNode.name === 'import') { 43 | list.remove(item); 44 | isModified = true; 45 | } 46 | }); 47 | if (isModified) { 48 | node.textContent = generate(ast); 49 | } 50 | } 51 | } 52 | ); 53 | 54 | // Use JS implemented TextDecoder and TextEncoder if it is not provided by the 55 | // browser. 56 | let _TextDecoder; 57 | let _TextEncoder; 58 | if (typeof TextDecoder === 'undefined' || typeof TextEncoder === 'undefined') { 59 | // Wait to require the text encoding polyfill until we know it's needed. 60 | // eslint-disable-next-line global-require 61 | const encoding = require('fastestsmallesttextencoderdecoder'); 62 | _TextDecoder = encoding.TextDecoder; 63 | _TextEncoder = encoding.TextEncoder; 64 | } else { 65 | _TextDecoder = TextDecoder; 66 | _TextEncoder = TextEncoder; 67 | } 68 | 69 | /** 70 | * Load an SVG Uint8Array of bytes and "sanitize" it 71 | * @param {!Uint8Array} rawData unsanitized SVG daata 72 | * @return {Uint8Array} sanitized SVG data 73 | */ 74 | sanitizeSvg.sanitizeByteStream = function (rawData) { 75 | const decoder = new _TextDecoder(); 76 | const encoder = new _TextEncoder(); 77 | const sanitizedText = sanitizeSvg.sanitizeSvgText(decoder.decode(rawData)); 78 | return encoder.encode(sanitizedText); 79 | }; 80 | 81 | /** 82 | * Load an SVG string and "sanitize" it. This is more aggressive than the handling in 83 | * fixup-svg-string.js, and thus more risky; there are known examples of SVGs that 84 | * it will clobber. We use DOMPurify's svg profile, which restricts many types of tag. 85 | * @param {!string} rawSvgText unsanitized SVG string 86 | * @return {string} sanitized SVG text 87 | */ 88 | sanitizeSvg.sanitizeSvgText = function (rawSvgText) { 89 | let sanitizedText = DOMPurify.sanitize(rawSvgText, { 90 | USE_PROFILES: {svg: true} 91 | }); 92 | 93 | // Remove partial XML comment that is sometimes left in the HTML 94 | const badTag = sanitizedText.indexOf(']>'); 95 | if (badTag >= 0) { 96 | sanitizedText = sanitizedText.substring(5, sanitizedText.length); 97 | } 98 | 99 | // also use our custom fixup rules 100 | sanitizedText = fixupSvgString(sanitizedText); 101 | return sanitizedText; 102 | }; 103 | 104 | module.exports = sanitizeSvg; 105 | -------------------------------------------------------------------------------- /src/serialize-svg-to-string.js: -------------------------------------------------------------------------------- 1 | const inlineSvgFonts = require('./font-inliner'); 2 | 3 | /** 4 | * Serialize a given SVG DOM to a string. 5 | * @param {SVGSVGElement} svgTag The SVG element to serialize. 6 | * @param {?boolean} shouldInjectFonts True if fonts should be included in the SVG as 7 | * base64 data. 8 | * @returns {string} String representing current SVG data. 9 | */ 10 | const serializeSvgToString = (svgTag, shouldInjectFonts) => { 11 | const serializer = new XMLSerializer(); 12 | let string = serializer.serializeToString(svgTag); 13 | if (shouldInjectFonts) { 14 | string = inlineSvgFonts(string); 15 | } 16 | return string; 17 | }; 18 | 19 | module.exports = serializeSvgToString; 20 | -------------------------------------------------------------------------------- /src/svg-element.js: -------------------------------------------------------------------------------- 1 | /* Adapted from 2 | * Paper.js - The Swiss Army Knife of Vector Graphics Scripting. 3 | * http://paperjs.org/ 4 | * 5 | * Copyright (c) 2011 - 2016, Juerg Lehni & Jonathan Puckey 6 | * http://scratchdisk.com/ & http://jonathanpuckey.com/ 7 | * 8 | * Distributed under the MIT license. See LICENSE file for details. 9 | * 10 | * All rights reserved. 11 | */ 12 | 13 | /** 14 | * @name SvgElement 15 | * @namespace 16 | * @private 17 | */ 18 | class SvgElement { 19 | // SVG related namespaces 20 | static get svg () { 21 | return 'http://www.w3.org/2000/svg'; 22 | } 23 | static get xmlns () { 24 | return 'http://www.w3.org/2000/xmlns'; 25 | } 26 | static get xlink () { 27 | return 'http://www.w3.org/1999/xlink'; 28 | } 29 | 30 | // Mapping of attribute names to required namespaces: 31 | static attributeNamespace () { 32 | return { 33 | 'href': SvgElement.xlink, 34 | 'xlink': SvgElement.xmlns, 35 | // Only the xmlns attribute needs the trailing slash. See #984 36 | 'xmlns': `${SvgElement.xmlns}/`, 37 | // IE needs the xmlns namespace when setting 'xmlns:xlink'. See #984 38 | 'xmlns:xlink': `${SvgElement.xmlns}/` 39 | }; 40 | } 41 | 42 | static create (tag, attributes, formatter) { 43 | return SvgElement.set(document.createElementNS(SvgElement.svg, tag), attributes, formatter); 44 | } 45 | 46 | static get (node, name) { 47 | const namespace = SvgElement.attributeNamespace[name]; 48 | const value = namespace ? 49 | node.getAttributeNS(namespace, name) : 50 | node.getAttribute(name); 51 | return value === 'null' ? null : value; 52 | } 53 | 54 | static set (node, attributes, formatter) { 55 | for (const name in attributes) { 56 | let value = attributes[name]; 57 | const namespace = SvgElement.attributeNamespace[name]; 58 | if (typeof value === 'number' && formatter) { 59 | value = formatter.number(value); 60 | } 61 | if (namespace) { 62 | node.setAttributeNS(namespace, name, value); 63 | } else { 64 | node.setAttribute(name, value); 65 | } 66 | } 67 | return node; 68 | } 69 | } 70 | 71 | module.exports = SvgElement; 72 | -------------------------------------------------------------------------------- /src/svg-renderer.js: -------------------------------------------------------------------------------- 1 | const loadSvgString = require('./load-svg-string'); 2 | const serializeSvgToString = require('./serialize-svg-to-string'); 3 | 4 | /** 5 | * Main quirks-mode SVG rendering code. 6 | * @deprecated Call into individual methods exported from this library instead. 7 | */ 8 | class SvgRenderer { 9 | /** 10 | * Create a quirks-mode SVG renderer for a particular canvas. 11 | * @param {HTMLCanvasElement} [canvas] An optional canvas element to draw to. If this is not provided, the renderer 12 | * will create a new canvas. 13 | * @constructor 14 | */ 15 | constructor (canvas) { 16 | /** 17 | * The canvas that this SVG renderer will render to. 18 | * @type {HTMLCanvasElement} 19 | * @private 20 | */ 21 | this._canvas = canvas || document.createElement('canvas'); 22 | this._context = this._canvas.getContext('2d'); 23 | 24 | /** 25 | * A measured SVG "viewbox" 26 | * @typedef {object} SvgRenderer#SvgMeasurements 27 | * @property {number} x - The left edge of the SVG viewbox. 28 | * @property {number} y - The top edge of the SVG viewbox. 29 | * @property {number} width - The width of the SVG viewbox. 30 | * @property {number} height - The height of the SVG viewbox. 31 | */ 32 | 33 | /** 34 | * The measurement box of the currently loaded SVG. 35 | * @type {SvgRenderer#SvgMeasurements} 36 | * @private 37 | */ 38 | this._measurements = {x: 0, y: 0, width: 0, height: 0}; 39 | 40 | /** 41 | * The `` element with the contents of the currently loaded SVG. 42 | * @type {?HTMLImageElement} 43 | * @private 44 | */ 45 | this._cachedImage = null; 46 | 47 | /** 48 | * True if this renderer's current SVG is loaded and can be rendered to the canvas. 49 | * @type {boolean} 50 | */ 51 | this.loaded = false; 52 | } 53 | 54 | /** 55 | * @returns {!HTMLCanvasElement} this renderer's target canvas. 56 | */ 57 | get canvas () { 58 | return this._canvas; 59 | } 60 | 61 | /** 62 | * @return {Array} the natural size, in Scratch units, of this SVG. 63 | */ 64 | get size () { 65 | return [this._measurements.width, this._measurements.height]; 66 | } 67 | 68 | /** 69 | * @return {Array} the offset (upper left corner) of the SVG's view box. 70 | */ 71 | get viewOffset () { 72 | return [this._measurements.x, this._measurements.y]; 73 | } 74 | 75 | /** 76 | * Load an SVG string and normalize it. All the steps before drawing/measuring. 77 | * @param {!string} svgString String of SVG data to draw in quirks-mode. 78 | * @param {?boolean} fromVersion2 True if we should perform conversion from 79 | * version 2 to version 3 svg. 80 | */ 81 | loadString (svgString, fromVersion2) { 82 | // New svg string invalidates the cached image 83 | this._cachedImage = null; 84 | const svgTag = loadSvgString(svgString, fromVersion2); 85 | 86 | this._svgTag = svgTag; 87 | this._measurements = { 88 | width: svgTag.viewBox.baseVal.width, 89 | height: svgTag.viewBox.baseVal.height, 90 | x: svgTag.viewBox.baseVal.x, 91 | y: svgTag.viewBox.baseVal.y 92 | }; 93 | } 94 | 95 | /** 96 | * Load an SVG string, normalize it, and prepare it for (synchronous) rendering. 97 | * @param {!string} svgString String of SVG data to draw in quirks-mode. 98 | * @param {?boolean} fromVersion2 True if we should perform conversion from version 2 to version 3 svg. 99 | * @param {Function} [onFinish] - An optional callback to call when the SVG is loaded and can be rendered. 100 | */ 101 | loadSVG (svgString, fromVersion2, onFinish) { 102 | this.loadString(svgString, fromVersion2); 103 | this._createSVGImage(onFinish); 104 | } 105 | 106 | /** 107 | * Creates an element for the currently loaded SVG string, then calls the callback once it's loaded. 108 | * @param {Function} [onFinish] - An optional callback to call when the has loaded. 109 | */ 110 | _createSVGImage (onFinish) { 111 | if (this._cachedImage === null) this._cachedImage = new Image(); 112 | const img = this._cachedImage; 113 | 114 | img.onload = () => { 115 | this.loaded = true; 116 | if (onFinish) onFinish(); 117 | }; 118 | const svgText = this.toString(true /* shouldInjectFonts */); 119 | img.src = `data:image/svg+xml;utf8,${encodeURIComponent(svgText)}`; 120 | this.loaded = false; 121 | } 122 | 123 | /** 124 | * Serialize the active SVG DOM to a string. 125 | * @param {?boolean} shouldInjectFonts True if fonts should be included in the SVG as 126 | * base64 data. 127 | * @returns {string} String representing current SVG data. 128 | * @deprecated Use the standalone `serializeSvgToString` export instead. 129 | */ 130 | toString (shouldInjectFonts) { 131 | return serializeSvgToString(this._svgTag, shouldInjectFonts); 132 | } 133 | 134 | /** 135 | * Synchronously draw the loaded SVG to this renderer's `canvas`. 136 | * @param {number} [scale] - Optionally, also scale the image by this factor. 137 | */ 138 | draw (scale) { 139 | if (!this.loaded) throw new Error('SVG image has not finished loading'); 140 | this._drawFromImage(scale); 141 | } 142 | 143 | /** 144 | * Draw to the canvas from a loaded image element. 145 | * @param {number} [scale] - Optionally, also scale the image by this factor. 146 | **/ 147 | _drawFromImage (scale) { 148 | if (this._cachedImage === null) return; 149 | 150 | const ratio = Number.isFinite(scale) ? scale : 1; 151 | const bbox = this._measurements; 152 | this._canvas.width = bbox.width * ratio; 153 | this._canvas.height = bbox.height * ratio; 154 | // Even if the canvas at the current scale has a nonzero size, the image's dimensions are floored pre-scaling. 155 | // e.g. if an image has a width of 0.4 and is being rendered at 3x scale, the canvas will have a width of 1, but 156 | // the image's width will be rounded down to 0 on some browsers (Firefox) prior to being drawn at that scale. 157 | if ( 158 | this._canvas.width <= 0 || 159 | this._canvas.height <= 0 || 160 | this._cachedImage.naturalWidth <= 0 || 161 | this._cachedImage.naturalHeight <= 0 162 | ) return; 163 | this._context.clearRect(0, 0, this._canvas.width, this._canvas.height); 164 | this._context.setTransform(ratio, 0, 0, ratio, 0, 0); 165 | this._context.drawImage(this._cachedImage, 0, 0); 166 | } 167 | } 168 | 169 | module.exports = SvgRenderer; 170 | -------------------------------------------------------------------------------- /src/transform-applier.js: -------------------------------------------------------------------------------- 1 | const Matrix = require('transformation-matrix'); 2 | const SvgElement = require('./svg-element'); 3 | const log = require('./util/log'); 4 | 5 | /** 6 | * @fileOverview Apply transforms to match stroke width appearance in 2.0 and 3.0 7 | */ 8 | 9 | // Adapted from paper.js's Path.applyTransform 10 | const _parseTransform = function (domElement) { 11 | let matrix = Matrix.identity(); 12 | const string = domElement.attributes && domElement.attributes.transform && domElement.attributes.transform.value; 13 | if (!string) return matrix; 14 | // https://www.w3.org/TR/SVG/types.html#DataTypeTransformList 15 | // Parse SVG transform string. First we split at /)\s*/, to separate 16 | // commands 17 | const transforms = string.split(/\)\s*/g); 18 | for (const transform of transforms) { 19 | if (!transform) break; 20 | // Command come before the '(', values after 21 | const parts = transform.split(/\(\s*/); 22 | const command = parts[0].trim(); 23 | const v = parts[1].split(/[\s,]+/g); 24 | // Convert values to floats 25 | for (let j = 0; j < v.length; j++) { 26 | v[j] = parseFloat(v[j]); 27 | } 28 | switch (command) { 29 | case 'matrix': 30 | matrix = Matrix.compose(matrix, {a: v[0], b: v[1], c: v[2], d: v[3], e: v[4], f: v[5]}); 31 | break; 32 | case 'rotate': 33 | matrix = Matrix.compose(matrix, Matrix.rotateDEG(v[0], v[1] || 0, v[2] || 0)); 34 | break; 35 | case 'translate': 36 | matrix = Matrix.compose(matrix, Matrix.translate(v[0], v[1] || 0)); 37 | break; 38 | case 'scale': 39 | matrix = Matrix.compose(matrix, Matrix.scale(v[0], v[1] || v[0])); 40 | break; 41 | case 'skewX': 42 | matrix = Matrix.compose(matrix, Matrix.skewDEG(v[0], 0)); 43 | break; 44 | case 'skewY': 45 | matrix = Matrix.compose(matrix, Matrix.skewDEG(0, v[0])); 46 | break; 47 | default: 48 | log.error(`Couldn't parse: ${command}`); 49 | } 50 | } 51 | return matrix; 52 | }; 53 | 54 | // Adapted from paper.js's Matrix.decompose 55 | // Given a matrix, return the x and y scale factors of the matrix 56 | const _getScaleFactor = function (matrix) { 57 | const a = matrix.a; 58 | const b = matrix.b; 59 | const c = matrix.c; 60 | const d = matrix.d; 61 | const det = (a * d) - (b * c); 62 | 63 | if (a !== 0 || b !== 0) { 64 | const r = Math.sqrt((a * a) + (b * b)); 65 | return {x: r, y: det / r}; 66 | } 67 | if (c !== 0 || d !== 0) { 68 | const s = Math.sqrt((c * c) + (d * d)); 69 | return {x: det / s, y: s}; 70 | } 71 | // a = b = c = d = 0 72 | return {x: 0, y: 0}; 73 | }; 74 | 75 | // Returns null if matrix is not invertible. Otherwise returns given ellipse 76 | // transformed by transform, an object {radiusX, radiusY, rotation}. 77 | const _calculateTransformedEllipse = function (radiusX, radiusY, theta, transform) { 78 | theta = -theta * Math.PI / 180; 79 | const a = transform.a; 80 | const b = -transform.c; 81 | const c = -transform.b; 82 | const d = transform.d; 83 | // Since other parameters determine the translation of the ellipse in SVG, we do not need to worry 84 | // about what e and f are. 85 | const det = (a * d) - (b * c); 86 | // Non-invertible matrix 87 | if (det === 0) return null; 88 | 89 | // rotA, rotB, and rotC represent Ax^2 + Bxy + Cy^2 = 1 coefficients for a rotated ellipse formula 90 | const sinT = Math.sin(theta); 91 | const cosT = Math.cos(theta); 92 | const sin2T = Math.sin(2 * theta); 93 | const rotA = (cosT * cosT / radiusX / radiusX) + (sinT * sinT / radiusY / radiusY); 94 | const rotB = (sin2T / radiusX / radiusX) - (sin2T / radiusY / radiusY); 95 | const rotC = (sinT * sinT / radiusX / radiusX) + (cosT * cosT / radiusY / radiusY); 96 | 97 | // Calculate the ellipse formula of the transformed ellipse 98 | // A, B, and C represent Ax^2 + Bxy + Cy^2 = 1 / det / det coefficients in a transformed ellipse formula 99 | // scaled by inverse det squared (to preserve accuracy) 100 | const A = ((rotA * d * d) - (rotB * d * c) + (rotC * c * c)); 101 | const B = ((-2 * rotA * b * d) + (rotB * a * d) + (rotB * b * c) - (2 * rotC * a * c)); 102 | const C = ((rotA * b * b) - (rotB * a * b) + (rotC * a * a)); 103 | 104 | // Derive new radii and theta from the transformed ellipse formula 105 | const newRadiusXOverDet = Math.sqrt(2) * 106 | Math.sqrt( 107 | (A + C - Math.sqrt((A * A) + (B * B) - (2 * A * C) + (C * C))) / 108 | ((-B * B) + (4 * A * C)) 109 | ); 110 | const newRadiusYOverDet = 1 / Math.sqrt(A + C - (1 / newRadiusXOverDet / newRadiusXOverDet)); 111 | let temp = (A - (1 / newRadiusXOverDet / newRadiusXOverDet)) / 112 | ((1 / newRadiusYOverDet / newRadiusYOverDet) - (1 / newRadiusXOverDet / newRadiusXOverDet)); 113 | if (temp < 0 && Math.abs(temp) < 1e-8) temp = 0; // Fix floating point issue 114 | temp = Math.sqrt(temp); 115 | if (Math.abs(1 - temp) < 1e-8) temp = 1; // Fix floating point issue 116 | // Solve for which of the two possible thetas is correct 117 | let newTheta = Math.asin(temp); 118 | temp = (B / ( 119 | (1 / newRadiusXOverDet / newRadiusXOverDet) - 120 | (1 / newRadiusYOverDet / newRadiusYOverDet))); 121 | const newTheta2 = -newTheta; 122 | if (Math.abs(Math.sin(2 * newTheta2) - temp) < 123 | Math.abs(Math.sin(2 * newTheta) - temp)) { 124 | newTheta = newTheta2; 125 | } 126 | 127 | return { 128 | radiusX: newRadiusXOverDet * det, 129 | radiusY: newRadiusYOverDet * det, 130 | rotation: -newTheta * 180 / Math.PI 131 | }; 132 | }; 133 | 134 | // Adapted from paper.js's PathItem.setPathData 135 | const _transformPath = function (pathString, transform) { 136 | if (!transform || Matrix.toString(transform) === Matrix.toString(Matrix.identity())) return pathString; 137 | // First split the path data into parts of command-coordinates pairs 138 | // Commands are any of these characters: mzlhvcsqta 139 | const parts = pathString && pathString.match(/[mlhvcsqtaz][^mlhvcsqtaz]*/ig); 140 | let coords; 141 | let relative = false; 142 | let previous; 143 | let control; 144 | let current = {x: 0, y: 0}; 145 | let start = {x: 0, y: 0}; 146 | let result = ''; 147 | 148 | const getCoord = function (index, coord) { 149 | let val = +coords[index]; 150 | if (relative) { 151 | val += current[coord]; 152 | } 153 | return val; 154 | }; 155 | 156 | const getPoint = function (index) { 157 | return {x: getCoord(index, 'x'), y: getCoord(index + 1, 'y')}; 158 | }; 159 | 160 | const roundTo4Places = function (num) { 161 | return Number(num.toFixed(4)); 162 | }; 163 | 164 | // Returns the transformed point as a string 165 | const getString = function (point) { 166 | const transformed = Matrix.applyToPoint(transform, point); 167 | return `${roundTo4Places(transformed.x)} ${roundTo4Places(transformed.y)} `; 168 | }; 169 | 170 | for (let i = 0, l = parts && parts.length; i < l; i++) { 171 | const part = parts[i]; 172 | const command = part[0]; 173 | const lower = command.toLowerCase(); 174 | // Match all coordinate values 175 | coords = part.match(/[+-]?(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g); 176 | const length = coords && coords.length; 177 | relative = command === lower; 178 | // Fix issues with z in the middle of SVG path data, not followed by 179 | // a m command, see paper.js#413: 180 | if (previous === 'z' && !/[mz]/.test(lower)) { 181 | result += `M ${current.x} ${current.y} `; 182 | } 183 | switch (lower) { 184 | case 'm': // Move to 185 | case 'l': // Line to 186 | { 187 | let move = lower === 'm'; 188 | for (let j = 0; j < length; j += 2) { 189 | result += move ? 'M ' : 'L '; 190 | current = getPoint(j); 191 | result += getString(current); 192 | if (move) { 193 | start = current; 194 | move = false; 195 | } 196 | } 197 | control = current; 198 | break; 199 | } 200 | case 'h': // Horizontal line 201 | case 'v': // Vertical line 202 | { 203 | const coord = lower === 'h' ? 'x' : 'y'; 204 | current = {x: current.x, y: current.y}; // Clone as we're going to modify it. 205 | for (let j = 0; j < length; j++) { 206 | current[coord] = getCoord(j, coord); 207 | result += `L ${getString(current)}`; 208 | } 209 | control = current; 210 | break; 211 | } 212 | case 'c': 213 | // Cubic Bezier curve 214 | for (let j = 0; j < length; j += 6) { 215 | const handle1 = getPoint(j); 216 | control = getPoint(j + 2); 217 | current = getPoint(j + 4); 218 | result += `C ${getString(handle1)}${getString(control)}${getString(current)}`; 219 | } 220 | break; 221 | case 's': 222 | // Smooth cubic Bezier curve 223 | for (let j = 0; j < length; j += 4) { 224 | const handle1 = /[cs]/.test(previous) ? 225 | {x: (current.x * 2) - control.x, y: (current.y * 2) - control.y} : 226 | current; 227 | control = getPoint(j); 228 | current = getPoint(j + 2); 229 | 230 | result += `C ${getString(handle1)}${getString(control)}${getString(current)}`; 231 | previous = lower; 232 | } 233 | break; 234 | case 'q': 235 | // Quadratic Bezier curve 236 | for (let j = 0; j < length; j += 4) { 237 | control = getPoint(j); 238 | current = getPoint(j + 2); 239 | result += `Q ${getString(control)}${getString(current)}`; 240 | } 241 | break; 242 | case 't': 243 | // Smooth quadratic Bezier curve 244 | for (let j = 0; j < length; j += 2) { 245 | control = /[qt]/.test(previous) ? 246 | {x: (current.x * 2) - control.x, y: (current.y * 2) - control.y} : 247 | current; 248 | current = getPoint(j); 249 | 250 | result += `Q ${getString(control)}${getString(current)}`; 251 | previous = lower; 252 | } 253 | break; 254 | case 'a': 255 | // Elliptical arc curve 256 | for (let j = 0; j < length; j += 7) { 257 | current = getPoint(j + 5); 258 | const rx = +coords[j]; 259 | const ry = +coords[j + 1]; 260 | const rotation = +coords[j + 2]; 261 | const largeArcFlag = +coords[j + 3]; 262 | let clockwiseFlag = +coords[j + 4]; 263 | const newEllipse = _calculateTransformedEllipse(rx, ry, rotation, transform); 264 | const matrixScale = _getScaleFactor(transform); 265 | if (newEllipse) { 266 | if ((matrixScale.x > 0 && matrixScale.y < 0) || 267 | (matrixScale.x < 0 && matrixScale.y > 0)) { 268 | clockwiseFlag = clockwiseFlag ^ 1; 269 | } 270 | result += `A ${roundTo4Places(Math.abs(newEllipse.radiusX))} ` + 271 | `${roundTo4Places(Math.abs(newEllipse.radiusY))} ` + 272 | `${roundTo4Places(newEllipse.rotation)} ${largeArcFlag} ` + 273 | `${clockwiseFlag} ${getString(current)}`; 274 | } else { 275 | result += `L ${getString(current)}`; 276 | } 277 | } 278 | break; 279 | case 'z': 280 | // Close path 281 | result += `Z `; 282 | // Correctly handle relative m commands, see paper.js#1101: 283 | current = start; 284 | break; 285 | } 286 | previous = lower; 287 | } 288 | return result; 289 | }; 290 | 291 | const GRAPHICS_ELEMENTS = ['circle', 'ellipse', 'image', 'line', 'path', 'polygon', 'polyline', 'rect', 'text', 'use']; 292 | const CONTAINER_ELEMENTS = ['a', 'defs', 'g', 'marker', 'glyph', 'missing-glyph', 'pattern', 'svg', 'switch', 'symbol']; 293 | const _isContainerElement = function (element) { 294 | return element.tagName && CONTAINER_ELEMENTS.includes(element.tagName.toLowerCase()); 295 | }; 296 | const _isGraphicsElement = function (element) { 297 | return element.tagName && GRAPHICS_ELEMENTS.includes(element.tagName.toLowerCase()); 298 | }; 299 | const _isPathWithTransformAndStroke = function (element, strokeWidth) { 300 | if (!element.attributes) return false; 301 | strokeWidth = element.attributes['stroke-width'] ? 302 | Number(element.attributes['stroke-width'].value) : Number(strokeWidth); 303 | return strokeWidth && 304 | element.tagName && element.tagName.toLowerCase() === 'path' && 305 | element.attributes.d && element.attributes.d.value; 306 | }; 307 | const _quadraticMean = function (a, b) { 308 | return Math.sqrt(((a * a) + (b * b)) / 2); 309 | }; 310 | 311 | const _createGradient = function (gradientId, svgTag, bbox, matrix) { 312 | // Adapted from Paper.js's SvgImport.getValue 313 | const getValue = function (node, name, isString, allowNull, allowPercent, defaultValue) { 314 | // Interpret value as number. Never return NaN, but 0 instead. 315 | // If the value is a sequence of numbers, parseFloat will 316 | // return the first occurring number, which is enough for now. 317 | let value = SvgElement.get(node, name); 318 | let res; 319 | if (value === null) { 320 | if (defaultValue) { 321 | res = defaultValue; 322 | if (/%\s*$/.test(res)) { 323 | value = defaultValue; 324 | res = parseFloat(value); 325 | } 326 | } else if (allowNull) { 327 | res = null; 328 | } else if (isString) { 329 | res = ''; 330 | } else { 331 | res = 0; 332 | } 333 | } else if (isString) { 334 | res = value; 335 | } else { 336 | res = parseFloat(value); 337 | } 338 | // Support for dimensions in percentage of the root size. If root-size 339 | // is not set (e.g. during ), just scale the percentage value to 340 | // 0..1, as required by gradients with gradientUnits="objectBoundingBox" 341 | if (/%\s*$/.test(value)) { 342 | const size = allowPercent ? 1 : bbox[/x|^width/.test(name) ? 'width' : 'height']; 343 | return res / 100 * size; 344 | } 345 | return res; 346 | }; 347 | const getPoint = function (node, x, y, allowNull, allowPercent, defaultX, defaultY) { 348 | x = getValue(node, x || 'x', false, allowNull, allowPercent, defaultX); 349 | y = getValue(node, y || 'y', false, allowNull, allowPercent, defaultY); 350 | return allowNull && (x === null || y === null) ? null : {x, y}; 351 | }; 352 | 353 | let defs = svgTag.getElementsByTagName('defs'); 354 | if (defs.length === 0) { 355 | defs = SvgElement.create('defs'); 356 | svgTag.appendChild(defs); 357 | } else { 358 | defs = defs[0]; 359 | } 360 | 361 | // Clone the old gradient. We'll make a new one, since the gradient might be reused elsewhere 362 | // with different transform matrix 363 | const oldGradient = svgTag.getElementById(gradientId); 364 | if (!oldGradient) return; 365 | 366 | const radial = oldGradient.tagName.toLowerCase() === 'radialgradient'; 367 | const newGradient = svgTag.getElementById(gradientId).cloneNode(true /* deep */); 368 | 369 | // Give the new gradient a new ID 370 | let matrixString = Matrix.toString(matrix); 371 | matrixString = matrixString.substring(8, matrixString.length - 1); 372 | const newGradientId = `${gradientId}-${matrixString}`; 373 | newGradient.setAttribute('id', newGradientId); 374 | 375 | // This gradient already exists and was transformed before. Just reuse the already-transformed one. 376 | if (svgTag.getElementById(newGradientId)) { 377 | // This is the same code as in the end of the function, but I don't feel like wrapping the next 80 lines 378 | // in an `if (!svgTag.getElementById(newGradientId))` block 379 | return `url(#${newGradientId})`; 380 | } 381 | 382 | const scaleToBounds = getValue(newGradient, 'gradientUnits', true) !== 383 | 'userSpaceOnUse'; 384 | let origin; 385 | let destination; 386 | let radius; 387 | let focal; 388 | if (radial) { 389 | origin = getPoint(newGradient, 'cx', 'cy', false, scaleToBounds, '50%', '50%'); 390 | radius = getValue(newGradient, 'r', false, false, scaleToBounds, '50%'); 391 | focal = getPoint(newGradient, 'fx', 'fy', true, scaleToBounds); 392 | } else { 393 | origin = getPoint(newGradient, 'x1', 'y1', false, scaleToBounds); 394 | destination = getPoint(newGradient, 'x2', 'y2', false, scaleToBounds, '1'); 395 | if (origin.x === destination.x && origin.y === destination.y) { 396 | // If it's degenerate, use the color of the last stop, as described by 397 | // https://www.w3.org/TR/SVG/pservers.html#LinearGradientNotes 398 | const stops = newGradient.getElementsByTagName('stop'); 399 | if (!stops.length || !stops[stops.length - 1].attributes || 400 | !stops[stops.length - 1].attributes['stop-color']) { 401 | return null; 402 | } 403 | return stops[stops.length - 1].attributes['stop-color'].value; 404 | } 405 | } 406 | 407 | // Transform points 408 | // Emulate SVG's gradientUnits="objectBoundingBox" 409 | if (scaleToBounds) { 410 | const boundsMatrix = Matrix.compose(Matrix.translate(bbox.x, bbox.y), Matrix.scale(bbox.width, bbox.height)); 411 | origin = Matrix.applyToPoint(boundsMatrix, origin); 412 | if (destination) destination = Matrix.applyToPoint(boundsMatrix, destination); 413 | if (radius) { 414 | radius = _quadraticMean(bbox.width, bbox.height) * radius; 415 | } 416 | if (focal) focal = Matrix.applyToPoint(boundsMatrix, focal); 417 | } 418 | 419 | if (radial) { 420 | origin = Matrix.applyToPoint(matrix, origin); 421 | const matrixScale = _getScaleFactor(matrix); 422 | radius = _quadraticMean(matrixScale.x, matrixScale.y) * radius; 423 | if (focal) focal = Matrix.applyToPoint(matrix, focal); 424 | } else { 425 | const dot = (a, b) => (a.x * b.x) + (a.y * b.y); 426 | const multiply = (coefficient, v) => ({x: coefficient * v.x, y: coefficient * v.y}); 427 | const add = (a, b) => ({x: a.x + b.x, y: a.y + b.y}); 428 | const subtract = (a, b) => ({x: a.x - b.x, y: a.y - b.y}); 429 | 430 | // The line through origin and gradientPerpendicular is the line at which the gradient starts 431 | let gradientPerpendicular = Math.abs(origin.x - destination.x) < 1e-8 ? 432 | add(origin, {x: 1, y: (origin.x - destination.x) / (destination.y - origin.y)}) : 433 | add(origin, {x: (destination.y - origin.y) / (origin.x - destination.x), y: 1}); 434 | 435 | // Transform points 436 | gradientPerpendicular = Matrix.applyToPoint(matrix, gradientPerpendicular); 437 | origin = Matrix.applyToPoint(matrix, origin); 438 | destination = Matrix.applyToPoint(matrix, destination); 439 | 440 | // Calculate the direction that the gradient has changed to 441 | const originToPerpendicular = subtract(gradientPerpendicular, origin); 442 | const originToDestination = subtract(destination, origin); 443 | const gradientDirection = Math.abs(originToPerpendicular.x) < 1e-8 ? 444 | {x: 1, y: -originToPerpendicular.x / originToPerpendicular.y} : 445 | {x: -originToPerpendicular.y / originToPerpendicular.x, y: 1}; 446 | 447 | // Set the destination so that the gradient moves in the correct direction, by projecting the destination vector 448 | // onto the gradient direction vector 449 | const projectionCoeff = dot(originToDestination, gradientDirection) / dot(gradientDirection, gradientDirection); 450 | const projection = multiply(projectionCoeff, gradientDirection); 451 | destination = {x: origin.x + projection.x, y: origin.y + projection.y}; 452 | } 453 | 454 | // Put values back into svg 455 | if (radial) { 456 | newGradient.setAttribute('cx', Number(origin.x.toFixed(4))); 457 | newGradient.setAttribute('cy', Number(origin.y.toFixed(4))); 458 | newGradient.setAttribute('r', Number(radius.toFixed(4))); 459 | if (focal) { 460 | newGradient.setAttribute('fx', Number(focal.x.toFixed(4))); 461 | newGradient.setAttribute('fy', Number(focal.y.toFixed(4))); 462 | } 463 | } else { 464 | newGradient.setAttribute('x1', Number(origin.x.toFixed(4))); 465 | newGradient.setAttribute('y1', Number(origin.y.toFixed(4))); 466 | newGradient.setAttribute('x2', Number(destination.x.toFixed(4))); 467 | newGradient.setAttribute('y2', Number(destination.y.toFixed(4))); 468 | } 469 | newGradient.setAttribute('gradientUnits', 'userSpaceOnUse'); 470 | defs.appendChild(newGradient); 471 | 472 | return `url(#${newGradientId})`; 473 | }; 474 | 475 | // Adapted from paper.js's SvgImport.getDefinition 476 | const _parseUrl = (value, windowRef) => { 477 | // When url() comes from a style property, '#'' seems to be missing on 478 | // WebKit. We also get variations of quotes or no quotes, single or 479 | // double, so handle it all with one regular expression: 480 | const match = value && value.match(/\((?:["'#]*)([^"')]+)/); 481 | const name = match && match[1]; 482 | const res = name && windowRef ? 483 | // This is required by Firefox, which can produce absolute 484 | // urls for local gradients, see paperjs#1001: 485 | name.replace(`${windowRef.location.href.split('#')[0]}#`, '') : 486 | name; 487 | return res; 488 | }; 489 | 490 | /** 491 | * Scratch 2.0 displays stroke widths in a "normalized" way, that is, 492 | * if a shape with a stroke width has a transform applied, it will be 493 | * rendered with a stroke that is the same width all the way around, 494 | * instead of stretched looking. 495 | * 496 | * The vector paint editor also prefers to normalize the stroke width, 497 | * rather than keep track of transforms at the group level, as this 498 | * simplifies editing (e.g. stroke width 3 always means the same thickness) 499 | * 500 | * This function performs that normalization process, pushing transforms 501 | * on groups down to the leaf level and averaging out the stroke width 502 | * around the shapes. Note that this doens't just change stroke widths, it 503 | * changes path data and attributes throughout the SVG. 504 | * 505 | * @param {SVGElement} svgTag The SVG dom object 506 | * @param {Window} windowRef The window to use. Need to pass in for 507 | * tests to work, as they get angry at even the mention of window. 508 | * @param {object} bboxForTesting The bounds to use. Need to pass in for 509 | * tests only, because getBBox doesn't work in Node. This should 510 | * be the bounds of the svgTag without including stroke width or transforms. 511 | * @return {void} 512 | */ 513 | const transformStrokeWidths = function (svgTag, windowRef, bboxForTesting) { 514 | const inherited = Matrix.identity(); 515 | 516 | const applyTransforms = (element, matrix, strokeWidth, fill, stroke) => { 517 | if (_isContainerElement(element)) { 518 | // Push fills and stroke width down to leaves 519 | if (element.attributes['stroke-width']) { 520 | strokeWidth = element.attributes['stroke-width'].value; 521 | } 522 | if (element.attributes) { 523 | if (element.attributes.fill) fill = element.attributes.fill.value; 524 | if (element.attributes.stroke) stroke = element.attributes.stroke.value; 525 | } 526 | 527 | // If any child nodes don't take attributes, leave the attributes 528 | // at the parent level. 529 | for (let i = 0; i < element.childNodes.length; i++) { 530 | applyTransforms( 531 | element.childNodes[i], 532 | Matrix.compose(matrix, _parseTransform(element)), 533 | strokeWidth, 534 | fill, 535 | stroke 536 | ); 537 | } 538 | element.removeAttribute('transform'); 539 | element.removeAttribute('stroke-width'); 540 | element.removeAttribute('fill'); 541 | element.removeAttribute('stroke'); 542 | } else if (_isPathWithTransformAndStroke(element, strokeWidth)) { 543 | if (element.attributes['stroke-width']) { 544 | strokeWidth = element.attributes['stroke-width'].value; 545 | } 546 | if (element.attributes.fill) fill = element.attributes.fill.value; 547 | if (element.attributes.stroke) stroke = element.attributes.stroke.value; 548 | matrix = Matrix.compose(matrix, _parseTransform(element)); 549 | if (Matrix.toString(matrix) === Matrix.toString(Matrix.identity())) { 550 | element.removeAttribute('transform'); 551 | element.setAttribute('stroke-width', strokeWidth); 552 | if (fill) element.setAttribute('fill', fill); 553 | if (stroke) element.setAttribute('stroke', stroke); 554 | return; 555 | } 556 | 557 | // Transform gradient 558 | const fillGradientId = _parseUrl(fill, windowRef); 559 | const strokeGradientId = _parseUrl(stroke, windowRef); 560 | 561 | if (fillGradientId || strokeGradientId) { 562 | const doc = windowRef.document; 563 | // Need path bounds to transform gradient 564 | const svgSpot = doc.createElement('span'); 565 | let bbox; 566 | if (bboxForTesting) { 567 | bbox = bboxForTesting; 568 | } else { 569 | try { 570 | doc.body.appendChild(svgSpot); 571 | const svg = SvgElement.set(doc.createElementNS(SvgElement.svg, 'svg')); 572 | const path = SvgElement.set(doc.createElementNS(SvgElement.svg, 'path')); 573 | path.setAttribute('d', element.attributes.d.value); 574 | svg.appendChild(path); 575 | svgSpot.appendChild(svg); 576 | // Take the bounding box. 577 | bbox = svg.getBBox(); 578 | } finally { 579 | // Always destroy the element, even if, for example, getBBox throws. 580 | doc.body.removeChild(svgSpot); 581 | } 582 | } 583 | 584 | if (fillGradientId) { 585 | const newFillRef = _createGradient(fillGradientId, svgTag, bbox, matrix); 586 | if (newFillRef) fill = newFillRef; 587 | } 588 | 589 | if (strokeGradientId) { 590 | const newStrokeRef = _createGradient(strokeGradientId, svgTag, bbox, matrix); 591 | if (newStrokeRef) stroke = newStrokeRef; 592 | } 593 | } 594 | 595 | // Transform path data 596 | element.setAttribute('d', _transformPath(element.attributes.d.value, matrix)); 597 | element.removeAttribute('transform'); 598 | 599 | // Transform stroke width 600 | const matrixScale = _getScaleFactor(matrix); 601 | element.setAttribute('stroke-width', _quadraticMean(matrixScale.x, matrixScale.y) * strokeWidth); 602 | if (fill) element.setAttribute('fill', fill); 603 | if (stroke) element.setAttribute('stroke', stroke); 604 | } else if (_isGraphicsElement(element)) { 605 | // Push stroke width, fill, and stroke down to leaves 606 | if (strokeWidth && !element.attributes['stroke-width']) { 607 | element.setAttribute('stroke-width', strokeWidth); 608 | } 609 | if (fill && !element.attributes.fill) { 610 | element.setAttribute('fill', fill); 611 | } 612 | if (stroke && !element.attributes.stroke) { 613 | element.setAttribute('stroke', stroke); 614 | } 615 | 616 | // Push transform down to leaves 617 | matrix = Matrix.compose(matrix, _parseTransform(element)); 618 | if (Matrix.toString(matrix) === Matrix.toString(Matrix.identity())) { 619 | element.removeAttribute('transform'); 620 | } else { 621 | element.setAttribute('transform', Matrix.toString(matrix)); 622 | } 623 | } 624 | }; 625 | applyTransforms(svgTag, inherited, 1 /* default SVG stroke width */); 626 | }; 627 | 628 | module.exports = transformStrokeWidths; 629 | -------------------------------------------------------------------------------- /src/util/log.js: -------------------------------------------------------------------------------- 1 | const minilog = require('minilog'); 2 | minilog.enable(); 3 | 4 | module.exports = minilog('scratch-svg-render'); 5 | -------------------------------------------------------------------------------- /test/bitmapAdapter_getResized.js: -------------------------------------------------------------------------------- 1 | // Test getResizedWidthHeight function of bitmap adapter class 2 | 3 | const test = require('tap').test; 4 | const BitmapAdapter = require('../src/bitmap-adapter'); 5 | 6 | test('zero', t => { 7 | const bitmapAdapter = new BitmapAdapter(); 8 | const size = bitmapAdapter.getResizedWidthHeight(0, 0); 9 | t.equals(0, size.width); 10 | t.equals(0, size.height); 11 | t.end(); 12 | }); 13 | 14 | // Double (as if it is bitmap resolution 1) 15 | test('smallImg', t => { 16 | const bitmapAdapter = new BitmapAdapter(); 17 | const size = bitmapAdapter.getResizedWidthHeight(50, 50); 18 | t.equals(100, size.width); 19 | t.equals(100, size.height); 20 | t.end(); 21 | }); 22 | 23 | // Double (as if it is bitmap resolution 1) 24 | test('stageSizeImage', t => { 25 | const bitmapAdapter = new BitmapAdapter(); 26 | const size = bitmapAdapter.getResizedWidthHeight(480, 360); 27 | t.equals(960, size.width); 28 | t.equals(720, size.height); 29 | t.end(); 30 | }); 31 | 32 | // Don't resize 33 | test('mediumHeightImage', t => { 34 | const bitmapAdapter = new BitmapAdapter(); 35 | const size = bitmapAdapter.getResizedWidthHeight(50, 700); 36 | t.equals(50, size.width); 37 | t.equals(700, size.height); 38 | t.end(); 39 | }); 40 | 41 | // Don't resize 42 | test('mediumWidthImage', t => { 43 | const bitmapAdapter = new BitmapAdapter(); 44 | const size = bitmapAdapter.getResizedWidthHeight(700, 50); 45 | t.equals(700, size.width); 46 | t.equals(50, size.height); 47 | t.end(); 48 | }); 49 | 50 | // Don't resize 51 | test('mediumImage', t => { 52 | const bitmapAdapter = new BitmapAdapter(); 53 | const size = bitmapAdapter.getResizedWidthHeight(700, 700); 54 | t.equals(700, size.width); 55 | t.equals(700, size.height); 56 | t.end(); 57 | }); 58 | 59 | // Don't resize 60 | test('doubleStageSizeImage', t => { 61 | const bitmapAdapter = new BitmapAdapter(); 62 | const size = bitmapAdapter.getResizedWidthHeight(960, 720); 63 | t.equals(960, size.width); 64 | t.equals(720, size.height); 65 | t.end(); 66 | }); 67 | 68 | // Fit to stage width 69 | test('wideImage', t => { 70 | const bitmapAdapter = new BitmapAdapter(); 71 | const size = bitmapAdapter.getResizedWidthHeight(1000, 50); 72 | t.equals(960, size.width); 73 | t.equals(960 / 1000 * 50, size.height); 74 | t.end(); 75 | }); 76 | 77 | // Fit to stage height 78 | test('tallImage', t => { 79 | const bitmapAdapter = new BitmapAdapter(); 80 | const size = bitmapAdapter.getResizedWidthHeight(50, 1000); 81 | t.equals(720, size.height); 82 | t.equals(720 / 1000 * 50, size.width); 83 | t.end(); 84 | }); 85 | 86 | // Fit to stage height 87 | test('largeImageHeightConstraint', t => { 88 | const bitmapAdapter = new BitmapAdapter(); 89 | const size = bitmapAdapter.getResizedWidthHeight(1000, 1000); 90 | t.equals(720, size.height); 91 | t.equals(720 / 1000 * 1000, size.width); 92 | t.end(); 93 | }); 94 | 95 | // Fit to stage width 96 | test('largeImageWidthConstraint', t => { 97 | const bitmapAdapter = new BitmapAdapter(); 98 | const size = bitmapAdapter.getResizedWidthHeight(2000, 1000); 99 | t.equals(960, size.width); 100 | t.equals(960 / 2000 * 1000, size.height); 101 | t.end(); 102 | }); 103 | -------------------------------------------------------------------------------- /test/fixtures/css-import.sanitized.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /test/fixtures/css-import.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /test/fixtures/embedded-cat-foo.sanitized.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /test/fixtures/embedded-cat-foo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /test/fixtures/embedded-cat-xlink.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /test/fixtures/hearts.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /test/fixtures/metadata-body.svg: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | stuff inside 6 | 7 | -------------------------------------------------------------------------------- /test/fixtures/metadata-onload.sanitized.svg: -------------------------------------------------------------------------------- 1 | 2 | ad="alert('from the svg')"> 3 | 4 | -------------------------------------------------------------------------------- /test/fixtures/metadata-onload.svg: -------------------------------------------------------------------------------- 1 | 5 | ad="alert('from the svg')"> 7 | 8 | -------------------------------------------------------------------------------- /test/fixtures/onload-script.svg: -------------------------------------------------------------------------------- 1 | 5 | ad="alert('from the svg')"> 7 | 8 | -------------------------------------------------------------------------------- /test/fixtures/red-and-white-carousel-pound-in-href.sanitized.svg: -------------------------------------------------------------------------------- 1 | 2 | red and white carousel 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | image/svg+xml 25 | 26 | Layer 1 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /test/fixtures/red-and-white-carousel-pound-in-href.svg: -------------------------------------------------------------------------------- 1 | 2 | red and white carousel 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | image/svg+xml 25 | 26 | Layer 1 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /test/fixtures/reserved-namespace.sanitized.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /test/fixtures/reserved-namespace.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /test/fixtures/scratch_cat_bitmap_within_svg.sanitized.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /test/fixtures/scratch_cat_bitmap_within_svg.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /test/fixtures/script.sanitized.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /test/fixtures/script.svg: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 8 | 9 | -------------------------------------------------------------------------------- /test/fixtures/svg-tag-prefixes.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | image/svg+xml 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /test/fixup-svg-string.js: -------------------------------------------------------------------------------- 1 | const test = require('tap').test; 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | const DOMParser = require('xmldom').DOMParser; 5 | const fixupSvgString = require('../src/fixup-svg-string'); 6 | 7 | // The browser DOMParser throws on errors by default, replicate that here 8 | // by customizing the error callback to throw (defaults to logging) 9 | const domParser = new DOMParser({ 10 | errorHandler: { 11 | error: e => { 12 | throw new Error(e); 13 | } 14 | } 15 | }); 16 | 17 | test('fixupSvgString should make parsing fixtures not throw', t => { 18 | const filePath = path.resolve(__dirname, './fixtures/hearts.svg'); 19 | const svgString = fs.readFileSync(filePath) 20 | .toString(); 21 | const fixed = fixupSvgString(svgString); 22 | 23 | // Make sure undefineds aren't being written into the file 24 | t.equal(fixed.indexOf('undefined'), -1); 25 | t.notThrow(() => { 26 | domParser.parseFromString(fixed, 'text/xml'); 27 | }); 28 | t.end(); 29 | }); 30 | 31 | test('fixupSvgString should correct namespace declarations bound to reserved namespace names', t => { 32 | const filePath = path.resolve(__dirname, './fixtures/reserved-namespace.svg'); 33 | const svgString = fs.readFileSync(filePath) 34 | .toString(); 35 | const fixed = fixupSvgString(svgString); 36 | 37 | // Make sure undefineds aren't being written into the file 38 | t.equal(fixed.indexOf('undefined'), -1); 39 | t.notThrow(() => { 40 | domParser.parseFromString(fixed, 'text/xml'); 41 | }); 42 | t.end(); 43 | }); 44 | 45 | test('fixupSvgString shouldn\'t correct non-attributes', t => { 46 | const dontFix = fixupSvgString('xmlns:test="http://www/w3.org/XML/1998/namespace" is not an xmlns attribute'); 47 | 48 | t.notEqual(dontFix.indexOf('http://www/w3.org/XML/1998/namespace'), -1); 49 | t.end(); 50 | }); 51 | 52 | test('fixupSvgString should strip `svg:` prefix from tag names', t => { 53 | const filePath = path.resolve(__dirname, './fixtures/svg-tag-prefixes.svg'); 54 | const svgString = fs.readFileSync(filePath) 55 | .toString(); 56 | const fixed = fixupSvgString(svgString); 57 | 58 | const checkPrefixes = element => { 59 | t.notEqual(element.prefix, 'svg'); 60 | // JSDOM doesn't have element.children, only element.childNodes 61 | if (element.childNodes) { 62 | // JSDOM's childNodes is not iterable, so for...of cannot be used here 63 | for (let i = 0; i < element.childNodes.length; i++) { 64 | const child = element.childNodes[i]; 65 | if (child.nodeType === 1 /* Node.ELEMENT_NODE */) checkPrefixes(child); 66 | } 67 | } 68 | }; 69 | 70 | // Make sure undefineds aren't being written into the file 71 | t.equal(fixed.indexOf('undefined'), -1); 72 | t.notThrow(() => { 73 | domParser.parseFromString(fixed, 'text/xml'); 74 | }); 75 | 76 | checkPrefixes(domParser.parseFromString(fixed, 'text/xml')); 77 | 78 | t.end(); 79 | }); 80 | 81 | test('fixupSvgString should empty script tags', t => { 82 | const filePath = path.resolve(__dirname, './fixtures/script.svg'); 83 | const svgString = fs.readFileSync(filePath) 84 | .toString(); 85 | const fixed = fixupSvgString(svgString); 86 | // Script tag should remain but have no contents. 87 | t.equals(fixed.indexOf(''), 207); 88 | // The contents of the script tag (e.g. the alert) are no longer there. 89 | t.equals(fixed.indexOf('stuff inside'), -1); 90 | t.end(); 91 | }); 92 | 93 | test('fixupSvgString should empty script tags in onload', t => { 94 | const filePath = path.resolve(__dirname, './fixtures/onload-script.svg'); 95 | const svgString = fs.readFileSync(filePath) 96 | .toString(); 97 | const fixed = fixupSvgString(svgString); 98 | // Script tag should remain but have no contents. 99 | t.equals(fixed.indexOf(''), 792); 100 | t.end(); 101 | }); 102 | 103 | test('fixupSvgString strips contents of metadata', t => { 104 | const filePath = path.resolve(__dirname, './fixtures/metadata-body.svg'); 105 | const svgString = fs.readFileSync(filePath) 106 | .toString(); 107 | const fixed = fixupSvgString(svgString); 108 | // Metadata tag should still exist, it'll just be empty. 109 | t.equals(fixed.indexOf(''), 207); 110 | // The contents of the metadata tag are gone. 111 | t.equals(fixed.indexOf('stuff inside'), -1); 112 | t.end(); 113 | }); 114 | 115 | test('fixupSvgString strips contents of metadata in onload', t => { 116 | const filePath = path.resolve(__dirname, './fixtures/metadata-onload.svg'); 117 | const svgString = fs.readFileSync(filePath) 118 | .toString(); 119 | const fixed = fixupSvgString(svgString); 120 | // Metadata tag should still exist, it'll just be empty. 121 | t.equals(fixed.indexOf(''), 800); 122 | t.end(); 123 | }); 124 | 125 | test('fixupSvgString should correct invalid mime type', t => { 126 | const filePath = path.resolve(__dirname, './fixtures/invalid-cloud.svg'); 127 | const svgString = fs.readFileSync(filePath, 'utf8'); 128 | const fixed = fixupSvgString(svgString); 129 | 130 | // Make sure we replace an invalid mime type from Photoshop exported SVGs 131 | t.notEqual(svgString.indexOf('img/png'), -1); 132 | t.equal(fixed.indexOf('img/png'), -1); 133 | t.notThrow(() => { 134 | domParser.parseFromString(fixed, 'text/xml'); 135 | }); 136 | t.end(); 137 | }); 138 | 139 | test('fixupSvgString shouldn\'t correct non-image tags', t => { 140 | const dontFix = fixupSvgString('data:img/png is not a mime type'); 141 | 142 | t.notEqual(dontFix.indexOf('img/png'), -1); 143 | t.end(); 144 | }); 145 | -------------------------------------------------------------------------------- /test/sanitize-svg.js: -------------------------------------------------------------------------------- 1 | const test = require('tap').test; 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | 5 | const sanitizeSvg = require('../src/sanitize-svg'); 6 | 7 | // find all svg fixtures with filenames ending '.sanitized.svg', and compare their 8 | // content to the result when we run sanitizeSvg.sanitizeSvgText() on the raw 9 | // versions 10 | test('compare svg content before and after sanitize-svg sanitizes it', t => { 11 | const dirPath = path.resolve(__dirname, './fixtures/'); 12 | const fixtureFilenames = fs.readdirSync(dirPath); 13 | // for simplicity, we'll call those existing '.sanitized.svg' files "correct" 14 | const correctSvgFilenames = []; 15 | fixtureFilenames.forEach(filename => { 16 | if (/^.*.sanitized.svg$/.test(filename)) { 17 | correctSvgFilenames.push(filename); 18 | } 19 | }); 20 | correctSvgFilenames.forEach(correctSvgFilename => { 21 | // load raw svg content and run it through sanitizeSvg.sanitizeSvgText() 22 | const rawSvgFilename = correctSvgFilename.replace('.sanitized.svg', '.svg'); 23 | const rawSvgFilePath = path.resolve(__dirname, `./fixtures/${rawSvgFilename}`); 24 | const rawSvgString = fs.readFileSync(rawSvgFilePath).toString(); 25 | const testSanitizedSvgString = sanitizeSvg.sanitizeSvgText(rawSvgString); 26 | 27 | // load "correct" content 28 | const correctSvgFilePath = path.resolve(__dirname, `./fixtures/${correctSvgFilename}`); 29 | const correctSvgString = fs.readFileSync(correctSvgFilePath).toString(); 30 | 31 | t.equals(testSanitizedSvgString, correctSvgString); 32 | }); 33 | t.end(); 34 | }); 35 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | const CopyWebpackPlugin = require('copy-webpack-plugin'); 2 | const path = require('path'); 3 | const ScratchWebpackConfigBuilder = require('scratch-webpack-configuration'); 4 | 5 | const common = { 6 | libraryName: 'scratch-svg-renderer', 7 | rootPath: path.resolve(__dirname) 8 | }; 9 | 10 | /** 11 | * @type {import('webpack').Configuration} 12 | */ 13 | const nodeConfig = new ScratchWebpackConfigBuilder(common) 14 | .setTarget('node') 15 | .merge({ 16 | output: { 17 | library: { 18 | name: 'ScratchSVGRenderer', 19 | type: 'umd' 20 | } 21 | } 22 | }) 23 | .get(); 24 | 25 | /** 26 | * @type {import('webpack').Configuration} 27 | */ 28 | const webConfig = new ScratchWebpackConfigBuilder(common) 29 | .setTarget('browserslist') 30 | .merge({ 31 | output: { 32 | library: { 33 | name: 'ScratchSVGRenderer', 34 | type: 'umd' 35 | } 36 | } 37 | }) 38 | .get(); 39 | 40 | /** 41 | * @type {import('webpack').Configuration} 42 | */ 43 | const playgroundConfig = new ScratchWebpackConfigBuilder(common) 44 | .setTarget('browserslist') 45 | .merge({ 46 | devServer: { 47 | contentBase: false, 48 | port: process.env.PORT || 8576 49 | }, 50 | output: { 51 | path: path.resolve(__dirname, 'playground'), 52 | library: { 53 | name: 'ScratchSVGRenderer', 54 | type: 'umd' 55 | }, 56 | publicPath: '/' 57 | } 58 | }) 59 | .addPlugin( 60 | new CopyWebpackPlugin([ 61 | { 62 | from: 'src/playground' 63 | } 64 | ]) 65 | ) 66 | .get(); 67 | 68 | module.exports = [ 69 | nodeConfig, 70 | webConfig, 71 | playgroundConfig 72 | ]; 73 | --------------------------------------------------------------------------------