├── .eslintignore ├── .eslintrc.cjs ├── .github └── workflows │ ├── deploy.yml │ └── playwright.yml ├── .gitignore ├── .npmrc ├── .prettierignore ├── .prettierrc ├── LICENSE ├── README.md ├── package.json ├── playwright.config.ts ├── playwright ├── index.html └── index.ts ├── pnpm-lock.yaml ├── src ├── app.d.ts ├── app.html ├── lib │ ├── Html.svelte │ ├── Renderer.svelte │ ├── SvgRenderer.svelte │ ├── index.ts │ ├── load.ts │ ├── parse.ts │ ├── types.ts │ └── utils.ts └── routes │ ├── +layout.svelte │ ├── +layout.ts │ ├── +page.svelte │ ├── GithubCorner.svelte │ ├── components │ ├── Test.svelte │ └── Textarea.svelte │ ├── parse-on-server │ ├── +page.server.ts │ ├── +page.svelte │ └── +page.ts │ ├── readme │ ├── 1 │ │ ├── +page.svelte │ │ └── Paragraph.svelte │ ├── 2 │ │ └── +page.svelte │ ├── 3 │ │ └── +page.svelte │ ├── 4 │ │ └── +page.svelte │ ├── 5 │ │ ├── +page.svelte │ │ └── Span.svelte │ ├── 6 │ │ ├── +page.server.ts │ │ ├── +page.svelte │ │ ├── +page.ts │ │ └── components │ │ │ └── Button.svelte │ ├── 7 │ │ ├── +page.svelte │ │ ├── Button.svelte │ │ ├── Card.svelte │ │ └── CardWrapper.svelte │ ├── +layout.svelte │ └── +page.svelte │ ├── svg │ ├── +page.svelte │ ├── Group.svelte │ └── Rect.svelte │ └── tests │ ├── +page.server.ts │ ├── +page.svelte │ └── +page.ts ├── static ├── logo.png └── logo.svg ├── svelte.config.js ├── tests ├── Html.spec.ts ├── Test.svelte ├── data.ts └── parse.spec.ts ├── tsconfig.json └── vite.config.ts /.eslintignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | /build 4 | /dist 5 | /.svelte-kit 6 | .env 7 | .env.* 8 | !.env.example 9 | 10 | /playwright/ 11 | /playwright-report/ 12 | /blob-report/ 13 | /test-results/ 14 | 15 | # Ignore files for PNPM, NPM and YARN 16 | pnpm-lock.yaml 17 | package-lock.json 18 | yarn.lock 19 | -------------------------------------------------------------------------------- /.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | /** @type { import("eslint").Linter.Config } */ 2 | module.exports = { 3 | root: true, 4 | extends: [ 5 | 'eslint:recommended', 6 | 'plugin:@typescript-eslint/recommended', 7 | 'plugin:svelte/recommended', 8 | 'prettier' 9 | ], 10 | parser: '@typescript-eslint/parser', 11 | plugins: ['@typescript-eslint'], 12 | parserOptions: { 13 | sourceType: 'module', 14 | ecmaVersion: 2020, 15 | extraFileExtensions: ['.svelte'] 16 | }, 17 | env: { 18 | browser: true, 19 | es2017: true, 20 | node: true 21 | }, 22 | overrides: [ 23 | { 24 | files: ['*.svelte'], 25 | parser: 'svelte-eslint-parser', 26 | parserOptions: { 27 | parser: '@typescript-eslint/parser' 28 | } 29 | } 30 | ] 31 | }; 32 | -------------------------------------------------------------------------------- /.github/workflows/deploy.yml: -------------------------------------------------------------------------------- 1 | name: Deploy to GitHub Pages 2 | 3 | on: 4 | push: 5 | branches: [ main, master ] 6 | 7 | jobs: 8 | build_site: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - name: Checkout 12 | uses: actions/checkout@v3 13 | 14 | - name: Install pnpm 15 | uses: pnpm/action-setup@v2 16 | with: 17 | version: 8 18 | 19 | - name: Install Node.js 20 | uses: actions/setup-node@v3 21 | with: 22 | node-version: 18 23 | cache: pnpm 24 | 25 | - name: Install dependencies 26 | run: pnpm install 27 | 28 | - name: Build 29 | env: 30 | BASE_PATH: '/${{ github.event.repository.name }}' 31 | run: | 32 | pnpm build 33 | 34 | - name: Upload Artifacts 35 | uses: actions/upload-pages-artifact@v2 36 | with: 37 | path: 'build/' 38 | 39 | deploy: 40 | needs: build_site 41 | runs-on: ubuntu-latest 42 | 43 | permissions: 44 | pages: write 45 | id-token: write 46 | 47 | environment: 48 | name: github-pages 49 | url: ${{ steps.deployment.outputs.page_url }} 50 | 51 | steps: 52 | - name: Deploy 53 | id: deployment 54 | uses: actions/deploy-pages@v2 55 | -------------------------------------------------------------------------------- /.github/workflows/playwright.yml: -------------------------------------------------------------------------------- 1 | name: Playwright Tests 2 | 3 | on: 4 | push: 5 | branches: [ main, master ] 6 | 7 | pull_request: 8 | branches: [ main, master ] 9 | 10 | jobs: 11 | test: 12 | timeout-minutes: 60 13 | runs-on: ubuntu-latest 14 | steps: 15 | - name: Checkout 16 | uses: actions/checkout@v3 17 | 18 | - name: Install pnpm 19 | uses: pnpm/action-setup@v2 20 | with: 21 | version: 8 22 | 23 | - uses: actions/setup-node@v3 24 | with: 25 | node-version: 18 26 | cache: pnpm 27 | 28 | - name: Install dependencies 29 | run: pnpm install 30 | 31 | - name: Install Playwright Browsers 32 | run: pnpx playwright install --with-deps 33 | 34 | - name: Run Playwright tests 35 | run: pnpm test 36 | 37 | - uses: actions/upload-artifact@v3 38 | if: always() 39 | with: 40 | name: playwright-report 41 | path: playwright-report/ 42 | retention-days: 30 43 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | /build 4 | /dist 5 | /.svelte-kit 6 | .env 7 | .env.* 8 | !.env.example 9 | 10 | /playwright/.cache/ 11 | /playwright-report/ 12 | /blob-report/ 13 | /test-results/ 14 | 15 | vite.config.js.timestamp-* 16 | vite.config.ts.timestamp-* 17 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | engine-strict=true 2 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | /build 4 | /dist 5 | /.svelte-kit 6 | .env 7 | .env.* 8 | !.env.example 9 | 10 | /playwright/ 11 | /playwright-report/ 12 | /blob-report/ 13 | /test-results/ 14 | 15 | # Ignore files for PNPM, NPM and YARN 16 | pnpm-lock.yaml 17 | package-lock.json 18 | yarn.lock 19 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "useTabs": true, 3 | "singleQuote": true, 4 | "trailingComma": "all", 5 | "arrowParens": "avoid", 6 | "semi": true, 7 | "plugins": [ 8 | "prettier-plugin-svelte" 9 | ], 10 | "overrides": [ 11 | { 12 | "files": "*.svelte", 13 | "options": { 14 | "parser": "svelte" 15 | } 16 | } 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 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 | # html-svelte-parser Logo html-svelte-parser 2 | 3 | HTML to Svelte parser that works on both the server (Node.js) and the client (browser). 4 | 5 | To replace an element with a svelte component, check out the [`processNode`](#processnode) option. 6 | 7 | #### Example 8 | 9 | _Paragraph.svelte_ 10 | 11 | ```svelte 12 |

13 | ``` 14 | 15 | _App.svelte_ 16 | 17 | ```svelte 18 | 22 | 23 | { 26 | if (isTag(node) && node.name === 'p') { 27 | return { component: Paragraph }; 28 | } 29 | }} 30 | /> 31 | 32 | 37 | ``` 38 | 39 | --- 40 | 41 |
42 | Table of Contents 43 | 44 | - [Install](#install) 45 | - [Usage](#usage) 46 | - [processNode](#processnode) 47 | - [Modify/remove nodes](#modifyremove-nodes) 48 | - [Replace nodes](#replace-nodes) 49 | - [Usage with sveltekit](#usage-with-sveltekit) 50 | - [Named slots](#named-slots) 51 | - [Credits](#credits) 52 | 53 |
54 | 55 | ## Install 56 | 57 | Install the [NPM package _html-svelte-parser_](https://www.npmjs.com/package/html-svelte-parser) with your favorite package manager: 58 | 59 | ```sh 60 | npm install html-svelte-parser 61 | # pnpm add html-svelte-parser 62 | # yarn add html-svelte-parser 63 | ``` 64 | 65 | ## Usage 66 | 67 | ```svelte 68 | 71 | 72 | 73 | 74 | 75 | 76 |
    77 | 78 |
