Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[transformers ] Add @lit/ts-transformers package with idiomatic decorator transform #1919

Merged
merged 42 commits into from
Jul 30, 2021
Merged
Show file tree
Hide file tree
Changes from 28 commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
fad9388
Create new @lit/transformers package
aomarks May 21, 2021
61fe0e3
Add README
aomarks May 21, 2021
653b914
Move compileTsFragment utility from localize-tools into /transformers…
aomarks May 21, 2021
1095f34
@customElement decorator transformer
aomarks May 21, 2021
9d59665
@property decorator transformer
aomarks May 21, 2021
3ff6ae9
@state decorator transformer
aomarks May 21, 2021
c1511b2
@query decorator transformer
aomarks May 21, 2021
6133113
@queryAll decorator transformer
aomarks May 21, 2021
6113887
@queryAsync decorator transformer
aomarks May 21, 2021
7e22e6d
@queryAssignedNodes decorator transformer
aomarks May 21, 2021
f14b6d2
@eventOptions decorator transformer
aomarks May 21, 2021
43e9661
Remove all uses of getText()
aomarks May 21, 2021
69235cc
Delete compile-ts-fragment.ts that should have moved in earlier commit
aomarks May 21, 2021
8f463da
Handle decorator imports more robustly
aomarks May 21, 2021
fddb8fe
Fix incorrect test import
aomarks Jun 10, 2021
f9c045e
Clean up visitor interfaces and location, and use implements
aomarks Jun 11, 2021
5a7159d
Allow visitors to insert additional visitors scoped to the current class
aomarks Jun 11, 2021
0bcb8a2
Add GenericVisitor
aomarks Jun 11, 2021
7f57cec
Transform private @eventOptions to event handler object inside templates
aomarks Jun 11, 2021
f909a04
Transform public/protected eventOptions methods to options Object.assign
aomarks Jun 11, 2021
d32afcf
Be more discriminating about event binding transforms
aomarks Jun 15, 2021
2f8dd3a
Clone existing properties instead of re-using node
aomarks Jun 15, 2021
2fdb6ee
Re-use transformer across files, and skip files with no Lit imports
aomarks Jun 15, 2021
eb769d8
Defer calling getTypeChecker since it is often not needed
aomarks Jun 15, 2021
f71246e
Check html tag by symbol instead of just by name
aomarks Jun 15, 2021
fc5fce1
Refactor into lit file and class contexts
aomarks Jun 15, 2021
4ccf8dc
Add readonly modifiers
aomarks Jun 15, 2021
b1f856a
Misc cleanup
aomarks Jun 15, 2021
d7ecbbf
Merge branch 'main' into transformers
aomarks Jul 15, 2021
2f6ff72
Add missing dependency
aomarks Jul 15, 2021
5b0518c
Improve top-level test script
aomarks Jul 15, 2021
00df50d
Use inline 'as void' pattern instead of unreachable
aomarks Jul 15, 2021
6320b0e
Clean up and rename _analyzeImportDeclaration method
aomarks Jul 15, 2021
fd51d5e
Clarify nodesToRemove check
aomarks Jul 15, 2021
ec25346
Add TODO about re-exports
aomarks Jul 15, 2021
47adc41
Expand LitTransformer class documentation
aomarks Jul 15, 2021
f0d6edd
Rename @lit/transformers to @lit/ts-transformers
aomarks Jul 15, 2021
6deb50a
Merge branch 'main' into transformers
aomarks Jul 29, 2021
7a2e93c
Error on invalid Lit module import style
aomarks Jul 29, 2021
4a1ad16
More concise output for caching @query decorator
aomarks Jul 29, 2021
32e7236
Remove unnecessary attribute:false from state decorator transform
aomarks Jul 29, 2021
823e38a
Remove x typo
aomarks Jul 30, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,8 @@ packages/reactive-element/reactive-controller.*

packages/tests/node_modules/

packages/transformers/lib/

packages/labs/motion/development/
packages/labs/motion/node_modules/
packages/labs/motion/index.*
Expand Down
2 changes: 2 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,8 @@ packages/reactive-element/reactive-controller.*

packages/tests/node_modules/

packages/transformers/lib/

packages/labs/motion/development/
packages/labs/motion/node_modules/
packages/labs/motion/index.*
Expand Down
6 changes: 5 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"lint": "eslint \"**/*.{js,ts}\"",
"nuke": "rm -rf node_modules && npm install && lerna exec 'rm -rf node_modules' && lerna bootstrap && npm run clean",
"upgrade": "rm -rf node_modules package-lock.json && npm install && lerna exec 'rm -rf node_modules package-lock.json' && lerna bootstrap && npm run clean",
"test": "(cd packages/tests && npm test) && (cd packages/labs/ssr && npm test) && (cd packages/localize && npm test) && (cd packages/localize-tools && npm test) && (cd packages/lit-starter-ts && npm test) && (cd packages/lit-starter-js && npm test)",
"test": "(cd packages/tests && npm test) && (cd packages/labs/ssr && npm test) && (cd packages/localize && npm test) && (cd packages/localize-tools && npm test) && (cd packages/lit-starter-ts && npm test) && (cd packages/lit-starter-js && npm test) && (cd packages/transformers && npm test)",
justinfagnani marked this conversation as resolved.
Show resolved Hide resolved
"prepare": "husky install"
},
"devDependencies": {
Expand Down
1 change: 1 addition & 0 deletions packages/localize-tools/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
"xmldom": "^0.5.0"
},
"devDependencies": {
"@lit/transformers": "^0.0.1",
"@types/diff": "^5.0.0",
"@types/fs-extra": "^9.0.1",
"@types/glob": "^7.1.1",
Expand Down
3 changes: 2 additions & 1 deletion packages/localize-tools/src/tests/analysis.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import ts from 'typescript';
import {
createTsProgramFromFragment,
CompilerHostCache,
} from './compile-ts-fragment.js';
} from '@lit/transformers/lib/tests/compile-ts-fragment.js';

