Repository: developit/htm Branch: master Commit: d62dcfdc721e Files: 38 Total size: 102.6 KB Directory structure: gitextract_72kckve2/ ├── .github/ │ └── workflows/ │ ├── compressed-size.yml │ └── test.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── babel.config.js ├── package.json ├── packages/ │ ├── babel-plugin-htm/ │ │ ├── README.md │ │ ├── index.mjs │ │ └── package.json │ └── babel-plugin-transform-jsx-to-htm/ │ ├── README.md │ ├── index.mjs │ └── package.json ├── src/ │ ├── build.mjs │ ├── cjs.mjs │ ├── constants-mini.mjs │ ├── constants.mjs │ ├── index.d.ts │ ├── index.mjs │ └── integrations/ │ ├── preact/ │ │ ├── index.d.ts │ │ ├── index.mjs │ │ ├── package.json │ │ └── standalone.mjs │ └── react/ │ ├── index.d.ts │ ├── index.mjs │ └── package.json └── test/ ├── __d8.mjs ├── __perftest.mjs ├── babel-transform-jsx.test.mjs ├── babel.test.mjs ├── fixtures/ │ └── esm/ │ ├── index.js │ └── package.json ├── index.test.mjs ├── perf.test.mjs ├── preact.test.mjs └── statics-caching.test.mjs ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/compressed-size.yml ================================================ name: Compressed Size on: [pull_request] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: preactjs/compressed-size-action@v2 with: pattern: "./{dist,mini,react,preact}/{index.js,index.mjs,htm.js,htm.mjs,standalone.js,standalone.mjs}" ================================================ FILE: .github/workflows/test.yml ================================================ name: Unit Tests on: [pull_request, push] jobs: build: runs-on: ubuntu-latest strategy: matrix: # Change the condition for ESM Dist Test below when changing this. node-version: [12.x, 14.x] steps: - name: Checkout uses: actions/checkout@v2 - name: Use Node.js ${{ matrix.node-version }} uses: actions/setup-node@v1 with: node-version: ${{ matrix.node-version }} - name: Install run: npm install - name: Build and Test run: npm test - if: matrix.node-version == '14.x' name: ESM Dist Test run: npm run test:dist ================================================ FILE: .gitignore ================================================ node_modules package-lock.json /preact /react dist mini yarn.lock htm.tgz ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at jason@developit.ca. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq ================================================ FILE: CONTRIBUTING.md ================================================ # How to Contribute We'd love to accept your patches and contributions to this project. There are just a few small guidelines you need to follow. ## Contributor License Agreement Contributions to this project must be accompanied by a Contributor License Agreement. You (or your employer) retain the copyright to your contribution, this simply gives us permission to use and redistribute your contributions as part of the project. Head over to to see your current agreements on file or to sign a new one. You generally only need to submit a CLA once, so if you've already submitted one (even if it was for a different project), you probably don't need to do it again. ## Code reviews All submissions, including submissions by project members, require review. We use GitHub pull requests for this purpose. Consult [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more information on using pull requests. ## Community Guidelines This project follows [Google's Open Source Community Guidelines](https://opensource.google.com/conduct/). ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2018 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================

HTM (Hyperscript Tagged Markup) npm

hyperscript tagged markup demo

`htm` is **JSX-like syntax in plain JavaScript** - no transpiler necessary. Develop with React/Preact directly in the browser, then compile `htm` away for production. It uses standard JavaScript [Tagged Templates] and works in [all modern browsers]. ## `htm` by the numbers: 🐣 **< 600 bytes** when used directly in the browser ⚛️ **< 500 bytes** when used with Preact _(thanks gzip 🌈)_ 🥚 **< 450 byte** `htm/mini` version 🏅 **0 bytes** if compiled using [babel-plugin-htm] ## Syntax: like JSX but also lit The syntax you write when using HTM is as close as possible to JSX: - Spread props: `
` instead of `
` - Self-closing tags: `
` - Components: `<${Foo}>` instead of `` _(where `Foo` is a component reference)_ - Boolean attributes: `
` ## Improvements over JSX `htm` actually takes the JSX-style syntax a couple steps further! Here's some ergonomic features you get for free that aren't present in JSX: - **No transpiler necessary** - HTML's optional quotes: `
` - Component end-tags: `<${Footer}>footer content` - Syntax highlighting and language support via the [lit-html VSCode extension] and [vim-jsx-pretty plugin]. - Multiple root element (fragments): `
` - Support for HTML-style comments: `
` ## Installation `htm` is published to npm, and accessible via the unpkg.com CDN: **via npm:** ```js npm i htm ``` **hotlinking from unpkg:** _(no build tool needed!)_ ```js import htm from 'https://unpkg.com/htm?module' const html = htm.bind(React.createElement); ``` ```js // just want htm + preact in a single file? there's a highly-optimized version of that: import { html, render } from 'https://unpkg.com/htm/preact/standalone.module.js' ``` ## Usage If you're using Preact or React, we've included off-the-shelf bindings to make your life easier. They also have the added benefit of sharing a template cache across all modules. ```js import { render } from 'preact'; import { html } from 'htm/preact'; render(html`Hello!`, document.body); ``` Similarly, for React: ```js import ReactDOM from 'react-dom'; import { html } from 'htm/react'; ReactDOM.render(html`Hello!`, document.body); ``` ### Advanced Usage Since `htm` is a generic library, we need to tell it what to "compile" our templates to. You can bind `htm` to any function of the form `h(type, props, ...children)` _([hyperscript])_. This function can return anything - `htm` never looks at the return value. Here's an example `h()` function that returns tree nodes: ```js function h(type, props, ...children) { return { type, props, children }; } ``` To use our custom `h()` function, we need to create our own `html` tag function by binding `htm` to our `h()` function: ```js import htm from 'htm'; const html = htm.bind(h); ``` Now we have an `html()` template tag that can be used to produce objects in the format we created above. Here's the whole thing for clarity: ```js import htm from 'htm'; function h(type, props, ...children) { return { type, props, children }; } const html = htm.bind(h); console.log( html`

Hello world!

` ); // { // type: 'h1', // props: { id: 'hello' }, // children: ['Hello world!'] // } ``` If the template has multiple element at the root level the output is an array of `h` results: ```js console.log(html`

Hello

World!
`); // [ // { // type: 'h1', // props: { id: 'hello' }, // children: ['Hello'] // }, // { // type: 'div', // props: { class: 'world' }, // children: ['world!'] // } // ] ``` ### Caching The default build of `htm` caches template strings, which means that it can return the same Javascript object at multiple points in the tree. If you don't want this behaviour, you have three options: * Change your `h` function to copy nodes when needed. * Add the code `this[0] = 3;` at the beginning of your `h` function, which disables caching of created elements. * Use `htm/mini`, which disables caching by default. ## Example Curious to see what it all looks like? Here's a working app! It's a single HTML file, and there's no build or tooling. You can edit it with nano. ```html htm Demo ``` [⚡️ **See live version** ▶](https://htm-demo-preact.glitch.me/) [⚡️ **Try this on CodeSandbox** ▶](https://codesandbox.io/s/x7pmq32j6q) How nifty is that? Notice there's only one import - here we're using the prebuilt Preact integration since it's easier to import and a bit smaller. The same example works fine without the prebuilt version, just using two imports: ```js import { h, Component, render } from 'preact'; import htm from 'htm'; const html = htm.bind(h); render(html`<${App} page="All" />`, document.body); ``` ## Other Uses Since `htm` is designed to meet the same need as JSX, you can use it anywhere you'd use JSX. **Generate HTML using [vhtml]:** ```js import htm from 'htm'; import vhtml from 'vhtml'; const html = htm.bind(vhtml); console.log( html`

Hello world!