79 | 80 | 81 | 82 | 83 | 84 | `} 86 | /> 87 | ``` 88 | 89 | ### processNode 90 | 91 | The `processNode` option is a function that allows you to modify or remove a DOM node or replace it with a svelte component. It receives one argument which is [domhandler](https://github.com/fb55/domhandler)'s node (either [`Element`](https://github.com/fb55/domhandler/blob/88fb7a71446e221f5a09cd3c41713c51043be2a7/src/node.ts#L271) or [`Text`](https://github.com/fb55/domhandler/blob/88fb7a71446e221f5a09cd3c41713c51043be2a7/src/node.ts#L155)): 92 | 93 | ```svelte 94 | { 97 | console.dir(domNode, { depth: null }); 98 | }} 99 | /> 100 | ``` 101 | 102 | Console output: 103 | 104 | ```js 105 | Element { 106 | type: 'tag', 107 | parent: null, 108 | prev: null, 109 | next: null, 110 | startIndex: null, 111 | endIndex: null, 112 | children: [], 113 | name: 'br', 114 | attribs: {} 115 | } 116 | ``` 117 | 118 | #### Modify/remove nodes 119 | 120 | You can directly modify the DOM nodes or remove them by returning `false`: 121 | 122 | ```svelte 123 | 145 | 146 | 147 | 148 | 153 | ``` 154 | 155 | #### Replace nodes 156 | 157 | To replaced a DOM node with a svelte component return an object with a `component` property.\ 158 | Additionally the object can have a `props` property. 159 | 160 | _Span.svelte_ 161 | 162 | ```svelte 163 | 164 | ``` 165 | 166 | _App.svelte_ 167 | 168 | ```svelte 169 | 183 | 184 | 185 | 186 | 191 | ``` 192 | 193 | ### Usage with sveltekit 194 | 195 | `html-svelte-parser` exports more than just the `Html` component, which makes it possible to delegate the work of parsing and processing to the server. An added bonus, you ship less code to the client. 196 | 197 |
198 | Other files 199 | 200 | _components/Button.svelte_ 201 | 202 | ```svelte 203 | 210 | 211 | {#if href} 212 | 213 | {:else} 214 | 215 | {/if} 216 | ``` 217 | 218 |
219 | 220 | _+page.server.js_ 221 | 222 | ```js 223 | import { isTag, parse } from 'html-svelte-parser'; 224 | 225 | /** @type {import('./$types').PageServerLoad} */ 226 | export const load = () => { 227 | return { 228 | content: parse( 229 | `

Svelte rocks