const cache = new CompilerHostCache();

Expand All @@ -39,6 +39,7 @@ function checkAnalysis(
options.typeRoots = [];
const {program, host} = createTsProgramFromFragment(
inputTs,
'',
options,
cache,
() => undefined
Expand Down
7 changes: 5 additions & 2 deletions packages/localize-tools/src/tests/transform.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ import {Message, makeMessageIdMap} from '../messages.js';
import {test} from 'uvu';
import * as assert from 'uvu/assert';
import prettier from 'prettier';
import {compileTsFragment, CompilerHostCache} from './compile-ts-fragment.js';
import {
compileTsFragment,
CompilerHostCache,
} from '@lit/transformers/lib/tests/compile-ts-fragment.js';

const cache = new CompilerHostCache();
const IMPORT_MSG = `import { msg, str } from "@lit/localize";\n`;
Expand Down Expand Up @@ -52,7 +55,7 @@ function checkTransform(
// them here, so it's a waste of time.
options.typeRoots = [];
options.experimentalDecorators = true;
const result = compileTsFragment(inputTs, options, cache, (program) => ({
const result = compileTsFragment(inputTs, '', options, cache, (program) => ({
before: [
litLocalizeTransform(
makeMessageIdMap(opts?.messages ?? []),
Expand Down
1 change: 1 addition & 0 deletions packages/transformers/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/lib/
12 changes: 12 additions & 0 deletions packages/transformers/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## Unreleased

### Added

- Initial release of `@lit/transformers`.
28 changes: 28 additions & 0 deletions packages/transformers/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
BSD 3-Clause License

Copyright (c) 2021 Google LLC. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
153 changes: 153 additions & 0 deletions packages/transformers/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
# @lit/transformers

[npm-img]: https://img.shields.io/npm/v/@lit/transformers
[npm-href]: https://www.npmjs.com/package/@lit/transformers
[test-img]: https://github.com/lit/lit/workflows/Tests/badge.svg?branch=master
[test-href]: https://github.com/lit/lit/actions?query=workflow%3ATests+branch%3Amaster+event%3Apush

[![Published on NPM][npm-img]][npm-href]
[![Test status][test-img]][test-href]

TypeScript transformers for the [Lit decorators](https://lit.dev/docs/components/decorators/).

## Example

### Before

```ts
import {LitElement, html} from 'lit';
import {
customElement,
property,
state,
query,
eventOptions,
} from 'lit/decorators.js';

@customElement('simple-greeting')
class SimpleGreeting extends LitElement {
@property()
name = 'Somebody';

@state()
private counter = 0;

@query('#myButton')
button?: HTMLButtonElement;

render() {
return html`
<button id="myButton" @click=${this._onClick}>
Hello ${this.name} (${this.counter})
</button>
`;
}

@eventOptions({capture: true})
private _onClick(event: Event) {
this.counter++;
console.log('click', event.target);
}
}
```

### After

```ts
import {LitElement, html} from 'lit';

class MyElement extends LitElement {
static get properties() {
return {
str: {},
num: {state: true, attribute: false},
};
}

get button() {
return this.renderRoot?.querySelector('#myButton');
}

constructor() {
super(...arguments);
this.name = 'Somebody';
this.counter = 0;
}

render() {
return html`
<button
id="myButton"
@click=${{
handleEvent: (e) => this._onClick(e),
capture: true,
}}
>
Hello ${this.name} (${this.counter})
</button>
`;
}

private _onClick(event: Event) {
this.counter++;
console.log('click', event.target);
}
}

customElements.define('simple-greeting', SimpleGreeting);
```

## Install

```sh
npm i @lit/transformers
```

## Usage

### Option 1: ttypescript

[ttypescript](https://github.com/cevek/ttypescript) wraps the standard
TypeScript compiler and adds the ability to run transformer plugins:

```sh
npm i ttypescript
```

Update your `tsconfig.json`:

```json
{
"compilerOptions": {
"plugins": [
{
"transform": "@lit/transformers/lib/idiomatic.js"
}
]
}
}
```

Now use `tssc` instead of `tsc`:

```sh
npx ttsc
```

### Option 2: TypeScript API

If you are using the [TypeScript compiler
API](https://github.com/microsoft/TypeScript-wiki/blob/master/Using-the-Compiler-API.md),
pass the transformer to the `customTransformers` parameter of `Program.emit`:

```ts
import idiomaticLitDecoratorsTransform from '@lit/transformers/lib/idiomatic.js';
import ts from 'typescript';

// Note this is not a complete example. For more information see
// https://github.com/microsoft/TypeScript-wiki/blob/master/Using-the-Compiler-API.md
const program = ts.createProgram(rootNames, options);
const result = program.emit(undefined, undefined, undefined, undefined, {
before: [idiomaticLitDecoratorTransformer(program)],
});
```
Loading