` ); // '

Hello world!

' ``` **Webpack configuration via [jsxobj]:** ([details here](https://webpack.js.org/configuration/configuration-languages/#babel-and-jsx)) _(never do this)_ ```js import htm from 'htm'; import jsxobj from 'jsxobj'; const html = htm.bind(jsxobj); console.log(html` `); // { // watch: true, // mode: 'production', // entry: { // path: 'src/index.js' // } // } ``` ## Demos & Examples - [Canadian Holidays](https://github.com/pcraig3/hols): A full app using HTM and Server-Side Rendering - [HTM SSR Example](https://github.com/timarney/htm-ssr-demo): Shows how to do SSR with HTM - [HTM + Preact SSR Demo](https://gist.github.com/developit/699c8d8f180a1e4eed58167f9c6711be) - [HTM + vhtml SSR Demo](https://gist.github.com/developit/ff925c3995b4a129b6b977bf7cd12ebd) ## Project Status The original goal for `htm` was to create a wrapper around Preact that felt natural for use untranspiled in the browser. I wanted to use Virtual DOM, but I wanted to eschew build tooling and use ES Modules directly. This meant giving up JSX, and the closest alternative was [Tagged Templates]. So, I wrote this library to patch up the differences between the two as much as possible. The technique turns out to be framework-agnostic, so it should work great with any library or renderer that works with JSX. `htm` is stable, fast, well-tested and ready for production use. [Tagged Templates]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_templates [lit-html]: https://github.com/Polymer/lit-html [babel-plugin-htm]: https://github.com/developit/htm/tree/master/packages/babel-plugin-htm [lit-html VSCode extension]: https://marketplace.visualstudio.com/items?itemName=bierner.lit-html [vim-jsx-pretty plugin]: https://github.com/MaxMEllon/vim-jsx-pretty [vhtml]: https://github.com/developit/vhtml [jsxobj]: https://github.com/developit/jsxobj [hyperscript]: https://github.com/hyperhype/hyperscript [all modern browsers]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Browser_compatibility ================================================ FILE: babel.config.js ================================================ module.exports = { presets: [ [ '@babel/preset-env', { targets: { node: 'current' } } ] ] }; ================================================ FILE: package.json ================================================ { "name": "htm", "version": "3.1.1", "description": "The Tagged Template syntax for Virtual DOM. Only browser-compatible syntax.", "main": "dist/htm.js", "umd:main": "dist/htm.umd.js", "module": "dist/htm.module.js", "types": "dist/htm.d.ts", "exports": { ".": { "types": "./dist/htm.d.ts", "browser": "./dist/htm.module.js", "umd": "./dist/htm.umd.js", "import": "./dist/htm.mjs", "require": "./dist/htm.js" }, "./": "./", "./preact": { "types": "./preact/index.d.ts", "browser": "./preact/index.module.js", "umd": "./preact/index.umd.js", "import": "./preact/index.mjs", "require": "./preact/index.js" }, "./preact/standalone": { "types": "./preact/index.d.ts", "browser": "./preact/standalone.module.js", "umd": "./preact/standalone.umd.js", "import": "./preact/standalone.mjs", "require": "./preact/standalone.js" }, "./react": { "types": "./react/index.d.ts", "browser": "./react/index.module.js", "umd": "./react/index.umd.js", "import": "./react/index.mjs", "require": "./react/index.js" }, "./mini": { "types": "./mini/index.d.ts", "browser": "./mini/index.module.js", "umd": "./mini/index.umd.js", "import": "./mini/index.mjs", "require": "./mini/index.js" } }, "scripts": { "build": "npm run -s build:main && npm run -s build:mini && npm run -s build:preact && npm run -s build:react && npm run -s build:babel && npm run -s build:babel-transform-jsx && npm run -s build:mjsalias", "build:main": "microbundle src/index.mjs -f es,umd --no-sourcemap --target web && microbundle src/cjs.mjs -f iife --no-sourcemap --target web && cp src/index.d.ts dist/htm.d.ts", "build:mini": "microbundle src/index.mjs -o ./mini/index.js -f es,umd --no-sourcemap --target web --alias ./constants.mjs=./constants-mini.mjs && microbundle src/cjs.mjs -o ./mini/index.js -f iife --no-sourcemap --target web --alias ./constants.mjs=./constants-mini.mjs && cp src/index.d.ts mini", "build:preact": "cd src/integrations/preact && npm run build", "build:react": "cd src/integrations/react && npm run build", "build:babel": "cd packages/babel-plugin-htm && npm run build", "build:babel-transform-jsx": "cd packages/babel-plugin-transform-jsx-to-htm && npm run build", "build:mjsalias": "cp dist/htm.module.js dist/htm.mjs && cp mini/index.module.js mini/index.mjs && cp preact/index.module.js preact/index.mjs && cp preact/standalone.module.js preact/standalone.mjs && cp react/index.module.js react/index.mjs", "test": "eslint src/**/*.mjs test/**/*.mjs --ignore-path .gitignore && npm run build && jest test", "test:perf": "v8 test/__perftest.mjs", "test:dist": "npm pack && mv htm*.tgz test/fixtures/esm/htm.tgz && cd test/fixtures/esm && npm install && node index.js", "release": "npm t && git commit -am \"$npm_package_version\" && git tag $npm_package_version && git push && git push --tags && npm publish" }, "files": [ "dist", "mini", "preact", "react", "src" ], "eslintConfig": { "extends": "developit", "rules": { "prefer-const": 0, "prefer-spread": 0, "prefer-rest-params": 0, "func-style": 0 } }, "jest": { "testURL": "http://localhost", "testMatch": [ "**/__tests__/**/*.?(m)js?(x)", "**/?(*.)(spec|test).?(m)js?(x)" ], "transform": { "\\.m?js$": "babel-jest" }, "moduleFileExtensions": [ "mjs", "js" ], "moduleNameMapper": { "^babel-plugin-transform-jsx-to-htm$": "/packages/babel-plugin-transform-jsx-to-htm/index.mjs", "^babel-plugin-htm$": "/packages/babel-plugin-htm/index.mjs", "^htm$": "/src/index.mjs", "^htm/preact$": "/src/integrations/preact/index.mjs" } }, "repository": "developit/htm", "keywords": [ "Hyperscript Tagged Markup", "tagged template", "template literals", "html", "htm", "jsx", "virtual dom", "hyperscript" ], "author": "Jason Miller ", "license": "Apache-2.0", "homepage": "https://github.com/developit/htm", "devDependencies": { "@babel/core": "^7.2.2", "@babel/preset-env": "^7.1.6", "@types/jest": "^26.0.24", "babel-jest": "^24.1.0", "babel-preset-env": "^1.7.0", "eslint": "^5.2.0", "eslint-config-developit": "^1.1.1", "jest": "^24.1.0", "microbundle": "^0.10.1", "preact": "^10.2.0", "react": "^16.8.3" } } ================================================ FILE: packages/babel-plugin-htm/README.md ================================================ # `babel-plugin-htm` A Babel plugin that compiles [htm] syntax to hyperscript, React.createElement, or just plain objects. ## Usage In your Babel configuration (`.babelrc`, `babel.config.js`, `"babel"` field in package.json, etc), add the plugin: ```js { "plugins": [ ["htm", { "pragma": "React.createElement" }] ] } ``` ```js // input: html`
hello ${you}
` // output: React.createElement("div", { id: "foo" }, "hello ", you) ``` ## options ### `pragma` The target "hyperscript" function to compile elements to (see [Babel docs]). Defaults to: `"h"`. ### `tag=html` By default, `babel-plugin-htm` will process all Tagged Templates with a tag function named `html`. To use a different name, use the `tag` option in your Babel configuration: ```js {"plugins":[ ["babel-plugin-htm", { "tag": "myCustomHtmlFunction" }] ]} ``` ### `import=false` _(experimental)_ Auto-import the pragma function, off by default. #### `false` (default) Don't auto-import anything. #### `String` Import the `pragma` like `import {} from ''`. With Babel config: ```js "plugins": [ ["babel-plugin-htm", { "tag": "$$html", "import": "htm/preact" }] ] ``` ```js import { html as $$html } from 'htm/preact'; export default $$html`
hello ${you}
` ``` The above will produce files that look like: ```js import { h } from 'preact'; import { html as $$html } from 'htm/preact'; export default h("div", { id: "foo" }, "hello ", you) ``` #### `{module: String, export: String}` Import the `pragma` like `import { as } from ''`. With Babel config: ```js "plugins": [ ["babel-plugin-htm", { "pragma": "React.createElement", "tag": "$$html", "import": { // the module to import: "module": "react", // a named export to use from that module: "export": "default" } }] ] ``` ```js import { html as $$html } from 'htm/react'; export default $$html`
hello ${you}
` ``` The above will produce files that look like: ```js import React from 'react'; import { html as $$html } from 'htm/react'; export default React.createElement("div", { id: "foo" }, "hello ", you) ``` ### `useBuiltIns=false` `babel-plugin-htm` transforms prop spreads (``) into `Object.assign()` calls. For browser support reasons, Babel's standard `_extends` helper is used by default. To use native `Object.assign` directly, pass `{useBuiltIns:true}`. ### `useNativeSpread=false` `babel-plugin-htm` transforms prop spreads (``) into `{ ...b, x: 'y' }` object spread syntax. For browser support reasons, Babel's standard `_extends` helper is used by default. To use object spread syntax, pass `{useNativeSpread:true}`. This option takes precedence over the `useBuiltIns` option. ### `variableArity=true` By default, `babel-plugin-htm` transpiles to the same output as JSX would, which assumes a target function of the form `h(type, props, ...children)`. If, for the purposes of optimization or simplification, you would like all calls to `h()` to be passed exactly 3 arguments, specify `{variableArity:false}` in your Babel config: ```js html`
` // h('div', null, []) html`
` // h('div', { a: true }, []) html`
b
` // h('div', null, ['b']) html`
b
` // h('div', { a: true }, ['b']) ``` ### `pragma=false` _(experimental)_ Setting `pragma` to `false` changes the output to be plain objects instead of `h()` function calls: ```js // input: html`
hello ${you}
` // output: { tag:"div", props:{ id: "foo" }, children:["hello ", you] } ``` ### `monomorphic` _(experimental)_ Like `pragma=false` but converts all inline text to objects, resulting in the same object shape being used: ```js // input: html`
hello ${you}
` // output: { type: 1, tag:"div", props:{ id: "foo" }, text: null, children:[ { type: 3, tag: null, props: null, text: "hello ", children: null }, you ] } ``` [htm]: https://github.com/developit/htm [Babel docs]: https://babeljs.io/docs/en/babel-plugin-transform-react-jsx#pragma ================================================ FILE: packages/babel-plugin-htm/index.mjs ================================================ import { build, treeify } from '../../src/build.mjs'; /** * @param {Babel} babel * @param {object} options * @param {string} [options.pragma=h] JSX/hyperscript pragma. * @param {string} [options.tag=html] The tagged template "tag" function name to process. * @param {string | boolean | object} [options.import=false] Import the tag automatically * @param {boolean} [options.monomorphic=false] Output monomorphic inline objects instead of using String literals. * @param {boolean} [options.useBuiltIns=false] Use the native Object.assign instead of trying to polyfill it. * @param {boolean} [options.useNativeSpread=false] Use the native { ...a, ...b } syntax for prop spreads. * @param {boolean} [options.variableArity=true] If `false`, always passes exactly 3 arguments to the pragma function. */ export default function htmBabelPlugin({ types: t }, options = {}) { const pragmaString = options.pragma===false ? false : options.pragma || 'h'; const pragma = pragmaString===false ? false : dottedIdentifier(pragmaString); const useBuiltIns = options.useBuiltIns; const useNativeSpread = options.useNativeSpread; const inlineVNodes = options.monomorphic || pragma===false; const importDeclaration = pragmaImport(options.import || false); function pragmaImport(imp) { if (pragmaString === false || imp === false) { return null; } const pragmaRoot = t.identifier(pragmaString.split('.')[0]); const { module, export: export_ } = typeof imp !== 'string' ? imp : { module: imp, export: null }; let specifier; if (export_ === '*') { specifier = t.importNamespaceSpecifier(pragmaRoot); } else if (export_ === 'default') { specifier = t.importDefaultSpecifier(pragmaRoot); } else { specifier = t.importSpecifier(pragmaRoot, export_ ? t.identifier(export_) : pragmaRoot); } return t.importDeclaration([specifier], t.stringLiteral(module)); } function dottedIdentifier(keypath) { const path = keypath.split('.'); let out; for (let i=0; i { const values = obj[key].map(valueOrNode => t.isNode(valueOrNode) ? valueOrNode : t.valueToNode(valueOrNode) ); let node = values[0]; if (values.length > 1 && !t.isStringLiteral(node) && !t.isStringLiteral(values[1])) { node = t.binaryExpression('+', t.stringLiteral(''), node); } values.slice(1).forEach(value => { node = t.binaryExpression('+', node, value); }); return t.objectProperty(propertyName(key), node); }); } function stringValue(str) { if (options.monomorphic) { return t.objectExpression([ t.objectProperty(propertyName('type'), t.numericLiteral(3)), t.objectProperty(propertyName('tag'), t.nullLiteral()), t.objectProperty(propertyName('props'), t.nullLiteral()), t.objectProperty(propertyName('children'), t.nullLiteral()), t.objectProperty(propertyName('text'), t.stringLiteral(str)) ]); } return t.stringLiteral(str); } function createVNode(tag, props, children) { // Never pass children=[[]]. if (children.elements.length === 1 && t.isArrayExpression(children.elements[0]) && children.elements[0].elements.length === 0) { children = children.elements[0]; } if (inlineVNodes) { return t.objectExpression([ options.monomorphic && t.objectProperty(propertyName('type'), t.numericLiteral(1)), t.objectProperty(propertyName('tag'), tag), t.objectProperty(propertyName('props'), props), t.objectProperty(propertyName('children'), children), options.monomorphic && t.objectProperty(propertyName('text'), t.nullLiteral()) ].filter(Boolean)); } // Passing `{variableArity:false}` always produces `h(tag, props, children)` - where `children` is always an Array. // Otherwise, the default is `h(tag, props, ...children)`. if (options.variableArity !== false) { children = children.elements; } return t.callExpression(pragma, [tag, props].concat(children)); } function spreadNode(args, state) { if (args.length === 0) { return t.nullLiteral(); } if (args.length > 0 && t.isNode(args[0])) { args.unshift({}); } // 'Object.assign(x)', can be collapsed to 'x'. if (args.length === 1) { return propsNode(args[0]); } // 'Object.assign({}, x)', can be collapsed to 'x'. if (args.length === 2 && !t.isNode(args[0]) && Object.keys(args[0]).length === 0) { return propsNode(args[1]); } if (useNativeSpread) { const properties = []; args.forEach(arg => { if (t.isNode(arg)) { properties.push(t.spreadElement(arg)); } else { properties.push(...objectProperties(arg)); } }); return t.objectExpression(properties); } const helper = useBuiltIns ? dottedIdentifier('Object.assign') : state.addHelper('extends'); return t.callExpression(helper, args.map(propsNode)); } function propsNode(props) { return t.isNode(props) ? props : t.objectExpression(objectProperties(props)); } function transform(node, state) { if (t.isNode(node)) return node; if (typeof node === 'string') return stringValue(node); if (typeof node === 'undefined') return t.identifier('undefined'); const { tag, props, children } = node; const newTag = typeof tag === 'string' ? t.stringLiteral(tag) : tag; const newProps = spreadNode(props, state); const newChildren = t.arrayExpression(children.map(child => transform(child, state))); return createVNode(newTag, newProps, newChildren); } // The tagged template tag function name we're looking for. // This is static because it's generally assigned via htm.bind(h), // which could be imported from elsewhere, making tracking impossible. const htmlName = options.tag || 'html'; return { name: 'htm', visitor: { Program: { exit(path, state) { if (state.get('hasHtm') && importDeclaration) { path.unshiftContainer('body', importDeclaration); } }, }, TaggedTemplateExpression(path, state) { const tag = path.node.tag.name; if (htmlName[0]==='/' ? patternStringToRegExp(htmlName).test(tag) : tag === htmlName) { const statics = path.node.quasi.quasis.map(e => e.value.raw); const expr = path.node.quasi.expressions; const tree = treeify(build(statics), expr); const node = !Array.isArray(tree) ? transform(tree, state) : t.arrayExpression(tree.map(root => transform(root, state))); path.replaceWith(node); state.set('hasHtm', true); } } } }; } ================================================ FILE: packages/babel-plugin-htm/package.json ================================================ { "name": "babel-plugin-htm", "version": "3.0.0", "description": "Babel plugin to compile htm's Tagged Template syntax to hyperscript or inline VNodes.", "main": "dist/babel-plugin-htm.js", "module": "dist/babel-plugin-htm.mjs", "scripts": { "build": "microbundle index.mjs -f es,cjs --target node --no-compress --no-sourcemap", "prepare": "npm run build" }, "files": [ "dist" ], "repository": { "type": "git", "url": "https://github.com/developit/htm.git", "directory": "packages/babel-plugin-htm" }, "keywords": [ "Hyperscript Tagged Markup", "tagged template", "template literals", "html", "htm", "jsx", "virtual dom", "hyperscript", "babel", "babel plugin", "babel-plugin" ], "author": "Jason Miller ", "license": "Apache-2.0", "homepage": "https://github.com/developit/htm/tree/master/packages/babel-plugin-htm", "dependencies": { "htm": "^3.0.0" }, "devDependencies": { "microbundle": "^0.10.1" } } ================================================ FILE: packages/babel-plugin-transform-jsx-to-htm/README.md ================================================ # babel-plugin-transform-jsx-to-htm This plugin converts JSX into Tagged Templates that work with [htm]. ```js // INPUT: const Foo = () =>

Hello

// OUTPUT: const Foo = () => html`

Hello

` ``` ## Installation Grab it from npm: ```sh npm i -D babel-plugin-transform-jsx-to-htm ``` ... then add it to your Babel config (eg: `.babelrc`): ```js "plugins": [ "babel-plugin-transform-jsx-to-htm" ] ``` ## Options The following options are available: | Option | Type | Default | Description |--------|---------|----------|------------ | `tag` | String | `"html"` | The "tag" function to prefix [Tagged Templates] with. | `import` | `false`\|String\|Object | `false` | Auto-import a tag function, off by default.
_See [Auto-importing a tag function](#auto-importing-the-tag) for an example._ Options are passed to a Babel plugin using a nested Array: ```js "plugins": [ ["babel-plugin-transform-jsx-to-htm", { "tag": "$$html" }] ] ``` ## Auto-importing the tag Want to automatically import `html` into any file that uses JSX? Just use the `import` option: ```js "plugins": [ ["babel-plugin-transform-jsx-to-htm", { "tag": "$$html", "import": { // the module to import: "module": "htm/preact", // a named export to use from that module: "export": "html" } }] ] ``` The above will produce files that look like: ```js import { html as $$html } from 'htm/preact'; export default $$html`

hello

` ``` ### License Apache 2 [htm]: https://github.com/developit/htm ================================================ FILE: packages/babel-plugin-transform-jsx-to-htm/index.mjs ================================================ import jsx from '@babel/plugin-syntax-jsx'; /** * @param {Babel} babel * @param {object} [options] * @param {string} [options.tag='html'] The tagged template "tag" function name to produce. * @param {boolean} [options.terse=false] Use `` for closing component tags * @param {string | boolean | object} [options.import=false] Import the tag automatically */ export default function jsxToHtmBabelPlugin({ types: t }, options = {}) { const tagString = options.tag || 'html'; const tag = dottedIdentifier(tagString); const importDeclaration = tagImport(options.import || false); const terse = options.terse === true; function tagImport(imp) { if (imp === false) { return null; } const tagRoot = t.identifier(tagString.split('.')[0]); const { module, export: export_ } = typeof imp !== 'string' ? imp : { module: imp, export: null }; let specifier; if (export_ === '*') { specifier = t.importNamespaceSpecifier(tagRoot); } else if (export_ === 'default') { specifier = t.importDefaultSpecifier(tagRoot); } else { specifier = t.importSpecifier(tagRoot, export_ ? t.identifier(export_) : tagRoot); } return t.importDeclaration([specifier], t.stringLiteral(module)); } function dottedIdentifier(keypath) { const path = keypath.split('.'); let out; for (let i = 0; i < path.length; i++) { const ident = t.identifier(path[i]); out = i === 0 ? ident : t.memberExpression(out, ident); } return out; } let quasis = []; let expressions = []; function expr(value) { expressions.push(value); quasis.push(t.templateElement({ raw: '', cooked: '' })); } function raw(str) { const last = quasis[quasis.length - 1]; last.value.raw += str; last.value.cooked += str; } function escapeText(text) { if (text.indexOf('<') < 0) { return raw(text); } return expr(t.stringLiteral(text)); } function escapePropValue(node) { const value = node.value; if (value.match(/^.*$/u)) { if (value.indexOf('"') < 0) { return raw(`"${value}"`); } else if (value.indexOf("'") < 0) { return raw(`'${value}'`); } } return expr(t.stringLiteral(node.value)); } const FRAGMENT_EXPR = dottedIdentifier('React.Fragment'); function isFragmentName(node) { return t.isNodesEquivalent(FRAGMENT_EXPR, node); } function isComponentName(node) { if (t.isJSXNamespacedName(node)) return false; return !t.isIdentifier(node) || node.name.match(/^[$_A-Z]/); } function getNameExpr(node) { if (t.isJSXNamespacedName(node)) { return t.identifier(node.namespace.name + ':' + node.name.name); } if (!t.isJSXMemberExpression(node)) { return t.identifier(node.name); } return t.memberExpression( getNameExpr(node.object), t.identifier(node.property.name) ); } function processChildren(node, name, isFragment) { const children = t.react.buildChildren(node); if (children && children.length !== 0) { if (!isFragment) { raw('>'); } for (let i = 0; i < children.length; i++) { let child = children[i]; if (t.isStringLiteral(child)) { escapeText(child.value); } else if (t.isJSXElement(child)) { processNode(child); } else { expr(child); } } if (!isFragment) { if (isComponentName(name)) { if (terse) { raw(''); } else { raw(''); } } else { raw(''); } } } else if (!isFragment) { raw('/>'); } } function processNode(node, path, isRoot) { const open = node.openingElement; const name = getNameExpr(open.name); const isFragment = isFragmentName(name); if (!isFragment) { if (isComponentName(name)) { raw('<'); expr(name); } else { raw('<'); raw(name.name); } if (open.attributes) { for (let i = 0; i < open.attributes.length; i++) { const attr = open.attributes[i]; raw(' '); if (t.isJSXSpreadAttribute(attr)) { raw('...'); expr(attr.argument); continue; } const { name, value } = attr; if (t.isJSXNamespacedName(name)) { raw(name.namespace.name + ':' + name.name.name); } else { raw(name.name); } if (value) { raw('='); if (value.expression) { expr(value.expression); } else if (t.isStringLiteral(value)) { escapePropValue(value); } else { expr(value); } } } } } processChildren(node, name, isFragment); if (isRoot) { const template = t.templateLiteral(quasis, expressions); const replacement = t.taggedTemplateExpression(tag, template); path.replaceWith(replacement); } } function jsxVisitorHandler(path, state, isFragment) { let quasisBefore = quasis; let expressionsBefore = expressions; quasis = [t.templateElement({ raw: '', cooked: '' })]; expressions = []; if (isFragment) { processChildren(path.node, null, true); const template = t.templateLiteral(quasis, expressions); const replacement = t.taggedTemplateExpression(tag, template); path.replaceWith(replacement); } else { processNode(path.node, path, true); } quasis = quasisBefore; expressions = expressionsBefore; state.set('jsxElement', true); } return { name: 'transform-jsx-to-htm', inherits: jsx, visitor: { Program: { exit(path, state) { if (state.get('jsxElement') && importDeclaration) { path.unshiftContainer('body', importDeclaration); } } }, JSXElement(path, state) { jsxVisitorHandler(path, state, false); }, JSXFragment(path, state) { jsxVisitorHandler(path, state, true); } } }; } ================================================ FILE: packages/babel-plugin-transform-jsx-to-htm/package.json ================================================ { "name": "babel-plugin-transform-jsx-to-htm", "version": "2.2.0", "description": "Babel plugin to compile JSX to Tagged Templates.", "main": "dist/babel-plugin-transform-jsx-to-htm.js", "scripts": { "build": "microbundle index.mjs -f cjs --target node --no-compress --no-sourcemap", "prepare": "npm run build" }, "files": [ "dist" ], "repository": { "type": "git", "url": "https://github.com/developit/htm.git", "directory": "packages/babel-plugin-transform-jsx-to-htm" }, "keywords": [ "tagged template", "template literals", "html", "htm", "jsx", "virtual dom", "hyperscript", "babel", "babel plugin", "babel-plugin" ], "author": "Jason Miller ", "license": "Apache-2.0", "homepage": "https://github.com/developit/htm/tree/master/packages/babel-plugin-transform-jsx-to-htm", "dependencies": { "@babel/plugin-syntax-jsx": "^7.2.0", "htm": "^3.0.0" }, "devDependencies": { "microbundle": "^0.10.1" } } ================================================ FILE: src/build.mjs ================================================ import { MINI } from './constants.mjs'; const MODE_SLASH = 0; const MODE_TEXT = 1; const MODE_WHITESPACE = 2; const MODE_TAGNAME = 3; const MODE_COMMENT = 4; const MODE_PROP_SET = 5; const MODE_PROP_APPEND = 6; const CHILD_APPEND = 0; const CHILD_RECURSE = 2; const TAG_SET = 3; const PROPS_ASSIGN = 4; const PROP_SET = MODE_PROP_SET; const PROP_APPEND = MODE_PROP_APPEND; // Turn a result of a build(...) call into a tree that is more // convenient to analyze and transform (e.g. Babel plugins). // For example: // treeify( // build`
<${x} />
`, // [X, Y, Z] // ) // returns: // { // tag: 'div', // props: [ { href: ["1", X] }, Y ], // children: [ { tag: Z, props: [], children: [] } ] // } export const treeify = (built, fields) => { const _treeify = built => { let tag = ''; let currentProps = null; const props = []; const children = []; for (let i = 1; i < built.length; i++) { const type = built[i++]; const value = built[i] ? fields[built[i++]-1] : built[++i]; if (type === TAG_SET) { tag = value; } else if (type === PROPS_ASSIGN) { props.push(value); currentProps = null; } else if (type === PROP_SET) { if (!currentProps) { currentProps = Object.create(null); props.push(currentProps); } currentProps[built[++i]] = [value]; } else if (type === PROP_APPEND) { currentProps[built[++i]].push(value); } else if (type === CHILD_RECURSE) { children.push(_treeify(value)); } else if (type === CHILD_APPEND) { children.push(value); } } return { tag, props, children }; }; const { children } = _treeify(built); return children.length > 1 ? children : children[0]; }; export const evaluate = (h, built, fields, args) => { let tmp; // `build()` used the first element of the operation list as // temporary workspace. Now that `build()` is done we can use // that space to track whether the current element is "dynamic" // (i.e. it or any of its descendants depend on dynamic values). built[0] = 0; for (let i = 1; i < built.length; i++) { const type = built[i++]; // Set `built[0]`'s appropriate bits if this element depends on a dynamic value. const value = built[i] ? ((built[0] |= type ? 1 : 2), fields[built[i++]]) : built[++i]; if (type === TAG_SET) { args[0] = value; } else if (type === PROPS_ASSIGN) { args[1] = Object.assign(args[1] || {}, value); } else if (type === PROP_SET) { (args[1] = args[1] || {})[built[++i]] = value; } else if (type === PROP_APPEND) { args[1][built[++i]] += (value + ''); } else if (type) { // type === CHILD_RECURSE // Set the operation list (including the staticness bits) as // `this` for the `h` call. tmp = h.apply(value, evaluate(h, value, fields, ['', null])); args.push(tmp); if (value[0]) { // Set the 2nd lowest bit it the child element is dynamic. built[0] |= 2; } else { // Rewrite the operation list in-place if the child element is static. // The currently evaluated piece `CHILD_RECURSE, 0, [...]` becomes // `CHILD_APPEND, 0, tmp`. // Essentially the operation list gets optimized for potential future // re-evaluations. built[i-2] = CHILD_APPEND; built[i] = tmp; } } else { // type === CHILD_APPEND args.push(value); } } return args; }; export const build = function(statics) { const fields = arguments; const h = this; let mode = MODE_TEXT; let buffer = ''; let quote = ''; let current = [0]; let char, propName; const commit = field => { if (mode === MODE_TEXT && (field || (buffer = buffer.replace(/^\s*\n\s*|\s*\n\s*$/g,'')))) { if (MINI) { current.push(field ? fields[field] : buffer); } else { current.push(CHILD_APPEND, field, buffer); } } else if (mode === MODE_TAGNAME && (field || buffer)) { if (MINI) { current[1] = field ? fields[field] : buffer; } else { current.push(TAG_SET, field, buffer); } mode = MODE_WHITESPACE; } else if (mode === MODE_WHITESPACE && buffer === '...' && field) { if (MINI) { current[2] = Object.assign(current[2] || {}, fields[field]); } else { current.push(PROPS_ASSIGN, field, 0); } } else if (mode === MODE_WHITESPACE && buffer && !field) { if (MINI) { (current[2] = current[2] || {})[buffer] = true; } else { current.push(PROP_SET, 0, true, buffer); } } else if (mode >= MODE_PROP_SET) { if (MINI) { if (mode === MODE_PROP_SET) { (current[2] = current[2] || {})[propName] = field ? buffer ? (buffer + fields[field]) : fields[field] : buffer; mode = MODE_PROP_APPEND; } else if (field || buffer) { current[2][propName] += field ? buffer + fields[field] : buffer; } } else { if (buffer || (!field && mode === MODE_PROP_SET)) { current.push(mode, 0, buffer, propName); mode = MODE_PROP_APPEND; } if (field) { current.push(mode, field, 0, propName); mode = MODE_PROP_APPEND; } } } buffer = ''; }; for (let i=0; i' if (buffer === '--' && char === '>') { mode = MODE_TEXT; buffer = ''; } else { buffer = char + buffer[0]; } } else if (quote) { if (char === quote) { quote = ''; } else { buffer += char; } } else if (char === '"' || char === "'") { quote = char; } else if (char === '>') { commit(); mode = MODE_TEXT; } else if (!mode) { // Ignore everything until the tag ends } else if (char === '=') { mode = MODE_PROP_SET; propName = buffer; buffer = ''; } else if (char === '/' && (mode < MODE_PROP_SET || statics[i][j+1] === '>')) { commit(); if (mode === MODE_TAGNAME) { current = current[0]; } mode = current; if (MINI) { (current = current[0]).push(h.apply(null, mode.slice(1))); } else { (current = current[0]).push(CHILD_RECURSE, 0, mode); } mode = MODE_SLASH; } else if (char === ' ' || char === '\t' || char === '\n' || char === '\r') { //
commit(); mode = MODE_WHITESPACE; } else { buffer += char; } if (mode === MODE_TAGNAME && buffer === '!--') { mode = MODE_COMMENT; current = current[0]; } } } commit(); if (MINI) { return current.length > 2 ? current.slice(1) : current[1]; } return current; }; ================================================ FILE: src/cjs.mjs ================================================ import htm from './index.mjs'; if (typeof module != 'undefined') module.exports = htm; else self.htm = htm; ================================================ FILE: src/constants-mini.mjs ================================================ export const MINI = true; ================================================ FILE: src/constants.mjs ================================================ export const MINI = false; ================================================ FILE: src/index.d.ts ================================================ declare const htm: { bind( h: (type: any, props: Record, ...children: any[]) => HResult ): (strings: TemplateStringsArray, ...values: any[]) => HResult | HResult[]; }; export default htm; ================================================ FILE: src/index.mjs ================================================ /** * Copyright 2018 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { MINI } from './constants.mjs'; import { build, evaluate } from './build.mjs'; const CACHES = new Map(); const regular = function(statics) { let tmp = CACHES.get(this); if (!tmp) { tmp = new Map(); CACHES.set(this, tmp); } tmp = evaluate(this, tmp.get(statics) || (tmp.set(statics, tmp = build(statics)), tmp), arguments, []); return tmp.length > 1 ? tmp : tmp[0]; }; export default MINI ? build : regular; ================================================ FILE: src/integrations/preact/index.d.ts ================================================ import { h, VNode, Component } from 'preact'; export * from 'preact/hooks'; declare function render(tree: VNode, parent: HTMLElement): void; declare const html: (strings: TemplateStringsArray, ...values: any[]) => VNode; export { h, html, render, Component }; ================================================ FILE: src/integrations/preact/index.mjs ================================================ /** * Copyright 2018 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { h, Component, render } from 'preact'; import htm from 'htm'; const html = htm.bind(h); export { h, html, render, Component }; ================================================ FILE: src/integrations/preact/package.json ================================================ { "name": "htm_preact", "module": "index.module.js", "main": "index.js", "umd:main": "index.umd.js", "unpkg": "standalone.js", "scripts": { "build": "npm run -s build:main && npm run -s build:standalone && npm run -s build:static", "build:main": "microbundle index.mjs -o ../../../preact/index.js --external preact,htm --no-sourcemap --target web", "build:static": "cp index.d.ts package.json ../../../preact/", "build:standalone": "microbundle standalone.mjs -o ../../../preact/standalone.js -f es,umd --no-sourcemap --target web" } } ================================================ FILE: src/integrations/preact/standalone.mjs ================================================ /** * Copyright 2018 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { h, Component, createContext, createRef, render } from 'preact'; import { useState, useReducer, useEffect, useLayoutEffect, useRef, useImperativeHandle, useMemo, useCallback, useContext, useDebugValue, useErrorBoundary } from 'preact/hooks'; import htm from '../../index.mjs'; const html = htm.bind(h); export { h, html, render, Component, createContext, createRef, useState, useReducer, useEffect, useLayoutEffect, useRef, useImperativeHandle, useMemo, useCallback, useContext, useDebugValue, useErrorBoundary }; ================================================ FILE: src/integrations/react/index.d.ts ================================================ import * as React from 'react'; declare const html: (strings: TemplateStringsArray, ...values: any[]) => React.ReactElement; ================================================ FILE: src/integrations/react/index.mjs ================================================ /** * Copyright 2018 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { createElement } from 'react'; import htm from 'htm'; export const html = htm.bind(createElement); ================================================ FILE: src/integrations/react/package.json ================================================ { "name": "htm_react", "module": "index.module.js", "main": "index.js", "umd:main": "index.umd.js", "unpkg": "index.js", "scripts": { "build": "npm run -s build:main && npm run -s build:static", "build:main": "microbundle index.mjs -o ../../../react/index.js --external react,htm --no-sourcemap --target web", "build:static": "cp index.d.ts package.json ../../../react/" } } ================================================ FILE: test/__d8.mjs ================================================ /*global globalThis*/ const queue = []; let stack = []; let index = 0; async function process() { const id = index++; if (id === queue.length) { queue.length = index = 0; return; } const [op, name, fn, extra] = queue[id]; queue[id] = undefined; await processors[op](name, fn, extra); await process(); } const processors = { async describe(name, fn, path) { stack.push(name); log('INFO', name); await fn(); stack.pop(); }, async test(name, fn, path) { let stackBefore = stack; stack = path.concat(name); logBuffer = []; await new Promise(resolve => { let calls = 0; const done = () => { if (calls++) throw Error(`Callback called multiple times\n\t${name}`); log('INFO', `✅ ${name}`); resolve(); }; Promise.resolve(done) .then(fn) .then(() => calls || done()) .catch(err => { log('ERROR', `🚨 ${name}`); log('ERROR', '\t' + String(err.stack || err.message || err)); resolve(); }); }); for (let i=0; i { push('describe', name, fn, stack.slice()); }; globalThis.test = (name, fn) => { push('test', name, fn, stack.slice()); }; globalThis.expect = (subject) => new Expect(subject); const SUBJECT = Symbol.for('subject'); const NEGATED = Symbol.for('negated'); class Expect { constructor(subject) { this[SUBJECT] = subject; } get not() { this[NEGATED] = true; return this; } toBeGreaterThan(value) { const subject = this[SUBJECT]; const negated = this[NEGATED]; const isOver = subject > value; let msg = `Expected ${subject}${negated?' not':''} to be greater than ${value}`; if (logBuffer) { for (let i=logBuffer.length; i-- > -1; ) { if (i<0 || logBuffer[i][2] === 1) { logBuffer.splice(i+1, 0, [isOver !== negated ? 'SUCCESS' : 'ERROR', ' ' + msg, 1]); break; } } } else { log(isOver !== negated ? 'SUCCESS' : 'ERROR', ' ' + msg); } } } ================================================ FILE: test/__perftest.mjs ================================================ import './__d8.mjs'; import './perf.test.mjs'; ================================================ FILE: test/babel-transform-jsx.test.mjs ================================================ import { transform } from '@babel/core'; import transformJsxToHtmPlugin from 'babel-plugin-transform-jsx-to-htm'; function compile(code, { plugins = [], ...options } = {}) { return transform(code, { babelrc: false, configFile: false, sourceType: 'module', plugins: [ ...plugins, [transformJsxToHtmPlugin, options] ] }).code; } describe('babel-plugin-transform-jsx-to-htm', () => { describe('import', () => { test('import shortcut', () => { expect( compile(`(
);`, { import: 'htm/preact' }) ).toBe('import { html } from "htm/preact";\nhtml`
`;'); }); test('import shortcut, dotted tag', () => { expect( compile(`(
);`, { tag: 'html.bound', import: 'htm/preact' }) ).toBe('import { html } from "htm/preact";\nhtml.bound`
`;'); }); test('named import', () => { expect( compile(`(
);`, { import: { module: 'htm/preact', export: '$html' } }) ).toBe('import { $html as html } from "htm/preact";\nhtml`
`;'); }); test('named import, dotted tag', () => { expect( compile(`(
);`, { tag: 'html.bound', import: { module: 'htm/preact', export: '$html' } }) ).toBe('import { $html as html } from "htm/preact";\nhtml.bound`
`;'); }); test('default import', () => { expect( compile(`(
);`, { import: { module: 'htm/preact', export: 'default' } }) ).toBe('import html from "htm/preact";\nhtml`
`;'); }); test('namespace import', () => { expect( compile(`(
);`, { import: { module: 'htm/preact', export: '*' } }) ).toBe('import * as html from "htm/preact";\nhtml`
`;'); }); test('no import without JSX', () => { expect( compile(`false;`, { import: 'htm/preact' }) ).toBe('false;'); }); }); describe('elements and text', () => { test('single named element', () => { expect( compile('(
);') ).toBe('html`
`;'); expect( compile('(
a
);') ).toBe('html`
a
`;'); expect( compile('();') ).toBe('html``;'); expect( compile('(a);') ).toBe('html`a`;'); expect( compile('();') ).toBe('html``;'); expect( compile('(a);') ).toBe('html`a`;'); }); test('single component element', () => { expect( compile('();') ).toBe('html`<${Foo}/>`;'); expect( compile('(a);') ).toBe('html`<${Foo}>a`;'); expect( compile('(<$ />);') ).toBe('html`<${$}/>`;'); expect( compile('(<$>a);') ).toBe('html`<${$}>a`;'); expect( compile('(<_ />);') ).toBe('html`<${_}/>`;'); expect( compile('(<_>a);') ).toBe('html`<${_}>a`;'); expect( compile('(<_foo />);') ).toBe('html`<${_foo}/>`;'); expect( compile('(<_foo>a);') ).toBe('html`<${_foo}>a`;'); expect( compile('(<$foo />);') ).toBe('html`<${$foo}/>`;'); expect( compile('(<$foo>a);') ).toBe('html`<${$foo}>a`;'); }); test('dotted component element', () => { expect( compile('();') ).toBe('html`<${a.b.c}/>`;'); expect( compile('(a);') ).toBe('html`<${a.b.c}>a`;'); }); test('namespaced element names', () => { expect( compile('();') ).toBe('html``;'); expect( compile('();') ).toBe('html``;'); }); test('namespaced attributes', () => { expect( compile('();') ).toBe('html``;'); expect( compile('(h);') ).toBe('html`
h`;'); }); test('static text', () => { expect( compile(`(
Hello
);`) ).toBe('html`
Hello
`;'); expect( compile(`(
こんにちわ
);`) ).toBe('html`
こんにちわ
`;'); }); test('HTML entities get unescaped', () => { expect( compile(`(
&
);`) ).toBe('html`
&
`;'); }); test('< gets wrapped into an expression container', () => { expect( compile(`(
a<b<<<c
);`) ).toBe('html`
${"a`;'); }); }); describe('fragments', () => { test('React.Fragment', () => { expect( compile(`
Foo
Bar
`) ).toBe('html`
Foo
Bar
`;'); }); test('short syntax', () => { expect( compile(`<>
Foo
Bar
`) ).toBe('html`
Foo
Bar
`;'); }); test('root expressions', () => { expect( compile(`{Foo}{Bar}`) ).toBe('html`${Foo}${Bar}`;'); }); test('short syntax fragments should not crash due to TemplateLiteral quasi/expression unbalance', () => { expect( compile(`<>{Bar}`) ).toBe('html`<${Foo}/>${Bar}`;'); }); }); describe('props', () => { test('static values', () => { expect( compile('(
);') ).toBe('html`
`;'); expect( compile('(
);') ).toBe('html`
`;'); }); test('HTML entities get unescaped', () => { expect( compile(`(
);`) ).toBe('html`
`;'); }); test('double quote values with single quotes', () => { expect( compile(`(
);`) ).toBe(`html\`
\`;`); }); test('single quote values with double quotes', () => { expect( compile(`(
);`) ).toBe(`html\`
\`;`); }); test('escape values with newlines as expressions', () => { expect( compile(`(
);`) ).toBe('html`
`;'); }); test('escape values with both single and double quotes as expressions', () => { expect( compile(`(
);`) ).toBe('html`
`;'); }); test('expression values', () => { expect( compile('const Foo = (props, a) =>
;') ).toBe('const Foo = (props, a) => html`
`;'); }); test('spread', () => { expect( compile('const Foo = props =>
;') ).toBe('const Foo = props => html`
`;'); expect( compile('(
);') ).toBe('html`
`;'); expect( compile('(
);') ).toBe('html`
`;'); }); }); describe('nesting', () => { test('element children are merged into one template', () => { expect( compile('const Foo = () =>
\n

Hello

\n

world.

\n
;') ).toBe('const Foo = () => html`

Hello

world.

`;'); }); test('inter-element whitespace is collapsed similarly to the JSX plugin', () => { expect( compile('const Foo = props =>
a \n b \n B c d e
;') ).toBe('const Foo = props => html`
a b B c d e
`;'); }); test('nested JSX Expressions produce nested templates', () => { expect( compile('const Foo = props =>
    {props.items.map(item =>\n
  • \n {item}\n
  • \n)}
;') ).toBe('const Foo = props => html`
    ${props.items.map(item => html`
  • ${item}
  • `)}
`;'); }); test('empty expressions are ignored', () => { expect( compile(`(
{/* a comment */}
);`) ).toBe('html`
`;'); }); }); }); ================================================ FILE: test/babel.test.mjs ================================================ /** * @jest-environment node */ import { transform } from '@babel/core'; import htmBabelPlugin from 'babel-plugin-htm'; const options = { babelrc: false, configFile: false, sourceType: 'script', compact: true }; describe('htm/babel', () => { test('basic transformation', () => { expect( transform('html`
hello
`;', { ...options, plugins: [ htmBabelPlugin ] }).code ).toBe(`h("div",{id:"hello"},"hello");`); }); test('basic transformation with variable', () => { expect( transform('var name="world";html`
hello, ${name}
`;', { ...options, plugins: [ htmBabelPlugin ] }).code ).toBe(`var name="world";h("div",{id:"hello"},"hello, ",name);`); }); test('basic nested transformation', () => { expect( transform('html`d: ${4}`;', { ...options, plugins: [ [htmBabelPlugin, { useBuiltIns: true }] ] }).code ).toBe(`h("a",Object.assign({b:2},{c:3}),"d: ",4);`); expect( transform('html`d: ${4}`;', { ...options, plugins: [ [htmBabelPlugin, { useNativeSpread: true }] ] }).code ).toBe(`h("a",{b:2,...{c:3}},"d: ",4);`); }); test('spread a single variable', () => { expect( transform('html``;', { ...options, plugins: [ htmBabelPlugin ] }).code ).toBe(`h("a",foo);`); expect( transform('html``;', { ...options, plugins: [ [htmBabelPlugin, { useNativeSpread: true }] ] }).code ).toBe(`h("a",foo);`); }); test('spread two variables', () => { expect( transform('html``;', { ...options, plugins: [ [htmBabelPlugin, { useBuiltIns: true }] ] }).code ).toBe(`h("a",Object.assign({},foo,bar));`); expect( transform('html``;', { ...options, plugins: [ [htmBabelPlugin, { useNativeSpread: true }] ] }).code ).toBe(`h("a",{...foo,...bar});`); }); test('property followed by a spread', () => { expect( transform('html``;', { ...options, plugins: [ [htmBabelPlugin, { useBuiltIns: true }] ] }).code ).toBe(`h("a",Object.assign({b:"1"},foo));`); expect( transform('html``;', { ...options, plugins: [ [htmBabelPlugin, { useNativeSpread: true }] ] }).code ).toBe(`h("a",{b:"1",...foo});`); }); test('spread followed by a property', () => { expect( transform('html``;', { ...options, plugins: [ [htmBabelPlugin, { useBuiltIns: true }] ] }).code ).toBe(`h("a",Object.assign({},foo,{b:"1"}));`); expect( transform('html``;', { ...options, plugins: [ [htmBabelPlugin, { useNativeSpread: true }] ] }).code ).toBe(`h("a",{...foo,b:"1"});`); }); test('mix-and-match spreads', () => { expect( transform('html``;', { ...options, plugins: [ [htmBabelPlugin, { useBuiltIns: true }] ] }).code ).toBe(`h("a",Object.assign({b:"1"},foo,{c:2},{d:3}));`); expect( transform('html``;', { ...options, plugins: [ [htmBabelPlugin, { useNativeSpread: true }] ] }).code ).toBe(`h("a",{b:"1",...foo,c:2,...{d:3}});`); }); test('mix-and-match dynamic and static values', () => { expect( transform('html``;', { ...options, plugins: [ [htmBabelPlugin, { useBuiltIns: true }] ] }).code ).toBe(`h("a",{b:"1"+2+3});`); expect( transform('html``;', { ...options, plugins: [ [htmBabelPlugin, { useNativeSpread: true }] ] }).code ).toBe(`h("a",{b:"1"+2+3});`); }); test('coerces props to strings when needed', () => { expect( transform('html``;', { ...options, plugins: [ [htmBabelPlugin, { useBuiltIns: true }] ] }).code ).toBe(`h("a",{b:""+1+2+"3"+4});`); expect( transform('html``;', { ...options, plugins: [ [htmBabelPlugin, { useNativeSpread: true }] ] }).code ).toBe(`h("a",{b:""+1+2+"3"+4});`); }); test('coerces props to strings only when needed', () => { expect( transform('html``;', { ...options, plugins: [ [htmBabelPlugin, { useBuiltIns: true }] ] }).code ).toBe(`h("a",{b:"1"+2+"3"+4});`); expect( transform('html``;', { ...options, plugins: [ [htmBabelPlugin, { useNativeSpread: true }] ] }).code ).toBe(`h("a",{b:"1"+2+"3"+4});`); }); describe('{variableArity:false}', () => { test('should pass no children as an empty Array', () => { expect( transform('html`
`;', { ...options, plugins: [ [htmBabelPlugin, { variableArity: false }] ] }).code ).toBe(`h("div",null,[]);`); }); test('should pass children as an Array', () => { expect( transform('html`
hello
`;', { ...options, plugins: [ [htmBabelPlugin, { variableArity: false }] ] }).code ).toBe(`h("div",{id:"hello"},["hello"]);`); }); }); describe('{pragma:false}', () => { test('should transform to inline vnodes', () => { expect( transform('var name="world",vnode=html`
hello, ${name}
`;', { ...options, plugins: [ [htmBabelPlugin, { pragma: false }] ] }).code ).toBe(`var name="world",vnode={tag:"div",props:{id:"hello"},children:["hello, ",name]};`); }); }); describe('{monomorphic:true}', () => { test('should transform to monomorphic inline vnodes', () => { expect( transform('var name="world",vnode=html`
hello, ${name}
`;', { ...options, plugins: [ [htmBabelPlugin, { monomorphic: true }] ] }).code ).toBe(`var name="world",vnode={type:1,tag:"div",props:{id:"hello"},children:[{type:3,tag:null,props:null,children:null,text:"hello, "},name],text:null};`); }); }); describe('{import:"preact"}', () => { test('should do nothing when pragma=false', () => { expect( transform('var name="world",vnode=html`
hello, ${name}
`;', { ...options, plugins: [ [htmBabelPlugin, { pragma: false, import: 'preact' }] ] }).code ).toBe(`var name="world",vnode={tag:"div",props:{id:"hello"},children:["hello, ",name]};`); }); test('should do nothing when tag is not used', () => { expect( transform('console.log("hi");', { ...options, plugins: [ [htmBabelPlugin, { import: 'preact' }] ] }).code ).toBe(`console.log("hi");`); }); test('should add import', () => { expect( transform('html`
hello
`;', { ...options, plugins: [ [htmBabelPlugin, { import: 'preact' }] ] }).code ).toBe(`import{h}from"preact";h("div",{id:"hello"},"hello");`); }); test('should add import for pragma', () => { expect( transform('html`
hello
`;', { ...options, plugins: [ [htmBabelPlugin, { pragma: 'createElement', import: 'react' }] ] }).code ).toBe(`import{createElement}from"react";createElement("div",{id:"hello"},"hello");`); }); }); describe('{import:Object}', () => { test('should add import', () => { expect( transform('html`
hello
`;', { ...options, plugins: [ [htmBabelPlugin, { import: { module: 'preact', export: 'h' } }] ] }).code ).toBe(`import{h}from"preact";h("div",{id:"hello"},"hello");`); }); test('should add import as pragma', () => { expect( transform('html`
hello
`;', { ...options, plugins: [ [htmBabelPlugin, { pragma: 'hh', import: { module: 'preact', export: 'h' } }] ] }).code ).toBe(`import{h as hh}from"preact";hh("div",{id:"hello"},"hello");`); }); test('should add import default', () => { expect( transform('html`
hello
`;', { ...options, plugins: [ [htmBabelPlugin, { pragma: 'React.createElement', import: { module: 'react', export: 'default' } }] ] }).code ).toBe(`import React from"react";React.createElement("div",{id:"hello"},"hello");`); }); test('should add import *', () => { expect( transform('html`
hello
`;', { ...options, plugins: [ [htmBabelPlugin, { pragma: 'Preact.h', import: { module: 'preact', export: '*' } }] ] }).code ).toBe(`import*as Preact from"preact";Preact.h("div",{id:"hello"},"hello");`); }); }); describe('main test suite', () => { // Run all of the main tests against the Babel plugin: const mod = require('fs').readFileSync(require('path').resolve(__dirname, 'index.test.mjs'), 'utf8').replace(/\\0/g, '\0'); const { code } = transform(mod.replace(/^\s*import\s*.+?\s*from\s+(['"]).*?\1[\s;]*$/im, 'const htm = function(){};'), { ...options, plugins: [htmBabelPlugin] }); eval(code); }); }); ================================================ FILE: test/fixtures/esm/index.js ================================================ import assert from 'assert'; import htm from 'htm'; import * as preact from 'htm/preact'; import * as standalone from 'htm/preact/standalone'; // TODO: Enable once react distro is ESM compatible. // import * as react 'htm/react'; assert(typeof htm === 'function', 'import htm from "htm"'); assert(typeof preact.html === 'function', 'import { html } from "preact"'); assert(typeof standalone.html === 'function', 'import { html } from "preact/standalone"'); console.log('✅ Dist Tests Passed'); ================================================ FILE: test/fixtures/esm/package.json ================================================ { "name": "htm_dist_test", "type": "module", "private": true, "description": "A package to test importing htm as ES modules in Node", "dependencies": { "htm": "file:htm.tgz", "preact": "^10.4.1" } } ================================================ FILE: test/index.test.mjs ================================================ /** * Copyright 2018 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import htm from '../src/index.mjs'; const h = (tag, props, ...children) => ({ tag, props, children }); const html = htm.bind(h); describe('htm', () => { test('empty', () => { expect(html``).toEqual(undefined); }); test('single named elements', () => { expect(html`
`).toEqual({ tag: 'div', props: null, children: [] }); expect(html`
`).toEqual({ tag: 'div', props: null, children: [] }); expect(html``).toEqual({ tag: 'span', props: null, children: [] }); }); test('multiple root elements', () => { expect(html``).toEqual([ { tag: 'a', props: null, children: [] }, { tag: 'b', props: null, children: [] }, { tag: 'c', props: null, children: [] } ]); }); test('single dynamic tag name', () => { expect(html`<${'foo'} />`).toEqual({ tag: 'foo', props: null, children: [] }); function Foo () {} expect(html`<${Foo} />`).toEqual({ tag: Foo, props: null, children: [] }); }); test('single boolean prop', () => { expect(html``).toEqual({ tag: 'a', props: { disabled: true }, children: [] }); }); test('two boolean props', () => { expect(html``).toEqual({ tag: 'a', props: { invisible: true, disabled: true }, children: [] }); }); test('single prop with empty value', () => { expect(html``).toEqual({ tag: 'a', props: { href: '' }, children: [] }); }); test('two props with empty values', () => { expect(html``).toEqual({ tag: 'a', props: { href: '', foo: '' }, children: [] }); }); test('single prop with empty name', () => { expect(html``).toEqual({ tag: 'a', props: { '': 'foo' }, children: [] }); }); test('single prop with static value', () => { expect(html``).toEqual({ tag: 'a', props: { href: '/hello' }, children: [] }); }); test('single prop with static value followed by a single boolean prop', () => { expect(html``).toEqual({ tag: 'a', props: { href: '/hello', b: true }, children: [] }); }); test('two props with static values', () => { expect(html``).toEqual({ tag: 'a', props: { href: '/hello', target: '_blank' }, children: [] }); }); test('single prop with dynamic value', () => { expect(html``).toEqual({ tag: 'a', props: { href: 'foo' }, children: [] }); }); test('slash in the middle of tag name or property name self-closes the element', () => { expect(html``).toEqual({ tag: 'ab', props: null, children: [] }); expect(html``).toEqual({ tag: 'abba', props: { pr: true }, children: [] }); }); test('slash in a property value does not self-closes the element, unless followed by >', () => { expect(html``).toEqual({ tag: 'abba', props: { prop: 'val/ue' }, children: [] }); expect(html``).toEqual({ tag: 'abba', props: { prop: 'value' }, children: [] }); expect(html``).toEqual({ tag: 'abba', props: { prop: 'value/' }, children: [] }); }); test('two props with dynamic values', () => { function onClick(e) { } expect(html``).toEqual({ tag: 'a', props: { href: 'foo', onClick }, children: [] }); }); test('prop with multiple static and dynamic values get concatenated as strings', () => { expect(html``).toEqual({ tag: 'a', props: { href: 'beforefooafter' }, children: [] }); expect(html``).toEqual({ tag: 'a', props: { href: '11' }, children: [] }); expect(html``).toEqual({ tag: 'a', props: { href: '1between1' }, children: [] }); expect(html``).toEqual({ tag: 'a', props: { href: '/before/foo/after' }, children: [] }); expect(html``).toEqual({ tag: 'a', props: { href: '/before/foo' }, children: [] }); }); test('spread props', () => { expect(html``).toEqual({ tag: 'a', props: { foo: 'bar' }, children: [] }); expect(html``).toEqual({ tag: 'a', props: { b: true, foo: 'bar' }, children: [] }); expect(html``).toEqual({ tag: 'a', props: { b: true, c: true, foo: 'bar' }, children: [] }); expect(html``).toEqual({ tag: 'a', props: { b: true, foo: 'bar' }, children: [] }); expect(html``).toEqual({ tag: 'a', props: { b: '1', foo: 'bar' }, children: [] }); expect(html``).toEqual(h('a', { x: '1' }, h('b', { y: '2', c: 'bar' }) )); expect(html`d: ${4}`).toEqual(h('a',{ b: 2, c: 3 }, 'd: ', 4)); expect(html``).toEqual(h('a', { c: 'bar' }, h('b', { d: 'baz' }) )); }); test('multiple spread props in one element', () => { expect(html``).toEqual({ tag: 'a', props: { foo: 'bar', quux: 'baz' }, children: [] }); }); test('mixed spread + static props', () => { expect(html``).toEqual({ tag: 'a', props: { b: true, foo: 'bar' }, children: [] }); expect(html``).toEqual({ tag: 'a', props: { b: true, c: true, foo: 'bar' }, children: [] }); expect(html``).toEqual({ tag: 'a', props: { b: true, foo: 'bar' }, children: [] }); expect(html``).toEqual({ tag: 'a', props: { b: true, c: true, foo: 'bar' }, children: [] }); }); test('closing tag', () => { expect(html``).toEqual({ tag: 'a', props: null, children: [] }); expect(html``).toEqual({ tag: 'a', props: { b: true }, children: [] }); }); test('auto-closing tag', () => { expect(html``).toEqual({ tag: 'a', props: null, children: [] }); }); test('non-element roots', () => { expect(html`foo`).toEqual('foo'); expect(html`${1}`).toEqual(1); expect(html`foo${1}`).toEqual(['foo', 1]); expect(html`foo${1}bar`).toEqual(['foo', 1, 'bar']); }); test('text child', () => { expect(html`foo`).toEqual({ tag: 'a', props: null, children: ['foo'] }); expect(html`foo bar`).toEqual({ tag: 'a', props: null, children: ['foo bar'] }); expect(html`foo "`).toEqual({ tag: 'a', props: null, children: ['foo "', { tag: 'b', props: null, children: [] }] }); }); test('dynamic child', () => { expect(html`${'foo'}`).toEqual({ tag: 'a', props: null, children: ['foo'] }); }); test('mixed text + dynamic children', () => { expect(html`${'foo'}bar`).toEqual({ tag: 'a', props: null, children: ['foo', 'bar'] }); expect(html`before${'foo'}after`).toEqual({ tag: 'a', props: null, children: ['before', 'foo', 'after'] }); expect(html`foo${null}`).toEqual({ tag: 'a', props: null, children: ['foo', null] }); }); test('element child', () => { expect(html``).toEqual(h('a', null, h('b', null))); }); test('multiple element children', () => { expect(html``).toEqual(h('a', null, h('b', null), h('c', null))); expect(html``).toEqual(h('a', { x: true }, h('b', { y: true }), h('c', { z: true }))); expect(html``).toEqual(h('a', { x: '1' }, h('b', { y: '2' }), h('c', { z: '3' }))); expect(html``).toEqual(h('a', { x: 1 }, h('b', { y: 2 }), h('c', { z: 3 }))); }); test('mixed typed children', () => { expect(html`foo`).toEqual(h('a', null, 'foo', h('b', null))); expect(html`bar`).toEqual(h('a', null, h('b', null), 'bar')); expect(html`beforeafter`).toEqual(h('a', null, 'before', h('b', null), 'after')); expect(html`beforeafter`).toEqual(h('a', null, 'before', h('b', { x: '1' }), 'after')); expect(html` before ${'foo'} ${'bar'} after `).toEqual(h('a', null, 'before', 'foo', h('b', null), 'bar', 'after')); }); test('hyphens (-) are allowed in attribute names', () => { expect(html``).toEqual(h('a', { 'b-c': true })); }); test('NUL characters are allowed in attribute values', () => { expect(html``).toEqual(h('a', { b: '\0' })); expect(html``).toEqual(h('a', { b: '\0', c: 'foo' })); }); test('NUL characters are allowed in text', () => { expect(html`\0`).toEqual(h('a', null, '\0')); expect(html`\0${'foo'}`).toEqual(h('a', null, '\0', 'foo')); }); test('cache key should be unique', () => { html``; expect(html``).toEqual(h('a', { b: '\0' })); expect(html`${''}9aaaaaaaaa${''}`).not.toEqual(html`${''}0${''}aaaaaaaaa${''}`); expect(html`${''}0${''}aaaaaaaa${''}`).not.toEqual(html`${''}.8aaaaaaaa${''}`); }); test('do not mutate spread variables', () => { const obj = {}; html``; expect(obj).toEqual({}); }); test('ignore HTML comments', () => { expect(html``).toEqual(h('a', null)); expect(html``).toEqual(h('a', null)); expect(html``).toEqual(h('a', null)); expect(html` Hello, world `).toEqual(h('a', null)); }); }); ================================================ FILE: test/perf.test.mjs ================================================ /** * Copyright 2018 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import htm from '../src/index.mjs'; const h = (tag, props, ...children) => ({ tag, props, children }); const html = htm.bind(h); describe('performance', () => { test('creation', () => { const results = []; const Foo = ({ name }) => html`
${name}
`; let count = 0; function go(count) { const statics = [ '\n
\n\t

Hello World

\n\t
    \n\t', '\n\t
\n\t\n\t<', ' name="foo" />\n\t<', ' name="other">content\n\n
' ]; return html( statics, `id${count}`, html`
  • ${'some text #' + count}
  • `, Foo, Foo ); } let now = performance.now(); const start = now; while ((now = performance.now()) < start+1000) { count++; if (results.push(String(go(count)))===10) results.length = 0; } const elapsed = now - start; const hz = count / elapsed * 1000; // eslint-disable-next-line no-console console.log(`Creation: ${(hz|0).toLocaleString()}/s, average: ${elapsed/count*1000|0}µs`); expect(elapsed).toBeGreaterThan(999); expect(hz).toBeGreaterThan(1000); }); test('usage', () => { const results = []; const Foo = ({ name }) => html`
    ${name}
    `; let count = 0; function go(count) { return html`

    Hello World

      ${html`
    • ${'some text #' + count}
    • `}
    <${Foo} name="foo" /> <${Foo} name="other">content
    `; } let now = performance.now(); const start = now; while ((now = performance.now()) < start+1000) { count++; if (results.push(String(go(count)))===10) results.length = 0; } const elapsed = now - start; const hz = count / elapsed * 1000; // eslint-disable-next-line no-console console.log(`Usage: ${(hz|0).toLocaleString()}/s, average: ${elapsed/count*1000|0}µs`); expect(elapsed).toBeGreaterThan(999); expect(hz).toBeGreaterThan(100000); }); }); ================================================ FILE: test/preact.test.mjs ================================================ /** * Copyright 2018 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { html, Component, render } from 'htm/preact'; const sleep = ms => new Promise(r => setTimeout(r, ms)); describe('htm/preact', () => { const scratch = document.createElement('div'); document.body.appendChild(scratch); class Foo extends Component { render({ name }, { count = 0 }) { return html`

    Name: ${name}

    Hello world!

    Count: ${count}
    xml-style end tags: <${Bar} hello /> explicit end tags: <${Bar} hello>some children (count=${count}) implicit end tags: (${''}) <${Bar} hello>some children (count=${count}) some text at the end
    `; } } const Bar = ({ hello, children }) => html`
    Value of hello: ${hello + ''} ${children}
    `; const Baz = ({ myCaseSensitiveProp }) => html`
    ${myCaseSensitiveProp}
    `; const fullHtml = '

    Name: jason

    Hello world!

    Count: 0
    xml-style end tags:
    Value of hello: true
    explicit end tags:
    Value of hello: truesome children (count=0)
    implicit end tags: (<//>)
    Value of hello: truesome children (count=0)
    some text at the end
    '; test('initial render', () => { render(html`<${Foo} name=jason />`, scratch); expect(scratch.innerHTML).toBe(fullHtml); }); test('rerenders in-place', () => { render(html`<${Foo} name=tom />`, scratch); expect(scratch.innerHTML).toBe(fullHtml.replace('jason', 'tom')); }); test('state update re-renders', async () => { document.querySelector('button').click(); document.querySelector('button').click(); await sleep(1); expect(scratch.innerHTML).toBe(fullHtml.replace('jason', 'tom').replace(/\b0\b/g, '2')); }); test('preserves case', () => { scratch.textContent = ''; render(html`<${Baz} myCaseSensitiveProp="Yay!" />`, scratch); expect(scratch.innerHTML).toBe('
    Yay!
    '); }); test('object spreads', () => { scratch.textContent = ''; const props = { a: 1, b: 2, c: 3 }; const other = { d: 4, e: 5, f: 6 }; render(html`
    `, scratch); expect(scratch.innerHTML).toBe(`
    `); scratch.innerHTML = ''; render(html`
    `, scratch); expect(scratch.innerHTML).toBe(`
    `); scratch.innerHTML = ''; render(html`
    `, scratch); expect(scratch.innerHTML).toBe(`
    `); expect(JSON.stringify(props)).toBe(`{"a":1,"b":2,"c":3}`); scratch.innerHTML = ''; render(html`
    `, scratch); expect(scratch.innerHTML).toBe(`
    `); scratch.innerHTML = ''; render(html`
    `, scratch); expect(scratch.innerHTML).toBe(`
    `); scratch.innerHTML = ''; }); // describe('performance', () => { // test('creation', () => { // const results = []; // const Foo = ({ name }) => html`
    ${name}
    `; // const statics = [ // '\n
    \n\t

    Hello World

    \n\t
      \n\t', // '\n\t
    \n\t\n\t<', ' name="foo" />\n\t<', ' name="other">content\n\n
    ' // ]; // let count = 0; // function go(count) { // return html( // statics.concat(['count:', count]), // `id${count}`, // html(['
  • ', '
  • '], 'i'+count, 'some text #'+count), // Foo, Foo, Foo // ); // } // let now = performance.now(); // const start = now; // while ((now = performance.now()) < start+2000) { // count++; // if (results.push(String(go(count)))===10) results.length = 0; // } // const elapsed = now - start; // const hz = count / elapsed * 1000; // // eslint-disable-next-line no-console // console.log(`Creation: ${hz|0}/s, average: ${elapsed/count.toFixed(4)}ms`); // expect(elapsed).toBeGreaterThan(999); // expect(hz).toBeGreaterThan(10); // }); // }); }); ================================================ FILE: test/statics-caching.test.mjs ================================================ /** * Copyright 2018 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import htm from '../src/index.mjs'; const h = (tag, props, ...children) => ({ tag, props, children }); const html = htm.bind(h); describe('htm', () => { test('should cache static subtrees', () => { const x = () => html`
    a
    `; const a = x(); const b = x(); expect(a).toEqual({ tag: 'div', props: null, children: ['a'] }); expect(b).toEqual({ tag: 'div', props: null, children: ['a'] }); expect(a).toBe(b); }); test('should have a different cache for each h', () => { let tmp = htm.bind(() => 1); const x = () => tmp`
    a
    `; const a = x(); tmp = htm.bind(() => 2); const b = x(); expect(a).toBe(1); expect(b).toBe(2); }); describe('`this` in the h function', () => { const html = htm.bind(function() { return this; }); test('stays the same for each call site)', () => { const x = () => html`
    a
    `; const a = x(); const b = x(); expect(a).toBe(b); }); test('is different for each call site', () => { const a = html`
    a
    `; const b = html`
    a
    `; expect(a).not.toBe(b); }); test('is specific to each h function', () => { let tmp = htm.bind(function() { return this; }); const x = () => tmp`
    a
    `; const a = x(); tmp = htm.bind(function() { return this; }); const b = x(); expect(a).not.toBe(b); }); }); describe('`this[0]` in the h function contains the staticness bits', () => { const html = htm.bind(function() { return this[0]; }); test('should be 0 for static subtrees', () => { expect(html`
    `).toBe(0); expect(html`
    a
    `).toBe(0); expect(html`
    `).toBe(0); }); test('should be 2 for static nodes with some dynamic children', () => { expect(html`
    ${'a'}
    `).toBe(2); expect(html`
    `).toBe(2); }); test('should be 1 for dynamic nodes with all static children', () => { expect(html`
    `).toBe(1); }); test('should be 3 for dynamic nodes with some dynamic children', () => { expect(html`
    `).toBe(3); }); }); describe('the h function should be able to modify `this[0]`', () => { function wrapH(h) { return function(type, props, ...children) { if (type === '@static') { this[0] &= ~3; return children; } if (props['@static']) { this[0] &= ~3; } return h(type, props, ...children); }; } test('should be able to force subtrees to be static via a prop', () => { const html = htm.bind(wrapH(h)); const x = () => html`
    ${'a'}
    `; const a = x(); const b = x(); expect(a).toEqual({ tag: 'div', props: { '@static': true }, children: ['a'] }); expect(b).toEqual({ tag: 'div', props: { '@static': true }, children: ['a'] }); expect(a).toBe(b); }); test('should be able to force subtrees to be static via a special tag', () => { const html = htm.bind(wrapH(h)); const x = () => html`<@static>${'a'}`; const a = x(); const b = x(); expect(a).toEqual(['a']); expect(b).toEqual(['a']); expect(a).toBe(b); }); }); });