`, 230 | { 231 | processNode(node) { 232 | if ( 233 | isTag(node) && 234 | node.name === 'a' && 235 | node.attribs.class?.split(/\s/).includes('btn') 236 | ) { 237 | // We use a `string` for the `component` property. 238 | return { component: 'Button', props: node.attribs }; 239 | } 240 | }, 241 | }, 242 | ), 243 | }; 244 | }; 245 | ``` 246 | 247 | _+page.js_ 248 | 249 | ```js 250 | import { loadComponents } from 'html-svelte-parser'; 251 | 252 | /** @type {import('./$types').PageLoad} */ 253 | export const load = ({ data }) => ({ 254 | content: loadComponents(data.content, componentName => { 255 | // `componentName` is the `component` we returned in `+page.server.js` 256 | return import(`./components/${componentName}.svelte`); 257 | }), 258 | }); 259 | ``` 260 | 261 | _+page.svelte_ 262 | 263 | ```svelte 264 | 270 | 271 | 272 | 273 | 278 | ``` 279 | 280 | ### Named slots 281 | 282 | What if your component has named slots? Unfortunately it is currently not possible to render named slots dynamically with svelte.\ 283 | Fortunately, we can work around the problem with a wrapper component and the `Renderer` component. 284 | 285 |
286 | Other files 287 | 288 | _Button.svelte_ 289 | 290 | ```svelte 291 | 298 | 299 | {#if href} 300 | 301 | {:else} 302 | 303 | {/if} 304 | ``` 305 | 306 | _Card.svelte_ 307 | 308 | ```svelte 309 |
310 | {#if $$slots.title} 311 |
312 | {/if} 313 | 314 |
315 | 316 | {#if $$slots.actions} 317 |
318 | {/if} 319 |
320 | ``` 321 | 322 |
323 | 324 | _CardWrapper.svelte_\ 325 | This is our wrapper component. 326 | 327 | ```svelte 328 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | ``` 348 | 349 | _App.svelte_ 350 | 351 | ```svelte 352 | 424 | 425 | 426 | 427 | 443 | ``` 444 | 445 | ## TODO 446 | 447 | - API docs 448 | - cleanup tests & more tests 449 | - GH page 450 | 451 | ## Credits 452 | 453 | - [html-dom-parser](https://github.com/remarkablemark/html-dom-parser) 454 | - [htmlparser2](https://github.com/fb55/htmlparser2) 455 | - [domhandler](https://github.com/fb55/domhandler) 456 | - [dom-serializer](https://github.com/cheeriojs/dom-serializer) 457 | 458 | Inspired by [html-react-parser](https://github.com/remarkablemark/html-react-parser) and [html-to-react](https://github.com/aknuds1/html-to-react). 459 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "html-svelte-parser", 3 | "description": "HTML to Svelte parser.", 4 | "version": "1.0.0", 5 | "license": "AGPL-3.0-only", 6 | "author": { 7 | "name": "Patrick Günther", 8 | "url": "https://patrick.id/" 9 | }, 10 | "repository": { 11 | "type": "git", 12 | "url": "https://github.com/PatrickG/html-svelte-parser.git" 13 | }, 14 | "bugs": { 15 | "url": "https://github.com/PatrickG/html-svelte-parser/issues" 16 | }, 17 | "keywords": [ 18 | "svelte", 19 | "svelte-parser", 20 | "html-svelte-parser", 21 | "html-to-svelte" 22 | ], 23 | "scripts": { 24 | "dev": "vite dev", 25 | "build": "vite build && pnpm package", 26 | "preview": "vite preview", 27 | "package": "svelte-kit sync && svelte-package && publint", 28 | "prepublishOnly": "pnpm package", 29 | "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", 30 | "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", 31 | "lint": "prettier --check . && eslint .", 32 | "format": "prettier --write .", 33 | "test": "playwright test -c playwright.config.ts" 34 | }, 35 | "exports": { 36 | "./Html.svelte": { 37 | "types": "./dist/Html.svelte.d.ts", 38 | "svelte": "./dist/Html.svelte", 39 | "default": "./dist/Html.svelte" 40 | }, 41 | "./Renderer.svelte": { 42 | "types": "./dist/Renderer.svelte.d.ts", 43 | "svelte": "./dist/Renderer.svelte", 44 | "default": "./dist/Renderer.svelte" 45 | }, 46 | ".": { 47 | "types": "./dist/index.d.ts", 48 | "svelte": "./dist/index.js", 49 | "default": "./dist/index.js" 50 | }, 51 | "./load": { 52 | "types": "./dist/load.d.ts", 53 | "default": "./dist/load.js" 54 | }, 55 | "./parse": { 56 | "types": "./dist/parse.d.ts", 57 | "default": "./dist/parse.js" 58 | }, 59 | "./types": { 60 | "types": "./dist/types.d.ts", 61 | "default": "./dist/types.js" 62 | } 63 | }, 64 | "typesVersions": { 65 | ">4.0": { 66 | "Html.svelte": [ 67 | "./dist/Html.svelte.d.ts" 68 | ], 69 | "Renderer.svelte": [ 70 | "./dist/Renderer.svelte.d.ts" 71 | ], 72 | "index.d.ts": [ 73 | "./dist/index.d.ts" 74 | ], 75 | "load": [ 76 | "./dist/load.d.ts" 77 | ], 78 | "parse": [ 79 | "./dist/parse.d.ts" 80 | ], 81 | "types": [ 82 | "./dist/types.d.ts" 83 | ] 84 | } 85 | }, 86 | "files": [ 87 | "dist", 88 | "!dist/**/*.test.*", 89 | "!dist/**/*.spec.*" 90 | ], 91 | "peerDependencies": { 92 | "svelte": "^3.47.0 || ^4.0.0 || ^5.0.0-next.0" 93 | }, 94 | "devDependencies": { 95 | "@playwright/experimental-ct-svelte": "^1.40.1", 96 | "@playwright/test": "^1.28.1", 97 | "@sveltejs/adapter-static": "^3.0.1", 98 | "@sveltejs/kit": "^2.0.0", 99 | "@sveltejs/package": "^2.0.0", 100 | "@sveltejs/vite-plugin-svelte": "^3.0.0", 101 | "@types/eslint": "8.56.0", 102 | "@types/node": "^20.10.8", 103 | "@typescript-eslint/eslint-plugin": "^6.0.0", 104 | "@typescript-eslint/parser": "^6.0.0", 105 | "eslint": "^8.56.0", 106 | "eslint-config-prettier": "^9.1.0", 107 | "eslint-plugin-svelte": "^2.35.1", 108 | "prettier": "^3.1.1", 109 | "prettier-plugin-svelte": "^3.1.2", 110 | "publint": "^0.1.9", 111 | "svelte": "^4.2.7", 112 | "svelte-check": "^3.6.0", 113 | "tslib": "^2.4.1", 114 | "typescript": "^5.0.0", 115 | "vite": "^5.0.3" 116 | }, 117 | "dependencies": { 118 | "dom-serializer": "^2.0.0", 119 | "domhandler": "^5.0.3", 120 | "esm-env": "^1.0.0", 121 | "html-dom-parser": "^5.0.6", 122 | "htmlparser2": "9.0.0" 123 | }, 124 | "svelte": "./dist/index.js", 125 | "types": "./dist/index.d.ts", 126 | "type": "module" 127 | } 128 | -------------------------------------------------------------------------------- /playwright.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig, devices } from '@playwright/experimental-ct-svelte'; 2 | 3 | /** 4 | * See https://playwright.dev/docs/test-configuration. 5 | */ 6 | export default defineConfig({ 7 | testDir: './tests', 8 | /* The base directory, relative to the config file, for snapshot files created with toMatchSnapshot and toHaveScreenshot. */ 9 | snapshotDir: './playwright/__snapshots__', 10 | /* Maximum time one test can run for. */ 11 | timeout: 10 * 1000, 12 | /* Run tests in files in parallel */ 13 | fullyParallel: true, 14 | /* Fail the build on CI if you accidentally left test.only in the source code. */ 15 | forbidOnly: !!process.env.CI, 16 | /* Retry on CI only */ 17 | retries: process.env.CI ? 2 : 0, 18 | /* Opt out of parallel tests on CI. */ 19 | workers: process.env.CI ? 1 : undefined, 20 | /* Reporter to use. See https://playwright.dev/docs/test-reporters */ 21 | reporter: process.env.CI ? 'html' : 'list', 22 | /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ 23 | use: { 24 | /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */ 25 | trace: 'on-first-retry', 26 | 27 | /* Port to use for Playwright component endpoint. */ 28 | ctPort: 3100, 29 | }, 30 | 31 | /* Configure projects for major browsers */ 32 | projects: [ 33 | { 34 | name: 'chromium', 35 | use: { ...devices['Desktop Chrome'] }, 36 | }, 37 | { 38 | name: 'firefox', 39 | use: { ...devices['Desktop Firefox'] }, 40 | }, 41 | ], 42 | 43 | /* Run your local dev server before starting the tests */ 44 | webServer: { 45 | reuseExistingServer: !process.env.CI, 46 | command: 'npm run dev', 47 | port: 5173, 48 | }, 49 | }); 50 | -------------------------------------------------------------------------------- /playwright/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Testing Page 7 | 8 | 9 |
10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /playwright/index.ts: -------------------------------------------------------------------------------- 1 | // Import styles, initialize component theme here. 2 | // import '../src/common.css'; 3 | -------------------------------------------------------------------------------- /src/app.d.ts: -------------------------------------------------------------------------------- 1 | // See https://kit.svelte.dev/docs/types#app 2 | // for information about these interfaces 3 | declare global { 4 | namespace App { 5 | // interface Error {} 6 | // interface Locals {} 7 | // interface PageData {} 8 | // interface PageState {} 9 | // interface Platform {} 10 | } 11 | } 12 | 13 | export {}; 14 | -------------------------------------------------------------------------------- /src/app.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | %sveltekit.head% 8 | 9 | 10 |
%sveltekit.body%
11 | 12 | 13 | -------------------------------------------------------------------------------- /src/lib/Html.svelte: -------------------------------------------------------------------------------- 1 | 2 | 3 | 28 | 29 | 35 | -------------------------------------------------------------------------------- /src/lib/Renderer.svelte: -------------------------------------------------------------------------------- 1 | {#each nodes as node}{#if node.type === NodeType.Text}{node.data}{:else if node.type === NodeType.Html}{@html node.data}{:else if node.type === NodeType.Tag}{#if node.tag === 'svg'}{:else if node.children?.length}{:else}{/if}{:else if node.children?.length}{:else}{/if}{/each} 23 | -------------------------------------------------------------------------------- /src/lib/SvgRenderer.svelte: -------------------------------------------------------------------------------- 1 | {#each nodes as node}{#if node.type === NodeType.Text}{node.data}{:else if node.type === NodeType.Html}{@html node.data}{:else if node.type === NodeType.Tag}{#if node.children?.length}{:else}{/if}{:else if node.children?.length}{:else}{/if}{/each} -------------------------------------------------------------------------------- /src/lib/index.ts: -------------------------------------------------------------------------------- 1 | export { Element, Text, isTag, isText, type AnyNode, type ChildNode, type ParentNode } from 'domhandler'; 2 | export { default as Html } from './Html.svelte'; 3 | export { default as Renderer } from './Renderer.svelte'; 4 | export * from './load.js'; 5 | export * from './parse.js'; 6 | export * from './types.js'; 7 | -------------------------------------------------------------------------------- /src/lib/load.ts: -------------------------------------------------------------------------------- 1 | import type { ComponentType } from 'svelte'; 2 | import type { Node } from './types.js'; 3 | 4 | export const loadComponents = async ( 5 | { nodes, components: componentNames }: { nodes: Node[]; components: T[] }, 6 | loader: ( 7 | componentName: T, 8 | ) => Promise, 9 | ) => { 10 | const components: Record = {} as Record; 11 | const promises: Promise[] = []; 12 | 13 | for (const componentName of componentNames) { 14 | promises.push( 15 | loader(componentName).then( 16 | mod => 17 | (components[componentName] = 'default' in mod ? mod.default : mod), 18 | ), 19 | ); 20 | } 21 | 22 | await Promise.all(promises); 23 | return { nodes, components }; 24 | }; 25 | -------------------------------------------------------------------------------- /src/lib/parse.ts: -------------------------------------------------------------------------------- 1 | import { render } from 'dom-serializer'; 2 | import { 3 | Text, 4 | isTag, 5 | isText, 6 | type ChildNode, 7 | type DomHandlerOptions, 8 | type Node as DomNode, 9 | type Element, 10 | } from 'domhandler'; 11 | import { BROWSER } from 'esm-env'; 12 | import htmlToDom from 'html-dom-parser'; 13 | import type { ComponentType } from 'svelte'; 14 | import { 15 | NodeType, 16 | type ComponentNode, 17 | type Node, 18 | type Options, 19 | type ProcessNode, 20 | type TagNode, 21 | } from './types.js'; 22 | 23 | const TEXTAREA_REGEX = /^<[^>]+>(.+)<\/[^<]+>$/; 24 | 25 | const defaultOptions: Omit = { 26 | lowerCaseAttributeNames: false, 27 | }; 28 | 29 | export const parse = ( 30 | html: string, 31 | options: Options = {}, 32 | ) => { 33 | const opts: Options & DomHandlerOptions = { 34 | ...defaultOptions, 35 | ...options, 36 | withStartIndices: true, 37 | withEndIndices: true, 38 | }; 39 | const { components, nodes } = transform(html, htmlToDom(html, opts), opts); 40 | return { 41 | nodes, 42 | components: Array.from(components), 43 | }; 44 | }; 45 | 46 | const removeNode = (node: DomNode) => { 47 | const { prev, next, parent } = node; 48 | if (prev) prev.next = next; 49 | if (next) next.prev = prev; 50 | if (parent) 51 | parent.children.splice(parent.children.indexOf(node as ChildNode), 1); 52 | }; 53 | 54 | const transform = ( 55 | html: string, 56 | domNodes: DomNode[], 57 | options: Options, 58 | ) => { 59 | const nodes: Node[] = []; 60 | const components = new Set(); 61 | 62 | for (const domNode of domNodes) { 63 | let processResult: ReturnType> = false; 64 | 65 | if (isText(domNode)) { 66 | processResult = options.processNode?.(domNode); 67 | } else if (isTag(domNode) && !options.filterTags?.includes(domNode.name)) { 68 | // fix textarea content on the server as good as possible 69 | // @see https://github.com/fb55/htmlparser2/issues/51 70 | if ( 71 | !BROWSER && 72 | domNode.name === 'textarea' && 73 | domNode.children?.length && 74 | domNode.startIndex !== null && 75 | domNode.endIndex !== null 76 | ) { 77 | const match = html 78 | .slice(domNode.startIndex, domNode.endIndex + 1) 79 | .match(TEXTAREA_REGEX); 80 | if (match) domNode.children = [new Text(match[1])]; 81 | } 82 | 83 | // Filter `node.attribs` before processing node 84 | domNode.attribs = getFilteredAttributes(domNode, options).attributes; 85 | processResult = options.processNode?.(domNode); 86 | } 87 | 88 | if (processResult === false) { 89 | removeNode(domNode); 90 | continue; 91 | } 92 | 93 | if (processResult?.component) { 94 | components.add(processResult.component); 95 | const node: Node = { 96 | type: NodeType.Component, 97 | component: processResult.component, 98 | }; 99 | 100 | if (processResult.props) node.props = processResult.props; 101 | 102 | if (processResult.rendererProps) { 103 | node.rendererProps = {}; 104 | for (const [propName, childNodes] of Object.entries( 105 | processResult.rendererProps, 106 | )) { 107 | if (!childNodes) { 108 | node.rendererProps[propName] = []; 109 | continue; 110 | } 111 | 112 | const childDomNodes = Array.isArray(childNodes) 113 | ? childNodes 114 | : [childNodes]; 115 | 116 | const { nodes, components: childComponents } = transform( 117 | html, 118 | childDomNodes, 119 | options, 120 | ); 121 | 122 | node.rendererProps[propName] = nodes; 123 | 124 | for (const childComponent of childComponents) { 125 | components.add(childComponent); 126 | } 127 | 128 | // Don't bother removing child nodes if they won't be processed anyway. 129 | if (!processResult.noChildren) { 130 | for (const childDomNode of childDomNodes) { 131 | removeNode(childDomNode); 132 | } 133 | } 134 | } 135 | } 136 | 137 | if ( 138 | !processResult.noChildren && 139 | isTag(domNode) && 140 | domNode.children?.length 141 | ) { 142 | transformAndAddChildren(html, node, domNode, components, options); 143 | } 144 | 145 | nodes.push(node); 146 | continue; 147 | } 148 | 149 | if (isText(domNode)) { 150 | // If the previous node is a `TextNode` or `HtmlNode`, append text to data 151 | const prevNode = nodes.at(-1); 152 | if ( 153 | prevNode?.type === NodeType.Text || 154 | prevNode?.type === NodeType.Html 155 | ) { 156 | prevNode.data += domNode.data; 157 | continue; 158 | } 159 | 160 | nodes.push({ type: NodeType.Text, data: domNode.data }); 161 | continue; 162 | } 163 | 164 | if (isTag(domNode)) { 165 | if (domNode.name === 'script' || domNode.name === 'style') { 166 | addHtmlNode(domNode, nodes, options); 167 | continue; 168 | } 169 | 170 | const node: TagNode = { type: NodeType.Tag, tag: domNode.name }; 171 | const { attributes, hasAttributes } = getFilteredAttributes( 172 | domNode, 173 | options, 174 | ); 175 | if (hasAttributes) node.attributes = attributes; 176 | 177 | let hasChildComponents; 178 | if (domNode.children?.length) { 179 | hasChildComponents = transformAndAddChildren( 180 | html, 181 | node, 182 | domNode, 183 | components, 184 | options, 185 | ); 186 | } 187 | 188 | if (options.noHtmlNodes || hasChildComponents) { 189 | nodes.push(node); 190 | continue; 191 | } 192 | 193 | addHtmlNode(domNode, nodes, options); 194 | } 195 | 196 | // Ignore all other node types 197 | } 198 | 199 | return { nodes, components }; 200 | }; 201 | 202 | const transformAndAddChildren = ( 203 | html: string, 204 | node: TagNode | ComponentNode, 205 | domNode: Element, 206 | components: Set, 207 | options: Options, 208 | ) => { 209 | const { nodes: childNodes, components: childComponents } = transform( 210 | html, 211 | domNode.children, 212 | options, 213 | ); 214 | 215 | if (childNodes.length) { 216 | node.children = childNodes; 217 | for (const component of childComponents) { 218 | components.add(component); 219 | } 220 | 221 | return childComponents.size as unknown as boolean; 222 | } 223 | }; 224 | 225 | const getFilteredAttributes = (domNode: Element, options: Options) => { 226 | const attributes: [PropertyKey, string][] = []; 227 | for (const [name, value] of Object.entries(domNode.attribs)) { 228 | if ( 229 | typeof value === 'string' && 230 | !options.filterAttributes?.includes(name) && 231 | !(options.filterEventAttributes && name.startsWith('on')) 232 | ) { 233 | attributes.push([name, value]); 234 | } 235 | } 236 | 237 | return { 238 | attributes: (domNode.attribs = Object.fromEntries(attributes)), 239 | hasAttributes: attributes.length, 240 | }; 241 | }; 242 | 243 | const addHtmlNode = (domNode: Element, nodes: Node[], options: Options) => { 244 | const html = render(domNode, options); 245 | 246 | // If the previous node is a `TextNode`, change it to `HtmlNode` and 247 | // append html to data 248 | const prevNode = nodes.at(-1); 249 | if (prevNode?.type === NodeType.Text) { 250 | (prevNode as Node).type = NodeType.Html; 251 | prevNode.data = prevNode.data + html; 252 | return; 253 | } 254 | 255 | // If the previous node is a `HtmlNode`, append html to data 256 | if (prevNode?.type === NodeType.Html) { 257 | prevNode.data += html; 258 | return; 259 | } 260 | 261 | nodes.push({ 262 | type: NodeType.Html, 263 | data: html, 264 | }); 265 | }; 266 | -------------------------------------------------------------------------------- /src/lib/types.ts: -------------------------------------------------------------------------------- 1 | import type { DomSerializerOptions } from 'dom-serializer'; 2 | import type { 3 | DomHandlerOptions, 4 | Node as DomNode, 5 | Element, 6 | Text, 7 | } from 'domhandler'; 8 | import type { ParserOptions } from 'htmlparser2'; 9 | import type { ComponentType } from 'svelte'; 10 | 11 | export enum NodeType { 12 | Text, 13 | Tag, 14 | Html, 15 | Component, 16 | } 17 | 18 | export type Attributes = Record; 19 | 20 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 21 | export type Props = Record; 22 | 23 | export type RendererProps = { 24 | nodes: Node[]; 25 | props: Record; 26 | components: Record; 27 | fallback?: ComponentType; 28 | }; 29 | 30 | export type TextNode = { type: NodeType.Text; data: string }; 31 | 32 | export type TagNode = { 33 | type: NodeType.Tag; 34 | tag: string; 35 | attributes?: Attributes; 36 | children?: Node[]; 37 | }; 38 | 39 | export type HtmlNode = { type: NodeType.Html; data: string }; 40 | 41 | export type ComponentNode = { 42 | type: NodeType.Component; 43 | component: ComponentType | string; 44 | props?: Props; 45 | children?: Node[]; 46 | rendererProps?: Record; 47 | }; 48 | 49 | export type Node = TextNode | TagNode | HtmlNode | ComponentNode; 50 | 51 | export type ProcessNode< 52 | C extends ComponentType | string = ComponentType | string, 53 | > = (node: Element | Text) => 54 | | { 55 | component: C; 56 | 57 | /** 58 | * Props that will be passed to `component`. 59 | */ 60 | props?: Props; 61 | 62 | /** 63 | * If `true`, children of `node` will not be processed and no `default` 64 | * slot is rendered for the `component`. 65 | */ 66 | noChildren?: boolean; 67 | 68 | /** 69 | * Transform child nodes into a prop that will be passed to `component` 70 | * which can be rendered to a named slot with the `Renderer` component. 71 | * 72 | * The nodes are automatically removed from the tree so that they do not 73 | * end up in the `default` slot. 74 | */ 75 | rendererProps?: Record< 76 | string, 77 | DomNode | DomNode[] | null | undefined | void 78 | >; 79 | } 80 | | false 81 | | void; 82 | 83 | export type Options = 84 | ParserOptions & 85 | Omit & 86 | DomSerializerOptions & { 87 | /** 88 | * Modify, remove or replace a node. 89 | */ 90 | processNode?: ProcessNode; 91 | 92 | /** 93 | * Remove element nodes with the specified names. 94 | * 95 | * @default [] 96 | */ 97 | filterTags?: string[]; 98 | 99 | /** 100 | * Remove element attributes with the specified names. 101 | * 102 | * @default [] 103 | */ 104 | filterAttributes?: string[]; 105 | 106 | /** 107 | * Remove element attributes that start with `on:`. 108 | * 109 | * @default false 110 | */ 111 | filterEventAttributes?: boolean; 112 | 113 | /** 114 | * Do not render children with sveltes `@html`. 115 | * 116 | * @default false 117 | */ 118 | noHtmlNodes?: boolean; 119 | 120 | /** 121 | * If set to true, all attribute names will be lowercased. This has noticeable impact on speed. 122 | * 123 | * @default false 124 | */ 125 | lowerCaseAttributeNames?: boolean; 126 | }; 127 | -------------------------------------------------------------------------------- /src/lib/utils.ts: -------------------------------------------------------------------------------- 1 | import type { ComponentType } from 'svelte'; 2 | import type { ComponentNode, Props } from './types.js'; 3 | 4 | export const getComponent = ( 5 | node: ComponentNode, 6 | components: Record, 7 | ) => 8 | typeof node.component === 'string' 9 | ? components[node.component] 10 | : node.component; 11 | 12 | export const getComponentProps = ( 13 | node: ComponentNode, 14 | props: Record, 15 | components: Record, 16 | fallback?: ComponentType, 17 | ) => ({ 18 | ...node.props, 19 | ...(typeof node.component === 'string' ? props[node.component] : {}), 20 | ...(node.rendererProps && 21 | Object.fromEntries( 22 | Object.entries(node.rendererProps).map(([propName, nodes]) => [ 23 | propName, 24 | { nodes, props, components, fallback }, 25 | ]), 26 | )), 27 | }); 28 | -------------------------------------------------------------------------------- /src/routes/+layout.svelte: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | 8 | 15 | 16 |
17 | -------------------------------------------------------------------------------- /src/routes/+layout.ts: -------------------------------------------------------------------------------- 1 | export const prerender = true; 2 | export const trailingSlash = 'always'; 3 | -------------------------------------------------------------------------------- /src/routes/+page.svelte: -------------------------------------------------------------------------------- 1 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | { 46 | console.dir(domNode, { depth: null }); 47 | }} 48 | /> 49 | -------------------------------------------------------------------------------- /src/routes/GithubCorner.svelte: -------------------------------------------------------------------------------- 1 | 11 | 25 | 26 | 36 | 50 | 51 | 52 | 97 | -------------------------------------------------------------------------------- /src/routes/components/Test.svelte: -------------------------------------------------------------------------------- 1 | 7 | 8 | {a} 9 | -------------------------------------------------------------------------------- /src/routes/components/Textarea.svelte: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 |

Create your package using @sveltejs/package and preview/showcase your work with SvelteKit

7 |

Visit kit.svelte.dev to read the documentation

`; 8 | 9 | return { 10 | myHtml: parse(html, { 11 | noHtmlNodes: true, 12 | processNode(node) { 13 | if (isTag(node)) { 14 | if (node.name === 'h1') { 15 | node.name = 'h2'; 16 | } else if (node.name === 'a') { 17 | return { component: 'Test', props: { a: 'B' } }; 18 | } else if (node.name === 'b') { 19 | node.name = 'strong'; 20 | } else if (node.name === 'textarea') { 21 | let props: Props | undefined; 22 | const child = node.children?.[0]; 23 | if (child) { 24 | if (isText(child)) props = { value: child.data }; 25 | node.children = []; 26 | } 27 | 28 | return { component: 'Textarea', props }; 29 | } 30 | } 31 | }, 32 | }), 33 | 34 | textareaTest: parse('', { 35 | // noHtmlNodes: true, 36 | }), 37 | }; 38 | } 39 | -------------------------------------------------------------------------------- /src/routes/parse-on-server/+page.svelte: -------------------------------------------------------------------------------- 1 | 6 | 7 |

parse html and process nodes on the server.

8 | 9 |
10 | 11 |
12 | 13 |
14 |

Textarea test

15 | 16 |
17 | 18 | 24 | -------------------------------------------------------------------------------- /src/routes/parse-on-server/+page.ts: -------------------------------------------------------------------------------- 1 | import { loadComponents } from '$lib/index.js'; 2 | 3 | export async function load({ data }) { 4 | return { 5 | ...data, 6 | myHtml: await loadComponents( 7 | data.myHtml, 8 | component => import(`../components/${component}.svelte`), 9 | ), 10 | textareaTest: { 11 | ...data.textareaTest, 12 | components: {}, 13 | }, 14 | }; 15 | } 16 | -------------------------------------------------------------------------------- /src/routes/readme/+layout.svelte: -------------------------------------------------------------------------------- 1 | 4 | 5 |

Readme examples

6 | 7 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/routes/readme/+page.svelte: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PatrickG/html-svelte-parser/d49f5ccb6985d3b0347784cf829058bcdd646086/src/routes/readme/+page.svelte -------------------------------------------------------------------------------- /src/routes/readme/1/+page.svelte: -------------------------------------------------------------------------------- 1 | 5 | 6 | { 9 | if (isTag(node) && node.name === 'p') { 10 | return { component: Paragraph }; 11 | } 12 | }} 13 | /> 14 | 15 | 20 | -------------------------------------------------------------------------------- /src/routes/readme/1/Paragraph.svelte: -------------------------------------------------------------------------------- 1 |

2 | -------------------------------------------------------------------------------- /src/routes/readme/2/+page.svelte: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | 9 |
    10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | `} 19 | /> 20 | -------------------------------------------------------------------------------- /src/routes/readme/3/+page.svelte: -------------------------------------------------------------------------------- 1 | 4 | 5 | { 8 | console.dir(domNode, { depth: null }); 9 | }} 10 | /> 11 | -------------------------------------------------------------------------------- /src/routes/readme/4/+page.svelte: -------------------------------------------------------------------------------- 1 | 22 | 23 | 24 | 25 | 30 | -------------------------------------------------------------------------------- /src/routes/readme/5/+page.svelte: -------------------------------------------------------------------------------- 1 | 14 | 15 | 16 | 17 | 22 | -------------------------------------------------------------------------------- /src/routes/readme/5/Span.svelte: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/routes/readme/6/+page.server.ts: -------------------------------------------------------------------------------- 1 | import { isTag, parse } from '$lib/index.js'; 2 | 3 | export function load() { 4 | return { 5 | content: parse( 6 | `

Svelte rocks

`, 7 | { 8 | processNode(node) { 9 | if ( 10 | isTag(node) && 11 | node.name === 'a' && 12 | node.attribs.class?.split(/\s/).includes('btn') 13 | ) { 14 | // We use a `string` for the `component` property. 15 | return { component: 'Button', props: node.attribs }; 16 | } 17 | }, 18 | }, 19 | ), 20 | }; 21 | } 22 | -------------------------------------------------------------------------------- /src/routes/readme/6/+page.svelte: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 | 9 | 14 | -------------------------------------------------------------------------------- /src/routes/readme/6/+page.ts: -------------------------------------------------------------------------------- 1 | import { loadComponents } from '$lib/index.js'; 2 | 3 | export async function load({ data }) { 4 | return { 5 | content: await loadComponents(data.content, componentName => { 6 | // `componentName` is the `component` we returned in `+page.server.js` 7 | return import(`./components/${componentName}.svelte`); 8 | }), 9 | }; 10 | } 11 | -------------------------------------------------------------------------------- /src/routes/readme/6/components/Button.svelte: -------------------------------------------------------------------------------- 1 | 7 | 8 | {#if href} 9 | 10 | {:else} 11 | 12 | {/if} 13 | -------------------------------------------------------------------------------- /src/routes/readme/7/+page.svelte: -------------------------------------------------------------------------------- 1 | 73 | 74 | 75 | 76 | 92 | -------------------------------------------------------------------------------- /src/routes/readme/7/Button.svelte: -------------------------------------------------------------------------------- 1 | 8 | 9 | {#if href} 10 | 13 | {:else} 14 | 15 | {/if} 16 | -------------------------------------------------------------------------------- /src/routes/readme/7/Card.svelte: -------------------------------------------------------------------------------- 1 |
2 | {#if $$slots.title} 3 |
4 | {/if} 5 | 6 |
7 | 8 | {#if $$slots.actions} 9 |
10 | {/if} 11 |
12 | -------------------------------------------------------------------------------- /src/routes/readme/7/CardWrapper.svelte: -------------------------------------------------------------------------------- 1 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/routes/svg/+page.svelte: -------------------------------------------------------------------------------- 1 | 30 | 31 | { 34 | if (!isTag(node)) return; 35 | switch (node.name) { 36 | case 'rect': 37 | return { component: Rect, props: { attributes: node.attribs } }; 38 | case 'g': 39 | if (node.parent && isTag(node.parent) && node.parent.name === 'svg') 40 | return { component: Group, props: { attributes: node.attribs } }; 41 | } 42 | }} 43 | /> 44 | 45 | 46 | -------------------------------------------------------------------------------- /src/routes/svg/Group.svelte: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /src/routes/svg/Rect.svelte: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /src/routes/tests/+page.server.ts: -------------------------------------------------------------------------------- 1 | import { parse } from '$lib/index.js'; 2 | import { error } from '@sveltejs/kit'; 3 | import { html, svg } from '../../../tests/data.js'; 4 | 5 | export const prerender = false; 6 | 7 | export function load({ url }) { 8 | const key = url.searchParams.get('test'); 9 | if (!key) { 10 | throw error(404); 11 | } 12 | 13 | const test = 14 | key in html 15 | ? html[key as keyof typeof html] 16 | : key in svg 17 | ? svg[key as keyof typeof svg] 18 | : null; 19 | if (!test) { 20 | throw error(404); 21 | } 22 | 23 | return { 24 | test, 25 | withHtmlNodes: parse(test), 26 | withoutHtmlNodes: parse(test, { noHtmlNodes: true }), 27 | }; 28 | } 29 | -------------------------------------------------------------------------------- /src/routes/tests/+page.svelte: -------------------------------------------------------------------------------- 1 | 6 | 7 |
8 | 9 |
10 | -------------------------------------------------------------------------------- /src/routes/tests/+page.ts: -------------------------------------------------------------------------------- 1 | import { loadComponents } from '$lib/index.js'; 2 | 3 | const loader = (component: string) => 4 | import(`./components/${component}.svelte`); 5 | 6 | export async function load({ data }) { 7 | const [withHtmlNodes, withoutHtmlNodes] = await Promise.all([ 8 | loadComponents(data.withHtmlNodes, loader), 9 | loadComponents(data.withoutHtmlNodes, loader), 10 | ]); 11 | 12 | return { 13 | ...data, 14 | withHtmlNodes, 15 | withoutHtmlNodes, 16 | }; 17 | } 18 | -------------------------------------------------------------------------------- /static/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PatrickG/html-svelte-parser/d49f5ccb6985d3b0347784cf829058bcdd646086/static/logo.png -------------------------------------------------------------------------------- /static/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 75 | -------------------------------------------------------------------------------- /svelte.config.js: -------------------------------------------------------------------------------- 1 | import adapter from '@sveltejs/adapter-static'; 2 | import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; 3 | 4 | /** @type {import('@sveltejs/kit').Config} */ 5 | const config = { 6 | preprocess: vitePreprocess(), 7 | 8 | kit: { 9 | adapter: adapter({ fallback: '404.html' }), 10 | paths: { 11 | base: /** @type {`/${string}` | undefined} */ (process.env.BASE_PATH), 12 | }, 13 | }, 14 | 15 | vitePlugin: { inspector: true }, 16 | }; 17 | 18 | export default config; 19 | -------------------------------------------------------------------------------- /tests/Html.spec.ts: -------------------------------------------------------------------------------- 1 | import { expect, test } from '@playwright/experimental-ct-svelte'; 2 | import type { Page } from '@playwright/test'; 3 | import { expect as expectSSR, test as testSSR } from '@playwright/test'; 4 | import Html from '../src/lib/Html.svelte'; 5 | import type { parse } from '../src/lib/parse.js'; 6 | import { NodeType } from '../src/lib/types.js'; 7 | import Test from './Test.svelte'; 8 | import { html, svg } from './data.js'; 9 | 10 | const getHtml = async (page: Page) => (await page.locator('#root')).innerHTML(); 11 | 12 | test('transforms HTML entities into hex code in html nodes', async ({ 13 | mount, 14 | }) => { 15 | const component = await mount(Test); 16 | const element = await component.locator('#result'); 17 | const result = await element.evaluate(element => 18 | (element as { parse?: typeof parse }).parse!( 19 | `asdf & ÿ ü '`, 20 | ), 21 | ); 22 | 23 | expect(result).toEqual({ 24 | components: [], 25 | nodes: [ 26 | { type: NodeType.Html, data: `asdf & ÿ ü '` }, 27 | ], 28 | }); 29 | }); 30 | 31 | test('decodes HTML entities in tag nodes', async ({ mount }) => { 32 | const component = await mount(Test); 33 | const element = await component.locator('#result'); 34 | const result = await element.evaluate(element => 35 | (element as { parse?: typeof parse }).parse!( 36 | `asdf & ÿ ü '`, 37 | { noHtmlNodes: true }, 38 | ), 39 | ); 40 | 41 | expect(result).toEqual({ 42 | components: [], 43 | nodes: [ 44 | { 45 | type: NodeType.Tag, 46 | tag: 'i', 47 | children: [{ type: NodeType.Text, data: "asdf & ÿ ü '" }], 48 | }, 49 | ], 50 | }); 51 | }); 52 | 53 | test.describe('converts "text" to "text"', () => { 54 | const html = 'text'; 55 | 56 | test('with html nodes', async ({ mount, page }) => { 57 | await mount(Html, { props: { html } }); 58 | expect(await getHtml(page)).toBe(html); 59 | }); 60 | 61 | test('without html nodes', async ({ mount, page }) => { 62 | await mount(Html, { props: { html, noHtmlNodes: true } }); 63 | expect(await getHtml(page)).toBe(html); 64 | }); 65 | }); 66 | 67 | test.describe('single DOM node', () => { 68 | test('with html nodes', async ({ mount, page }) => { 69 | await mount(Html, { props: { html: html.single } }); 70 | expect(await getHtml(page)).toBe(html.single); 71 | }); 72 | 73 | test('without html nodes', async ({ mount, page }) => { 74 | await mount(Html, { props: { html: html.single, noHtmlNodes: true } }); 75 | expect(await getHtml(page)).toBe(html.single); 76 | }); 77 | }); 78 | 79 | test.describe('multiple DOM nodes', () => { 80 | test('with html nodes', async ({ mount, page }) => { 81 | await mount(Html, { props: { html: html.multiple } }); 82 | expect(await getHtml(page)).toBe(html.multiple); 83 | }); 84 | 85 | test('without html nodes', async ({ mount, page }) => { 86 | await mount(Html, { props: { html: html.multiple, noHtmlNodes: true } }); 87 | expect(await getHtml(page)).toBe(html.multiple); 88 | }); 89 | }); 90 | 91 | test.describe('converts ', 97 | ); 98 | expect(await component.inputValue()).toBe('

foo

bar

'); 99 | }); 100 | 101 | test('without html nodes', async ({ mount, page }) => { 102 | const component = await mount(Html, { 103 | props: { html: html.textarea, noHtmlNodes: true }, 104 | }); 105 | expect(await getHtml(page)).toBe( 106 | '', 107 | ); 108 | expect(await component.inputValue()).toBe('

foo

bar

'); 109 | }); 110 | }); 111 | 112 | testSSR.describe('without javascript', () => { 113 | testSSR.use({ javaScriptEnabled: false }); 114 | 115 | testSSR('', async ({ page }) => { 116 | await page.goto('http://localhost:5173/tests?test=textarea'); 117 | 118 | expectSSR( 119 | await (await page.locator('#with-html-nodes')).innerHTML(), 120 | ).toBe( 121 | '', 122 | ); 123 | expectSSR( 124 | await (await page.locator('#with-html-nodes textarea')).inputValue(), 125 | ).toBe('

foo

bar

'); 126 | 127 | expectSSR( 128 | await (await page.locator('#without-html-nodes')).innerHTML(), 129 | ).toBe( 130 | '', 131 | ); 132 | expectSSR( 133 | await (await page.locator('#without-html-nodes textarea')).inputValue(), 134 | ).toBe('

foo

bar

'); 135 | }); 136 | }); 137 | }); 138 | 139 | test.describe('does not parse ', 145 | ); 146 | expect(await component.inputValue()).toBe('

foo

'); 147 | }); 148 | 149 | test('without html nodes', async ({ mount, page }) => { 150 | const component = await mount(Html, { 151 | props: { html: html.textareaWithInvalidHtml, noHtmlNodes: true }, 152 | }); 153 | expect(await getHtml(page)).toBe( 154 | '', 155 | ); 156 | expect(await component.inputValue()).toBe('

foo

'); 157 | }); 158 | }); 159 | 160 | testSSR.describe('without javascript', () => { 161 | testSSR.use({ javaScriptEnabled: false }); 162 | 163 | testSSR('', async ({ page }) => { 164 | await page.goto('http://localhost:5173/tests?test=textareaWithInvalidHtml'); 165 | 166 | expectSSR( 167 | await (await page.locator('#with-html-nodes')).innerHTML(), 168 | ).toBe( 169 | '', 170 | ); 171 | expectSSR( 172 | await (await page.locator('#with-html-nodes textarea')).inputValue(), 173 | ).toBe('

foo

'); 174 | 175 | expectSSR( 176 | await (await page.locator('#without-html-nodes')).innerHTML(), 177 | ).toBe( 178 | '', 179 | ); 180 | expectSSR( 181 | await (await page.locator('#without-html-nodes textarea')).inputValue(), 182 | ).toBe('

foo

'); 183 | }); 184 | }); 185 | }); 186 | 187 | test.describe('does not escape ', 210 | ); 211 | 212 | expectSSR( 213 | await (await page.locator('#without-html-nodes')).innerHTML(), 214 | ).toBe( 215 | '', 216 | ); 217 | }); 218 | }); 219 | }); 220 | 221 | test.describe('does not escape ', 244 | ); 245 | 246 | expectSSR( 247 | await (await page.locator('#without-html-nodes')).innerHTML(), 248 | ).toBe( 249 | '', 250 | ); 251 | }); 252 | }); 253 | }); 254 | 255 | test.describe('renders void elements correctly', () => { 256 | test('with html nodes', async ({ mount, page }) => { 257 | await mount(Html, { props: { html: html.void } }); 258 | 259 | expect(await getHtml(page)).toBe('

'); 260 | }); 261 | 262 | test('without html nodes', async ({ mount, page }) => { 263 | await mount(Html, { props: { html: html.void, noHtmlNodes: true } }); 264 | 265 | expect(await getHtml(page)).toBe('

'); 266 | }); 267 | 268 | testSSR.describe('without javascript', () => { 269 | testSSR.use({ javaScriptEnabled: false }); 270 | 271 | testSSR('', async ({ page }) => { 272 | await page.goto('http://localhost:5173/tests?test=void'); 273 | 274 | expectSSR( 275 | await (await page.locator('#with-html-nodes')).innerHTML(), 276 | ).toBe( 277 | '

', 278 | ); 279 | 280 | expectSSR( 281 | await (await page.locator('#without-html-nodes')).innerHTML(), 282 | ).toBe('

'); 283 | }); 284 | }); 285 | }); 286 | 287 | test.describe('skips doctype and comments', () => { 288 | test('with html nodes', async ({ mount, page }) => { 289 | await mount(Html, { props: { html: html.doctypeAndComment } }); 290 | 291 | expect(await getHtml(page)).toBe(html.single + html.single); 292 | }); 293 | 294 | test('without html nodes', async ({ mount, page }) => { 295 | await mount(Html, { 296 | props: { html: html.doctypeAndComment, noHtmlNodes: true }, 297 | }); 298 | 299 | expect(await getHtml(page)).toBe(html.single + html.single); 300 | }); 301 | 302 | testSSR.describe('without javascript', () => { 303 | testSSR.use({ javaScriptEnabled: false }); 304 | 305 | testSSR('', async ({ page }) => { 306 | await page.goto('http://localhost:5173/tests?test=doctypeAndComment'); 307 | 308 | expectSSR( 309 | await (await page.locator('#with-html-nodes')).innerHTML(), 310 | ).toBe( 311 | '' + 312 | html.single + 313 | html.single + 314 | '', 315 | ); 316 | 317 | expectSSR( 318 | await (await page.locator('#without-html-nodes')).innerHTML(), 319 | ).toBe(html.single + html.single); 320 | }); 321 | }); 322 | }); 323 | 324 | test.describe('converts SVG element with viewBox attribute', () => { 325 | test('with html nodes', async ({ mount, page }) => { 326 | await mount(Html, { props: { html: svg.simple } }); 327 | 328 | expect(await getHtml(page)).toBe(svg.simple); 329 | }); 330 | 331 | test('without html nodes', async ({ mount, page }) => { 332 | await mount(Html, { props: { html: svg.simple, noHtmlNodes: true } }); 333 | 334 | expect(await getHtml(page)).toBe(svg.simple); 335 | }); 336 | 337 | testSSR.describe('without javascript', () => { 338 | testSSR.use({ javaScriptEnabled: false }); 339 | 340 | testSSR('', async ({ page }) => { 341 | await page.goto('http://localhost:5173/tests?test=simple'); 342 | 343 | expectSSR( 344 | await (await page.locator('#with-html-nodes')).innerHTML(), 345 | ).toBe('' + svg.simple + ''); 346 | 347 | expectSSR( 348 | await (await page.locator('#without-html-nodes')).innerHTML(), 349 | ).toBe(svg.simple); 350 | }); 351 | }); 352 | }); 353 | 354 | test.describe('converts custom element with attributes', () => { 355 | test('with html nodes', async ({ mount, page }) => { 356 | await mount(Html, { props: { html: html.customElement } }); 357 | 358 | expect(await getHtml(page)).toBe(html.customElement); 359 | }); 360 | 361 | test('without html nodes', async ({ mount, page }) => { 362 | await mount(Html, { 363 | props: { html: html.customElement, noHtmlNodes: true }, 364 | }); 365 | 366 | expect(await getHtml(page)).toBe( 367 | '', 368 | ); 369 | }); 370 | 371 | testSSR.describe('without javascript', () => { 372 | testSSR.use({ javaScriptEnabled: false }); 373 | 374 | testSSR('', async ({ page }) => { 375 | await page.goto('http://localhost:5173/tests?test=customElement'); 376 | 377 | expectSSR( 378 | await (await page.locator('#with-html-nodes')).innerHTML(), 379 | ).toBe( 380 | '' + 381 | html.customElement + 382 | '', 383 | ); 384 | 385 | expectSSR( 386 | await (await page.locator('#without-html-nodes')).innerHTML(), 387 | ).toBe(html.customElement); 388 | }); 389 | }); 390 | }); 391 | 392 | test.describe('rerenders when html prop is changes dynamically', () => { 393 | test('with html nodes', async ({ mount, page }) => { 394 | await mount(Test); 395 | 396 | expect(await (await page.locator('#result')).innerHTML()).toBe( 397 | '

foo

', 398 | ); 399 | 400 | await (await page.locator('button')).click(); 401 | 402 | expect(await (await page.locator('#result')).innerHTML()).toBe( 403 | '
bar
', 404 | ); 405 | }); 406 | 407 | test('without html nodes', async ({ mount, page }) => { 408 | await mount(Test, { props: { noHtmlNodes: true } }); 409 | 410 | expect(await (await page.locator('#result')).innerHTML()).toBe( 411 | '

foo

', 412 | ); 413 | 414 | await (await page.locator('button')).click(); 415 | 416 | expect(await (await page.locator('#result')).innerHTML()).toBe( 417 | '
bar
', 418 | ); 419 | }); 420 | }); 421 | -------------------------------------------------------------------------------- /tests/Test.svelte: -------------------------------------------------------------------------------- 1 | 19 | 20 |
21 | 22 |
23 | 24 | 25 | -------------------------------------------------------------------------------- /tests/data.ts: -------------------------------------------------------------------------------- 1 | export const html = { 2 | single: '

foo

', 3 | multiple: '

foo

bar

', 4 | nested: '

foo bar

', 5 | attributes: 6 | '
', 7 | events: ``, 8 | complex: 9 | 'Title

Heading


Paragraph

Some text.
', 10 | textarea: '', 11 | textareaWithInvalidHtml: '', 12 | script: '', 13 | style: '', 14 | img: 'Image', 15 | void: '

', 16 | comment: '', 17 | doctype: '', 18 | doctypeAndComment: '

foo

foo

', 19 | title: '<em>text</em><b>text</b>', 20 | customElement: 21 | '', 22 | form: '', 23 | }; 24 | 25 | export const svg = { 26 | simple: 'Inner', 27 | complex: 28 | 'AYour browser does not support inline SVG.', 29 | }; 30 | -------------------------------------------------------------------------------- /tests/parse.spec.ts: -------------------------------------------------------------------------------- 1 | import { expect, test } from '@playwright/test'; 2 | import { isTag, isText } from 'domhandler'; 3 | import type { ComponentType } from 'svelte'; 4 | import { parse } from '../src/lib/parse.js'; 5 | import { NodeType } from '../src/lib/types.js'; 6 | import { html, svg } from './data.js'; 7 | 8 | for (const value of [ 9 | undefined, 10 | null, 11 | {}, 12 | [], 13 | true, 14 | false, 15 | 0, 16 | 1, 17 | () => {}, // eslint-disable-line @typescript-eslint/no-empty-function 18 | 'date', 19 | ]) { 20 | test('throws error for value: ' + value, () => { 21 | expect(() => 22 | parse((value === 'date' ? new Date() : value) as unknown as string), 23 | ).toThrow(TypeError); 24 | }); 25 | } 26 | 27 | test('parses "" to []', () => { 28 | expect(parse('')).toEqual({ components: [], nodes: [] }); 29 | }); 30 | 31 | for (const [name, value] of [ 32 | ['comment', html.comment], 33 | ['doctype', html.doctype], 34 | ]) { 35 | test('skips ' + name, () => { 36 | expect(parse(value)).toEqual({ components: [], nodes: [] }); 37 | }); 38 | } 39 | 40 | test("returns text node if it's not HTML", () => { 41 | const string = 'text'; 42 | expect(parse(string)).toEqual({ 43 | components: [], 44 | nodes: [{ type: NodeType.Text, data: string }], 45 | }); 46 | }); 47 | 48 | test.describe('parses single HTML element with comment', () => { 49 | // comment should be ignored 50 | test('with html nodes', () => { 51 | expect(parse(html.single + html.comment)).toEqual({ 52 | components: [], 53 | nodes: [{ type: NodeType.Html, data: '

foo

' }], 54 | }); 55 | }); 56 | 57 | test('without html nodes', () => { 58 | expect(parse(html.single + html.comment, { noHtmlNodes: true })).toEqual({ 59 | components: [], 60 | nodes: [ 61 | { 62 | type: NodeType.Tag, 63 | tag: 'p', 64 | children: [{ type: NodeType.Text, data: 'foo' }], 65 | }, 66 | ], 67 | }); 68 | }); 69 | }); 70 | 71 | test.describe('parses multiple HTML elements', () => { 72 | test('with html nodes', () => { 73 | expect(parse(html.multiple)).toEqual({ 74 | components: [], 75 | nodes: [{ type: NodeType.Html, data: '

foo

bar

' }], 76 | }); 77 | }); 78 | 79 | test('without html nodes', () => { 80 | expect(parse(html.multiple, { noHtmlNodes: true })).toEqual({ 81 | components: [], 82 | nodes: [ 83 | { 84 | type: NodeType.Tag, 85 | tag: 'p', 86 | children: [{ type: NodeType.Text, data: 'foo' }], 87 | }, 88 | { 89 | type: NodeType.Tag, 90 | tag: 'p', 91 | children: [{ type: NodeType.Text, data: 'bar' }], 92 | }, 93 | ], 94 | }); 95 | }); 96 | }); 97 | 98 | test.describe('parses textarea correctly', () => { 99 | test('with html nodes', () => { 100 | expect(parse(html.textarea)).toEqual({ 101 | components: [], 102 | nodes: [ 103 | { 104 | type: NodeType.Html, 105 | data: '', 106 | }, 107 | ], 108 | }); 109 | }); 110 | 111 | test('without html nodes', () => { 112 | expect(parse(html.textarea, { noHtmlNodes: true })).toEqual({ 113 | components: [], 114 | nodes: [ 115 | { 116 | type: NodeType.Tag, 117 | tag: 'textarea', 118 | children: [{ type: NodeType.Text, data: '

foo

bar

' }], 119 | }, 120 | ], 121 | }); 122 | }); 123 | }); 124 | 125 | test.describe('parses complex HTML without doctype', () => { 126 | test('with html nodes', () => { 127 | expect(parse(html.doctype + html.complex)).toEqual({ 128 | components: [], 129 | nodes: [ 130 | { 131 | type: NodeType.Html, 132 | data: 133 | '' + 134 | '' + 135 | '' + 136 | 'Title' + 137 | '' + 138 | '' + 139 | '' + 140 | '' + 141 | '

Heading

' + 142 | '
' + 143 | '

Paragraph

' + 144 | '' + 145 | '
' + 146 | 'Some ' + 147 | 'text' + 148 | '.' + 149 | '
' + 150 | '' + 151 | '' + 152 | '', 153 | }, 154 | ], 155 | }); 156 | }); 157 | 158 | test('without html nodes', () => { 159 | expect(parse(html.doctype + html.complex, { noHtmlNodes: true })).toEqual({ 160 | components: [], 161 | nodes: [ 162 | { 163 | type: NodeType.Tag, 164 | tag: 'html', 165 | children: [ 166 | { 167 | type: NodeType.Tag, 168 | tag: 'head', 169 | children: [ 170 | { 171 | type: NodeType.Tag, 172 | tag: 'meta', 173 | attributes: { charSet: 'utf-8' }, 174 | }, 175 | { 176 | type: NodeType.Tag, 177 | tag: 'title', 178 | children: [{ type: NodeType.Text, data: 'Title' }], 179 | }, 180 | { 181 | type: NodeType.Tag, 182 | tag: 'link', 183 | attributes: { rel: 'stylesheet', href: 'style.css' }, 184 | }, 185 | ], 186 | }, 187 | { 188 | type: NodeType.Tag, 189 | tag: 'body', 190 | children: [ 191 | { 192 | type: NodeType.Tag, 193 | tag: 'header', 194 | attributes: { id: 'header' }, 195 | children: [{ type: NodeType.Text, data: 'Header' }], 196 | }, 197 | { 198 | type: NodeType.Tag, 199 | tag: 'h1', 200 | attributes: { style: 'color:#000;font-size:42px' }, 201 | children: [{ type: NodeType.Text, data: 'Heading' }], 202 | }, 203 | { type: NodeType.Tag, tag: 'hr' }, 204 | { 205 | type: NodeType.Tag, 206 | tag: 'p', 207 | children: [{ type: NodeType.Text, data: 'Paragraph' }], 208 | }, 209 | { 210 | type: NodeType.Tag, 211 | tag: 'img', 212 | attributes: { src: 'image.jpg' }, 213 | }, 214 | { 215 | type: NodeType.Tag, 216 | tag: 'div', 217 | attributes: { class: 'class1 class2' }, 218 | children: [ 219 | { type: NodeType.Text, data: 'Some ' }, 220 | { 221 | type: NodeType.Tag, 222 | tag: 'em', 223 | children: [{ type: NodeType.Text, data: 'text' }], 224 | }, 225 | { type: NodeType.Text, data: '.' }, 226 | ], 227 | }, 228 | { 229 | type: NodeType.Html, // script is always a `HtmlNode` 230 | data: '', 231 | }, 232 | ], 233 | }, 234 | ], 235 | }, 236 | ], 237 | }); 238 | }); 239 | }); 240 | 241 | test.describe('parses empty ')).toEqual({ 244 | components: [], 245 | nodes: [{ type: NodeType.Html, data: '' }], 246 | }); 247 | }); 248 | 249 | test('without html nodes', () => { 250 | expect(parse('', { noHtmlNodes: true })).toEqual({ 251 | components: [], 252 | nodes: [ 253 | { type: NodeType.Html, data: '' }, // script is always a `HtmlNode` 254 | ], 255 | }); 256 | }); 257 | }); 258 | 259 | test.describe('parses empty ')).toEqual({ 262 | components: [], 263 | nodes: [{ type: NodeType.Html, data: '' }], 264 | }); 265 | }); 266 | 267 | test('without html nodes', () => { 268 | expect(parse('', { noHtmlNodes: true })).toEqual({ 269 | components: [], 270 | nodes: [ 271 | { type: NodeType.Html, data: '' }, // style is always a `HtmlNode` 272 | ], 273 | }); 274 | }); 275 | }); 276 | 277 | test.describe('parses form', () => { 278 | test('with html nodes', () => { 279 | expect(parse(html.form)).toEqual({ 280 | components: [], 281 | nodes: [ 282 | { 283 | type: NodeType.Html, 284 | data: '', 285 | }, 286 | ], 287 | }); 288 | }); 289 | 290 | test('without html nodes', () => { 291 | expect(parse(html.form, { noHtmlNodes: true })).toEqual({ 292 | components: [], 293 | nodes: [ 294 | { 295 | type: NodeType.Tag, 296 | tag: 'input', 297 | attributes: { type: 'text', value: 'foo', checked: 'checked' }, 298 | }, 299 | ], 300 | }); 301 | }); 302 | }); 303 | 304 | test.describe('parses SVG', () => { 305 | test('with html nodes', () => { 306 | expect(parse(svg.complex)).toEqual({ 307 | components: [], 308 | nodes: [ 309 | { 310 | type: NodeType.Html, 311 | data: 312 | '' + 313 | '' + 314 | '' + 315 | '' + 316 | '' + 317 | '' + 318 | 'A' + 319 | '' + 320 | 'Your browser does not support inline SVG.' + 321 | '', 322 | }, 323 | ], 324 | }); 325 | }); 326 | 327 | test('without html nodes', () => { 328 | expect(parse(svg.complex, { noHtmlNodes: true })).toEqual({ 329 | components: [], 330 | nodes: [ 331 | { 332 | type: NodeType.Tag, 333 | tag: 'svg', 334 | attributes: { height: '400', width: '450' }, 335 | children: [ 336 | { 337 | type: NodeType.Tag, 338 | tag: 'path', 339 | attributes: { 340 | id: 'lineAB', 341 | d: 'M 100 350 l 150 -300', 342 | stroke: 'red', 343 | 'stroke-width': '3', 344 | fill: 'none', 345 | }, 346 | }, 347 | { 348 | type: NodeType.Tag, 349 | tag: 'g', 350 | attributes: { 351 | stroke: 'black', 352 | 'stroke-width': '3', 353 | fill: 'black', 354 | }, 355 | children: [ 356 | { 357 | type: NodeType.Tag, 358 | tag: 'circle', 359 | attributes: { id: 'pointA', cx: '100', cy: '350', r: '3' }, 360 | }, 361 | ], 362 | }, 363 | { 364 | type: NodeType.Tag, 365 | tag: 'g', 366 | attributes: { 367 | 'font-size': '30', 368 | 'font-family': 'sans-serif', 369 | fill: 'black', 370 | stroke: 'none', 371 | 'text-anchor': 'middle', 372 | }, 373 | children: [ 374 | { 375 | type: NodeType.Tag, 376 | tag: 'text', 377 | attributes: { x: '100', y: '350', dx: '-30' }, 378 | children: [{ type: NodeType.Text, data: 'A' }], 379 | }, 380 | ], 381 | }, 382 | { 383 | type: NodeType.Text, 384 | data: 'Your browser does not support inline SVG.', 385 | }, 386 | ], 387 | }, 388 | ], 389 | }); 390 | }); 391 | }); 392 | 393 | test('transforms HTML entities into hex code in html nodes', () => { 394 | const encodedEntities = 'asdf & ÿ ü ''; 395 | const hexCode = 'asdf & ÿ ü ''; 396 | expect(parse(`${encodedEntities}`)).toEqual({ 397 | components: [], 398 | nodes: [{ type: NodeType.Html, data: `${hexCode}` }], 399 | }); 400 | }); 401 | 402 | test('decodes HTML entities in text nodes', () => { 403 | const encodedEntities = 'asdf & ÿ ü ''; 404 | const decodedEntities = "asdf & ÿ ü '"; 405 | expect(parse(`${encodedEntities}`, { noHtmlNodes: true })).toEqual({ 406 | components: [], 407 | nodes: [ 408 | { 409 | type: NodeType.Tag, 410 | tag: 'i', 411 | children: [{ type: NodeType.Text, data: decodedEntities }], 412 | }, 413 | ], 414 | }); 415 | }); 416 | 417 | test('escapes tags inside of in html nodes', () => { 418 | expect(parse(html.title)).toEqual({ 419 | components: [], 420 | nodes: [ 421 | { 422 | type: NodeType.Html, 423 | data: '<title><em>text</em><b>text</b>', 424 | }, 425 | ], 426 | }); 427 | }); 428 | 429 | test('creates text node for content of ', () => { 430 | expect(parse(html.title, { noHtmlNodes: true })).toEqual({ 431 | components: [], 432 | nodes: [ 433 | { 434 | type: NodeType.Tag, 435 | tag: 'title', 436 | children: [{ type: NodeType.Text, data: '<em>text</em><b>text</b>' }], 437 | }, 438 | ], 439 | }); 440 | }); 441 | 442 | test('returns component names', () => { 443 | expect( 444 | parse(html.nested, { 445 | processNode(node) { 446 | if (isTag(node) && node.name === 'em') return { component: 'Test' }; 447 | }, 448 | }), 449 | ).toEqual({ 450 | components: ['Test'], 451 | nodes: [ 452 | { 453 | type: NodeType.Tag, 454 | tag: 'div', 455 | children: [ 456 | { 457 | type: NodeType.Tag, 458 | tag: 'p', 459 | children: [ 460 | { type: NodeType.Text, data: 'foo ' }, 461 | { 462 | type: NodeType.Component, 463 | component: 'Test', 464 | children: [{ type: NodeType.Text, data: 'bar' }], 465 | }, 466 | ], 467 | }, 468 | ], 469 | }, 470 | ], 471 | }); 472 | }); 473 | 474 | test.describe('processNode option', () => { 475 | test('replaces the element if a svelte component is returned and removes the element if `false` is returned', () => { 476 | // We can not import .svelte files here 477 | const component = {} as unknown as ComponentType; 478 | expect( 479 | parse(html.complex, { 480 | processNode(node) { 481 | if (isTag(node)) { 482 | if (node.name === 'body') return false; 483 | if (node.name === 'meta') return { component, props: node.attribs }; 484 | if (node.name === 'title') { 485 | if (isText(node.children?.[0])) 486 | node.children[0].data = 'Replaced Title'; 487 | return { component }; 488 | } 489 | } 490 | }, 491 | }), 492 | ).toEqual({ 493 | components: [component], 494 | nodes: [ 495 | { 496 | type: NodeType.Tag, 497 | tag: 'html', 498 | children: [ 499 | { 500 | type: NodeType.Tag, 501 | tag: 'head', 502 | children: [ 503 | { 504 | type: NodeType.Component, 505 | component, 506 | props: { charSet: 'utf-8' }, 507 | }, 508 | { 509 | type: NodeType.Component, 510 | component, 511 | children: [{ type: NodeType.Text, data: 'Replaced Title' }], 512 | }, 513 | { 514 | type: NodeType.Html, 515 | data: '<link rel="stylesheet" href="style.css">', 516 | }, 517 | ], 518 | }, 519 | ], 520 | }, 521 | ], 522 | }); 523 | }); 524 | 525 | test('filters tags', () => { 526 | expect(parse(html.nested, { filterTags: ['em'] })).toEqual({ 527 | components: [], 528 | nodes: [{ type: NodeType.Html, data: '<div><p>foo </p></div>' }], 529 | }); 530 | }); 531 | 532 | test('filters attributes', () => { 533 | expect(parse(html.attributes, { filterAttributes: ['style'] })).toEqual({ 534 | components: [], 535 | nodes: [ 536 | { 537 | type: NodeType.Html, 538 | data: '<hr id="foo" class="bar baz" data-foo="bar">', 539 | }, 540 | ], 541 | }); 542 | }); 543 | 544 | test('filters event attributes', () => { 545 | expect(parse(html.events, { filterEventAttributes: true })).toEqual({ 546 | components: [], 547 | nodes: [{ type: NodeType.Html, data: '<button>Test</button>' }], 548 | }); 549 | }); 550 | }); 551 | 552 | test.describe('htmlparser2 option', () => { 553 | test('parses XHTML with xmlMode enabled', () => { 554 | // using self-closing syntax (`/>`) for non-void elements is invalid 555 | // which causes elements to nest instead of being rendered correctly 556 | // enabling htmlparser2 option xmlMode resolves this issue 557 | expect(parse('<ul><li/><li/></ul>', { xmlMode: true })).toEqual({ 558 | components: [], 559 | nodes: [{ type: NodeType.Html, data: '<ul><li/><li/></ul>' }], 560 | }); 561 | }); 562 | }); 563 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./.svelte-kit/tsconfig.json", 3 | "compilerOptions": { 4 | "allowJs": true, 5 | "checkJs": true, 6 | "esModuleInterop": true, 7 | "forceConsistentCasingInFileNames": true, 8 | "resolveJsonModule": true, 9 | "skipLibCheck": true, 10 | "sourceMap": true, 11 | "strict": true, 12 | "module": "NodeNext", 13 | "moduleResolution": "NodeNext" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /vite.config.ts: -------------------------------------------------------------------------------- 1 | import { sveltekit } from '@sveltejs/kit/vite'; 2 | import { defineConfig } from 'vite'; 3 | 4 | export default defineConfig({ 5 | plugins: [sveltekit()], 6 | }); 7 | --------------------------------------------------------------------------------