diff --git a/.eslintrc.json b/.eslintrc.json index d5c785f1..d0b5d929 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -11,7 +11,7 @@ }, "overrides": [ { - "files": "test/*", + "files": "test/**", "rules": { "@typescript-eslint/no-empty-function": "off" }, diff --git a/docs/_guide/attrs.md b/docs/_guide/attrs.md index 2374054c..e17d2e2a 100644 --- a/docs/_guide/attrs.md +++ b/docs/_guide/attrs.md @@ -16,7 +16,7 @@ Catalyst includes the `@attr` decorator, which provides nice syntax sugar to sim - The attribute name is automatically [observed, meaning `attributeChangedCallback` will fire when it changes](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements#using_the_lifecycle_callbacks). - Assigning a value in the class description will make that value the _default_ value, so when the element is connected that value is set (unless the element has the attribute defined already). -To use the `@attr` decorator, attach it to a class field, and it will get/set the value of the matching `data-*` attribute. +To use the `@attr` decorator, attach it to a class field, and it will get/set the value of the matching `data-*` attribute. With [standard decorators]({{ site.baseurl }}/guide/decorators#standard-decorators), `@attr` needs decorator metadata support, which TypeScript has from version 5.2. ### Example @@ -150,6 +150,9 @@ When an element gets connected to the DOM, the attr is initialized. During this - If the class property has a value, that is the _default_ - When connected, if the element _does not_ have a matching attribute, the default _is_ applied. - When connected, if the element _does_ have a matching attribute, the default _is not_ applied, the property will be assigned to the value of the attribute instead. + - Field and `accessor` attrs are initialized first, in the order they're registered. Getter and setter attrs come next, starting with those that have a matching attribute, so a getter's default can read the other attrs' values. + - With legacy decorators, Catalyst can't tell an `accessor` from a getter and setter you wrote, so only a getter without a setter counts as a getter attr. Any attr with a setter initializes in registration order, as in earlier versions. + - Standard decorators register `accessor` attrs before field attrs, whatever order they're declared in. To initialize attrs in declaration order, as legacy decorators do, decorate fields, not accessors: `@attr name!: string`. {% capture callout %} Remember! The values defined in the class field are the _default_. They won't be set if the element is created and its attribute set to a custom value! diff --git a/docs/_guide/decorators.md b/docs/_guide/decorators.md index e27f2f3d..56c085e9 100644 --- a/docs/_guide/decorators.md +++ b/docs/_guide/decorators.md @@ -5,7 +5,7 @@ title: Decorators subtitle: Using TypeScript for ergonomics --- -Decorators are used heavily in Catalyst, because they provide really clean ergonomics and makes using the library a lot easier. Decorators are a special, (currently) non standard, feature of TypeScript. You'll need to turn the `experimentalDecorators` option on inside of your TypeScript project to use them (if you're using `@babel/plugin-proposal-decorators` plugin, you need to use [`legacy` option](https://babeljs.io/docs/en/babel-plugin-proposal-decorators#legacy)). +Decorators are used heavily in Catalyst, because they provide really clean ergonomics and makes using the library a lot easier. Catalyst's decorators work with both TypeScript's legacy `experimentalDecorators` option (or the `@babel/plugin-proposal-decorators` [`legacy` option](https://babeljs.io/docs/en/babel-plugin-proposal-decorators#legacy)) and [standard decorators](#standard-decorators). The same imports work in both modes. You can read more about [decorators in the TypeScript handbook](https://www.typescriptlang.org/docs/handbook/decorators.html), but here's quick guide: @@ -83,6 +83,45 @@ class HelloWorldElement extends HTMLElement { } ``` +### Standard decorators + +TypeScript 5.0+ and SWC (`decoratorVersion: "2023-11"`) compile standard (TC39) decorators when `experimentalDecorators` is off. `@controller`, `@attr`, `@target` and `@targets` support them, with two differences from legacy decorators: + +- `@target` and `@targets` must decorate an `accessor`. Standard decorators can't decorate `declare` fields, and a plain field would hide the getter the decorator defines: + + ```typescript + @controller + class HelloWorldElement extends HTMLElement { + @target accessor output!: HTMLElement + @targets accessor items!: HTMLElement[] + } + ``` + + Assigning to the accessor throws a `TypeError`, just as assigning to the getter-only legacy property does. +- `@attr` records its fields in [decorator metadata](https://github.com/tc39/proposal-decorator-metadata), so with TypeScript you need version 5.2 or later. `@attr` can decorate a field, an `accessor`, a getter or a setter. Prefer a field, such as `@attr name!: string` in place of a legacy `@attr declare name: string`: standard decorators register accessors before fields, so mixing them changes the order attrs initialize in (see [attrs]({{ site.baseurl }}/guide/attrs#default-values)). + +Catalyst's member decorators only support public, non-static members. `@controller` (and `@register`) define the element once static fields such as `observedAttributes` and `attrPrefix` are assigned, the same as with legacy decorators. + +Without an explicit name, `@controller` derives the element name from the class name, so the class name must survive your build. With standard decorators, TypeScript's output declares the class twice under the same name, and esbuild renames one of them in any transform or bundle, even at the same target. `HelloWorldElement` then becomes `HelloWorldElement2`, and the element is defined as `hello-world-element2` without an error. esbuild's [`keepNames`](https://esbuild.github.io/api/#keep-names) keeps the name from version 0.18.2. Before that, `@controller` sees an empty or internal name, such as `_this`, and defining the element throws. Minifiers rename classes too. + +Passing the tag name, as in `@controller('hello-world')`, avoids all of this, and we recommend it with standard decorators. See [build considerations]({{ site.baseurl }}/guide/you-will-need#build-considerations). + +### Legacy decorators and `useDefineForClassFields` + +With legacy decorators, `@target` and `@targets` define a getter on the class prototype. When `useDefineForClassFields` is on, TypeScript defines each declared field on the instance, which hides that getter, so the target is always `undefined`. TypeScript turns `useDefineForClassFields` on by default when `target` is `ES2022` or later. + +Marking the field with `!` or `?`, or typing it as `| undefined`, still emits the field. Use `declare`, which emits nothing: + +```typescript +@controller +class HelloWorldElement extends HTMLElement { + @target declare output: HTMLElement | undefined + @targets declare items: HTMLElement[] +} +``` + +`@target` returns `undefined` when no element matches, so `| undefined` is the accurate type. `@attr` works either way, because Catalyst redefines `@attr` fields on each instance when it connects. Standard decorators avoid the problem by requiring an [accessor](#standard-decorators). + ### Supporting `strictPropertyInitialization` TypeScript comes with various "strict" mode settings, one of which is `strictPropertyInitialization` which lets TypeScript catch potential class properties which might not be assigned during construction of a class. This option conflicts with Catalyst's `@target`/`@targets` decorators, which safely do the assignment but TypeScript's simple heuristics cannot detect this. There are two ways to work around this: @@ -96,7 +135,7 @@ TypeScript comes with various "strict" mode settings, one of which is `strictPro } ``` - Note that this only works on TypeScript 3.7+, so if you're on an older version, you can also use the [definite initialization operator](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#definite-assignment-assertions) to do the same thing. + Note that this only works on TypeScript 3.7+, so if you're on an older version, you can also use the [definite initialization operator](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#definite-assignment-assertions) to do the same thing, as long as `useDefineForClassFields` is off ([see above](#legacy-decorators-and-usedefineforclassfields)). With [standard decorators](#standard-decorators), use the definite initialization operator on an accessor instead: `@target accessor something!: HTMLElement`. 2. You can also disable the compiler option (other strict mode rules can still apply) in your `tsconfig.json` like so: diff --git a/docs/_guide/targets.md b/docs/_guide/targets.md index 877522b2..4983d39b 100644 --- a/docs/_guide/targets.md +++ b/docs/_guide/targets.md @@ -139,7 +139,7 @@ Important to note here is that nodes from the `shadowRoot` get returned _first_. ### What about without Decorators? -If you're using decorators, then the `@target` and `@targets` decorators will turn the decorated properties into getters. +If you're using decorators, then the `@target` and `@targets` decorators will turn the decorated properties into getters. With [standard decorators]({{ site.baseurl }}/guide/decorators#standard-decorators), decorate an accessor instead of a field: `@target accessor output!: HTMLElement`. If you're not using decorators, then you'll need to make a `getter`, and call `findTarget(this, key)` or `findTargets(this, key)` in the getter, for example: diff --git a/docs/_guide/you-will-need.md b/docs/_guide/you-will-need.md index a56495ee..0f3ca29c 100644 --- a/docs/_guide/you-will-need.md +++ b/docs/_guide/you-will-need.md @@ -8,7 +8,7 @@ Catalyst is available as an npm module `@github/catalyst`. To install into your ### TypeScript -Catalyst has no strict dependencies, but it relies on TypeScript for decorator support, so you should also configure your project to use TypeScript. [Read the TypeScript docs on how to set up TypeScript on a new project](https://www.typescriptlang.org/docs/home.html). +Catalyst has no strict dependencies, but it relies on TypeScript for decorator support, so you should also configure your project to use TypeScript. [Read the TypeScript docs on how to set up TypeScript on a new project](https://www.typescriptlang.org/docs/home.html). Catalyst's decorators work with both the `experimentalDecorators` option and standard decorators; see [Decorators]({{ site.baseurl }}/guide/decorators). ### Polyfills @@ -20,6 +20,8 @@ Catalyst uses modern browser standards, and so requires evergreen browsers or ma Please note this list may increase over time. Catalyst will never ship with polyfills that add missing browser functionality, but will continue to use the latest Web Standards, and so may require more polyfills as new releases come out. +The one exception is `Symbol.metadata`, which [standard decorators]({{ site.baseurl }}/guide/decorators#standard-decorators) use to store metadata. TypeScript only attaches decorator metadata when `Symbol.metadata` exists, so if it is missing, Catalyst defines it as `Symbol.for('Symbol.metadata')` when it loads. That is the key SWC's and Babel's decorator helpers fall back to. Lit also defines `Symbol.metadata` when it is missing. + ### Build considerations When using build tools, some JavaScript minifiers modify the class name that Catalyst relies on. You know you have an issue if you encounter the error `"c" is not a valid custom element name`. @@ -30,6 +32,8 @@ The preferred way to handle this is to disable renaming class names in your buil When using ESBuild you can turn off all class and function name minification with the [`keep_names`](https://esbuild.github.io/api/#keep-names) option. Setting this to `true` in your build will opt-out all classes and all functions from minification. +With [standard decorators]({{ site.baseurl }}/guide/decorators#standard-decorators), esbuild renames classes in TypeScript's output even without minification, and `keep_names` only prevents it from esbuild 0.18.2. Passing a tag name to `@controller` works with every build tool. + ```ts { keep_names: true } diff --git a/package-lock.json b/package-lock.json index 5ced631a..e6a9f3aa 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,8 +14,8 @@ "@open-wc/testing": "^4.0.0", "@size-limit/preset-small-lib": "^8.0.1", "@types/mocha": "^10.0.10", - "@typescript-eslint/eslint-plugin": "^5.36.1", - "@typescript-eslint/parser": "^5.36.1", + "@typescript-eslint/eslint-plugin": "^5.62.0", + "@typescript-eslint/parser": "^5.62.0", "@web/dev-server-esbuild": "^0.3.2", "@web/test-runner": "^0.20.0", "eslint": "^8.23.0", @@ -23,7 +23,7 @@ "sinon": "^14.0.0", "size-limit": "^8.0.1", "tslib": "^2.4.0", - "typescript": "^4.8.2" + "typescript": "^5.9.3" } }, "node_modules/@babel/code-frame": { @@ -92,6 +92,35 @@ "node": ">=12" } }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.10.1", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz", + "integrity": "sha1-iRG9crLDZApUNgngQAuMTS5+fLY=", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.2", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", + "integrity": "sha1-vM32Fbz3tujbgw7AuNIcmiXeWXs=", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, "node_modules/@eslint/eslintrc": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-1.3.1.tgz", @@ -2335,10 +2364,11 @@ } }, "node_modules/@types/json-schema": { - "version": "7.0.11", - "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.11.tgz", - "integrity": "sha512-wOuvG1SN4Us4rez+tylwwwCV1psiNVOkJeM3AUWUNWg/jDQY2+HE/444y5gc+jBmRqASOm2Oeh5c1axHobwRKQ==", - "dev": true + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha1-WWoXRyM2lNUPatinhp/Lb1bPWEE=", + "dev": true, + "license": "MIT" }, "node_modules/@types/json5": { "version": "0.0.29", @@ -2425,6 +2455,13 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/semver": { + "version": "7.8.0", + "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.8.0.tgz", + "integrity": "sha512-1mAINjtQCXXeLkJ9ehXkwOcBpqtLxiVtKhpUf83DdRNdQKV0iXZpaHYqRr7nj+wvxuJzoAmAwXI+sCNMv1CzLQ==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/serve-static": { "version": "1.13.10", "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.13.10.tgz", @@ -2488,18 +2525,20 @@ } }, "node_modules/@typescript-eslint/eslint-plugin": { - "version": "5.36.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.36.1.tgz", - "integrity": "sha512-iC40UK8q1tMepSDwiLbTbMXKDxzNy+4TfPWgIL661Ym0sD42vRcQU93IsZIrmi+x292DBr60UI/gSwfdVYexCA==", + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.62.0.tgz", + "integrity": "sha512-TiZzBSJja/LbhNPvk6yc0JrX9XqhQ0hdh6M2svYfsHGejaKFIAGd9MQ+ERIMzLGlN/kZoYIgdxFV0PuljTKXag==", "dev": true, + "license": "MIT", "dependencies": { - "@typescript-eslint/scope-manager": "5.36.1", - "@typescript-eslint/type-utils": "5.36.1", - "@typescript-eslint/utils": "5.36.1", + "@eslint-community/regexpp": "^4.4.0", + "@typescript-eslint/scope-manager": "5.62.0", + "@typescript-eslint/type-utils": "5.62.0", + "@typescript-eslint/utils": "5.62.0", "debug": "^4.3.4", - "functional-red-black-tree": "^1.0.1", + "graphemer": "^1.4.0", "ignore": "^5.2.0", - "regexpp": "^3.2.0", + "natural-compare-lite": "^1.4.0", "semver": "^7.3.7", "tsutils": "^3.21.0" }, @@ -2521,14 +2560,15 @@ } }, "node_modules/@typescript-eslint/parser": { - "version": "5.36.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.36.1.tgz", - "integrity": "sha512-/IsgNGOkBi7CuDfUbwt1eOqUXF9WGVBW9dwEe1pi+L32XrTsZIgmDFIi2RxjzsvB/8i+MIf5JIoTEH8LOZ368A==", + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.62.0.tgz", + "integrity": "sha512-VlJEV0fOQ7BExOsHYAGrgbEiZoi8D+Bl2+f6V2RrXerRSylnp+ZBHmPvaIa8cz0Ajx7WO7Z5RqfgYg7ED1nRhA==", "dev": true, + "license": "BSD-2-Clause", "dependencies": { - "@typescript-eslint/scope-manager": "5.36.1", - "@typescript-eslint/types": "5.36.1", - "@typescript-eslint/typescript-estree": "5.36.1", + "@typescript-eslint/scope-manager": "5.62.0", + "@typescript-eslint/types": "5.62.0", + "@typescript-eslint/typescript-estree": "5.62.0", "debug": "^4.3.4" }, "engines": { @@ -2548,13 +2588,14 @@ } }, "node_modules/@typescript-eslint/scope-manager": { - "version": "5.36.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.36.1.tgz", - "integrity": "sha512-pGC2SH3/tXdu9IH3ItoqciD3f3RRGCh7hb9zPdN2Drsr341zgd6VbhP5OHQO/reUqihNltfPpMpTNihFMarP2w==", + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.62.0.tgz", + "integrity": "sha512-VXuvVvZeQCQb5Zgf4HAxc04q5j+WrNAtNh9OwCsCgpKqESMTu3tF/jhZ3xG6T4NZwWl65Bg8KuS2uEvhSfLl0w==", "dev": true, + "license": "MIT", "dependencies": { - "@typescript-eslint/types": "5.36.1", - "@typescript-eslint/visitor-keys": "5.36.1" + "@typescript-eslint/types": "5.62.0", + "@typescript-eslint/visitor-keys": "5.62.0" }, "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" @@ -2565,13 +2606,14 @@ } }, "node_modules/@typescript-eslint/type-utils": { - "version": "5.36.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-5.36.1.tgz", - "integrity": "sha512-xfZhfmoQT6m3lmlqDvDzv9TiCYdw22cdj06xY0obSznBsT///GK5IEZQdGliXpAOaRL34o8phEvXzEo/VJx13Q==", + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-5.62.0.tgz", + "integrity": "sha512-xsSQreu+VnfbqQpW5vnCJdq1Z3Q0U31qiWmRhr98ONQmcp/yhiPJFPq8MXiJVLiksmOKSjIldZzkebzHuCGzew==", "dev": true, + "license": "MIT", "dependencies": { - "@typescript-eslint/typescript-estree": "5.36.1", - "@typescript-eslint/utils": "5.36.1", + "@typescript-eslint/typescript-estree": "5.62.0", + "@typescript-eslint/utils": "5.62.0", "debug": "^4.3.4", "tsutils": "^3.21.0" }, @@ -2592,10 +2634,11 @@ } }, "node_modules/@typescript-eslint/types": { - "version": "5.36.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.36.1.tgz", - "integrity": "sha512-jd93ShpsIk1KgBTx9E+hCSEuLCUFwi9V/urhjOWnOaksGZFbTOxAT47OH2d4NLJnLhkVD+wDbB48BuaycZPLBg==", + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.62.0.tgz", + "integrity": "sha512-87NVngcbVXUahrRTqIK27gD2t5Cu1yuCXxbLcFtCzZGlfyVWWh8mLHkoxzjsB6DDNnvdL+fW8MiwPEJyGJQDgQ==", "dev": true, + "license": "MIT", "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" }, @@ -2605,13 +2648,14 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "5.36.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.36.1.tgz", - "integrity": "sha512-ih7V52zvHdiX6WcPjsOdmADhYMDN15SylWRZrT2OMy80wzKbc79n8wFW0xpWpU0x3VpBz/oDgTm2xwDAnFTl+g==", + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.62.0.tgz", + "integrity": "sha512-CmcQ6uY7b9y694lKdRB8FEel7JbU/40iSAPomu++SjLMntB+2Leay2LO6i8VnJk58MtE9/nQSFIH6jpyRWyYzA==", "dev": true, + "license": "BSD-2-Clause", "dependencies": { - "@typescript-eslint/types": "5.36.1", - "@typescript-eslint/visitor-keys": "5.36.1", + "@typescript-eslint/types": "5.62.0", + "@typescript-eslint/visitor-keys": "5.62.0", "debug": "^4.3.4", "globby": "^11.1.0", "is-glob": "^4.0.3", @@ -2632,17 +2676,20 @@ } }, "node_modules/@typescript-eslint/utils": { - "version": "5.36.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-5.36.1.tgz", - "integrity": "sha512-lNj4FtTiXm5c+u0pUehozaUWhh7UYKnwryku0nxJlYUEWetyG92uw2pr+2Iy4M/u0ONMKzfrx7AsGBTCzORmIg==", + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-5.62.0.tgz", + "integrity": "sha512-n8oxjeb5aIbPFEtmQxQYOLI0i9n5ySBEY/ZEHHZqKQSFnxio1rv6dthascc9dLuwrL0RC5mPCxB7vnAVGAYWAQ==", "dev": true, + "license": "MIT", "dependencies": { + "@eslint-community/eslint-utils": "^4.2.0", "@types/json-schema": "^7.0.9", - "@typescript-eslint/scope-manager": "5.36.1", - "@typescript-eslint/types": "5.36.1", - "@typescript-eslint/typescript-estree": "5.36.1", + "@types/semver": "^7.3.12", + "@typescript-eslint/scope-manager": "5.62.0", + "@typescript-eslint/types": "5.62.0", + "@typescript-eslint/typescript-estree": "5.62.0", "eslint-scope": "^5.1.1", - "eslint-utils": "^3.0.0" + "semver": "^7.3.7" }, "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" @@ -2656,12 +2703,13 @@ } }, "node_modules/@typescript-eslint/visitor-keys": { - "version": "5.36.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.36.1.tgz", - "integrity": "sha512-ojB9aRyRFzVMN3b5joSYni6FAS10BBSCAfKJhjJAV08t/a95aM6tAhz+O1jF+EtgxktuSO3wJysp2R+Def/IWQ==", + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.62.0.tgz", + "integrity": "sha512-07ny+LHRzQXepkGg6w0mFY41fVUNBrL2Roj/++7V1txKugfjm/Ci/qSND03r2RhlJhJYMcTn9AhhSSqQp0Ysyw==", "dev": true, + "license": "MIT", "dependencies": { - "@typescript-eslint/types": "5.36.1", + "@typescript-eslint/types": "5.62.0", "eslint-visitor-keys": "^3.3.0" }, "engines": { @@ -5727,6 +5775,7 @@ "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", "dev": true, + "license": "BSD-2-Clause", "dependencies": { "esrecurse": "^4.3.0", "estraverse": "^4.1.1" @@ -5763,12 +5812,16 @@ } }, "node_modules/eslint-visitor-keys": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.3.0.tgz", - "integrity": "sha512-mQ+suqKJVyeuwGYHAdjMFqjCyfl8+Ldnxuyp3ldiMBFKkvytrXUZWaiPCEav8qDHKty44bD+qV1IP4T+w+xXRA==", + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha1-DNcv6FUOPC6uFWqWpN3c0cisWAA=", "dev": true, + "license": "Apache-2.0", "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" } }, "node_modules/eslint/node_modules/argparse": { @@ -5993,6 +6046,7 @@ "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", "dev": true, + "license": "BSD-2-Clause", "engines": { "node": ">=4.0" } @@ -6659,6 +6713,13 @@ "integrity": "sha512-bzh50DW9kTPM00T8y4o8vQg89Di9oLJVLW/KaOGIXJWP/iqCN6WKYkbNOF04vFLJhwcpYUh9ydh/+5vpOqV4YQ==", "dev": true }, + "node_modules/graphemer": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", + "integrity": "sha1-+y8dVeDjoYSa7/yQxPoN1ToOZsY=", + "dev": true, + "license": "MIT" + }, "node_modules/has": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", @@ -8684,6 +8745,13 @@ "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=", "dev": true }, + "node_modules/natural-compare-lite": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/natural-compare-lite/-/natural-compare-lite-1.4.1.tgz", + "integrity": "sha512-8Mz06azhPqiDlxhUaUTjBhNAbib/1MoPr89kgmuV6Ir8ICT2/Q/XSYg6VfL3fq2x8MpSQX8sqyI/NeZ5GsGyXA==", + "dev": true, + "license": "MIT" + }, "node_modules/negotiator": { "version": "0.6.3", "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", @@ -9305,10 +9373,11 @@ } }, "node_modules/prettier": { - "version": "2.6.2", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.6.2.tgz", - "integrity": "sha512-PkUpF+qoXTqhOeWL9fu7As8LXsIUZ1WYaJiY/a7McAQzxjk82OF0tibkFXVCDImZtWxbvojFjerkiLb0/q8mew==", + "version": "2.8.8", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz", + "integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==", "dev": true, + "license": "MIT", "bin": { "prettier": "bin-prettier.js" }, @@ -10717,16 +10786,17 @@ "license": "MIT" }, "node_modules/typescript": { - "version": "4.8.2", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.8.2.tgz", - "integrity": "sha512-C0I1UsrrDHo2fYI5oaCGbSejwX4ch+9Y5jTQELvovfmFkK3HHSZJB8MSJcWLmCUBzQBchCrZ9rMRV6GuNrvGtw==", + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "dev": true, + "license": "Apache-2.0", "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" }, "engines": { - "node": ">=4.2.0" + "node": ">=14.17" } }, "node_modules/typical": { diff --git a/package.json b/package.json index 34980bb6..ff1712df 100644 --- a/package.json +++ b/package.json @@ -27,11 +27,11 @@ "build:docs": "cd docs && JEKYLL_ENV=production bundle exec jekyll build", "clean": "tsc --build --clean tsconfig.build.json", "lint": "eslint . --ignore-path .gitignore", - "postlint": "tsc", + "postlint": "tsc && tsc -p test/standard && tsc -p test/types", "prepack": "npm run build", "presize": "npm run build", "size": "size-limit", - "test": "web-test-runner" + "test": "web-test-runner && web-test-runner --config web-test-runner-standard.config.js" }, "prettier": "@github/prettier-config", "devDependencies": { @@ -40,8 +40,8 @@ "@open-wc/testing": "^4.0.0", "@size-limit/preset-small-lib": "^8.0.1", "@types/mocha": "^10.0.10", - "@typescript-eslint/eslint-plugin": "^5.36.1", - "@typescript-eslint/parser": "^5.36.1", + "@typescript-eslint/eslint-plugin": "^5.62.0", + "@typescript-eslint/parser": "^5.62.0", "@web/dev-server-esbuild": "^0.3.2", "@web/test-runner": "^0.20.0", "eslint": "^8.23.0", @@ -49,13 +49,13 @@ "sinon": "^14.0.0", "size-limit": "^8.0.1", "tslib": "^2.4.0", - "typescript": "^4.8.2" + "typescript": "^5.9.3" }, "size-limit": [ { "path": "lib/index.js", "import": "{controller, attr, target, targets}", - "limit": "2.5kb" + "limit": "3.4kb" }, { "path": "lib/abilities.js", diff --git a/src/attr.ts b/src/attr.ts index 2d7472fc..ddfff5ba 100644 --- a/src/attr.ts +++ b/src/attr.ts @@ -1,21 +1,127 @@ import type {CustomElementClass} from './custom-element.js' import {mustDasherize} from './dasherize.js' -import {meta} from './core.js' +import {meta, ownMeta} from './core.js' +import type {ClassContext, MemberContext} from './decorator-context.js' +import {assertClass, hasOwn, isDecoratorContext, memberName} from './decorator-context.js' const attrKey = 'attr' type attrValue = string | number | boolean +const standardAttrs = Symbol.for('catalyst:attr') +// Names of standard `@attr` getters and setters, which compute their value rather than store it. +const standardComputedAttrs = Symbol.for('catalyst:attr:computed') + /** * Attr is a decorator which tags a property as one to be initialized via * `initializeAttrs`. * * The signature is typed such that the property must be one of a String, * Number or Boolean. This matches the behavior of `initializeAttrs`. + * + * It supports both TypeScript's `experimentalDecorators` and standard + * decorators. With standard decorators it can decorate a field, accessor, + * getter or setter, and records the name in the class's decorator metadata + * for `@controller` to register. + */ +export function attr, Value extends attrValue>( + value: unknown, + context: MemberContext<'field' | 'accessor' | 'getter' | 'setter', This, Value> & {readonly name: K} +): void +export function attr(proto: Record, key: K): void +export function attr(proto: unknown, keyOrContext: unknown): void { + if (!isDecoratorContext(keyOrContext)) { + meta(proto as Record, attrKey).add(keyOrContext as string) + return + } + const name = memberName('attr', keyOrContext, ['field', 'accessor', 'getter', 'setter']) + const metadata = keyOrContext.metadata as Record | undefined + if (!metadata) throw new TypeError('@attr requires decorator metadata (`Symbol.metadata`) support') + // Metadata inherits from the parent class's metadata, so only append to this class's own lists. The kind is recorded + // now, because another decorator may replace the member's getter. + const record = (list: symbol) => { + if (hasOwn(metadata, list)) metadata[list]!.push(name) + // Define the list rather than assign it, which fails if the parent class's metadata is frozen. + else Object.defineProperty(metadata, list, {value: [name], enumerable: true}) + } + record(standardAttrs) + if (keyOrContext.kind === 'getter' || keyOrContext.kind === 'setter') record(standardComputedAttrs) +} + +/** + * Returns the `@attr` members recorded in the class's own decorator metadata. Finds the metadata by these lists rather + * than by `Symbol.metadata`, because another library may redefine `Symbol.metadata` after some classes are defined. + */ +function ownStandardAttrs(classObject: object): Record { + for (const symbol of Object.getOwnPropertySymbols(classObject)) { + const metadata: unknown = Object.getOwnPropertyDescriptor(classObject, symbol)!.value + if (typeof metadata === 'object' && metadata !== null && hasOwn(metadata, standardAttrs)) { + return metadata as Record + } + } + return {} +} + +// Classes whose attrs are registered, mapped to whether any of them came from standard decorator metadata. +const registeredStandardAttrs = new WeakMap() +// Standard attrs of a registered class, including inherited ones, mapped to whether they're getters or setters. +const standardAttrKinds = new WeakMap>() + +/** + * Registers the `@attr` members recorded in decorator metadata by standard + * decorators, so `initializeAttrs` and `defineObservedAttributes` find them. + * + * Walks up the class chain to include undecorated base classes, stopping at a + * class already registered. Reads each class's own metadata because a class + * without a class decorator may get metadata that doesn't inherit from its + * parent's. */ -export function attr(proto: Record, key: K): void { - meta(proto, attrKey).add(key) +export function registerStandardAttrs(classObject: CustomElementClass): void { + if (registeredStandardAttrs.has(classObject)) return + const levels: CustomElementClass[] = [] + let current: unknown = classObject + for ( + ; + typeof current === 'function' && !registeredStandardAttrs.has(current); + current = Object.getPrototypeOf(current) + ) { + levels.unshift(current as CustomElementClass) + } + const attrs = meta(classObject.prototype, attrKey) + const ancestor = registeredStandardAttrs.has(current as object) ? (current as CustomElementClass) : undefined + const kinds = new Map(standardAttrKinds.get(current as object)) + const standard = levels.map(level => { + const metadata = ownStandardAttrs(level) + const own = metadata[standardAttrs] ?? [] + // Metadata inherits from the parent class's, so ignore a computed list this class doesn't own. + const computed = (hasOwn(metadata, standardComputedAttrs) && metadata[standardComputedAttrs]) || [] + // A subclass that redefines an inherited standard attr without decorating it, such as a legacy getter, decides + // its kind from its own definition. + for (const key of kinds.keys()) if (hasOwn(level.prototype, key) && !own.includes(key)) kinds.delete(key) + for (const key of own) kinds.set(key, computed.includes(key)) + return own + }) + const hasStandard = standard.some(level => level.length) || !!registeredStandardAttrs.get(current as object) + standardAttrKinds.set(classObject, kinds) + if (hasStandard) { + // Base class attrs first, matching the order legacy decorators register them in. Within a class, standard attrs + // come first, because they're recorded when the class is defined and legacy `attr()` calls can only follow. Read + // each class's own legacy attrs, because a subclass's copy of them can predate standard attrs on its ancestors. + const ordered = new Set(ancestor ? meta(ancestor.prototype, attrKey) : []) + for (const [i, level] of levels.entries()) { + for (const key of standard[i]!) ordered.add(key) + for (const key of level === classObject ? attrs : ownMeta(level.prototype, attrKey) ?? []) ordered.add(key) + } + attrs.clear() + for (const key of ordered) attrs.add(key) + } + registeredStandardAttrs.set(classObject, hasStandard) } +// Every element dasherizes the same few names, so cache them. +const attrNames = new Map() +const attrName = (prefixed: string): string => + attrNames.get(prefixed) ?? attrNames.set(prefixed, mustDasherize(prefixed)).get(prefixed)! + /** * initializeAttrs is called with a set of class property names (if omitted, it * will look for any properties tagged with the `@attr` decorator). With this @@ -36,57 +142,109 @@ export function attr(proto: Record, key: K): voi * `@controller` decorator it should not call this manually. */ const initialized = new WeakSet() +const nativeCode = /\{\s*\[native code\]\s*\}$/ +// Prototypes mapped to whether they belong to a built-in class. Reading a class's source is slow, so do it once. +const nativePrototypes = new WeakMap() +const isNative = (proto: object): boolean => + nativePrototypes.get(proto) ?? + nativePrototypes + .set( + proto, + typeof proto.constructor === 'function' && nativeCode.test(Function.prototype.toString.call(proto.constructor)) + ) + .get(proto)! export function initializeAttrs(instance: HTMLElement, names?: Iterable): void { if (initialized.has(instance)) return initialized.add(instance) const proto = Object.getPrototypeOf(instance) const prefix = proto?.constructor?.attrPrefix ?? 'data-' + // Registering also records the kinds of standard attrs, which explicitly named attrs need too. + if (typeof proto?.constructor === 'function') registerStandardAttrs(proto.constructor) if (!names) names = meta(proto, attrKey) - for (const key of names) { - const value = (>(instance))[key] - const name = mustDasherize(`${prefix}${key}`) - let descriptor: PropertyDescriptor = { + const nameOf = (key: string) => attrName(`${prefix}${key}`) + const kinds = standardAttrKinds.get(proto?.constructor) + // Standard decorators record whether an attr is a getter or setter. For others, look for a getter without a setter + // on the classes above the built-in element they extend. One with a setter, such as an auto-accessor or a getter and + // setter pair, stores a value as far as Catalyst can tell, so it keeps registration order, as in v1.8.1. An attr + // named like a built-in accessor, such as `title`, is a field. + const isAccessor = (key: string) => { + if (kinds?.has(key)) return kinds.get(key) + for (let o = proto; o && !isNative(o); o = Object.getPrototypeOf(o)) { + const descriptor = Object.getOwnPropertyDescriptor(o, key) + if (descriptor) return !!descriptor.get && !descriptor.set + } + return false + } + // A getter attr may read other attrs, so it should see them initialized. Fields read nothing, so they go first, in + // registration order. They're own properties by now, or have no accessor at all. + const fields: string[] = [] + const accessors: string[] = [] + for (const key of names) (!hasOwn(instance, key) && isAccessor(key) ? accessors : fields).push(key) + for (const key of fields) initializeAttr(instance, key, nameOf(key)) + // Getters, setters and accessors follow, those with an HTML attribute first, checked now because field callbacks may + // add attributes. One without an HTML attribute returns its default before and after it's initialized. + if (!accessors.length) return + const has = (key: string) => instance.hasAttribute(nameOf(key)) + for (const key of accessors.filter(has).concat(accessors.filter(other => !has(other)))) { + initializeAttr(instance, key, nameOf(key)) + } +} + +function initializeAttr(instance: HTMLElement, key: string, name: string) { + const value = (>(instance))[key] + let descriptor: PropertyDescriptor = { + configurable: true, + get(this: HTMLElement): string { + return this.getAttribute(name) || '' + }, + set(this: HTMLElement, newValue: string) { + this.setAttribute(name, newValue || '') + } + } + if (typeof value === 'number') { + descriptor = { configurable: true, - get(this: HTMLElement): string { - return this.getAttribute(name) || '' + get(this: HTMLElement): number { + return Number(this.getAttribute(name) || 0) }, set(this: HTMLElement, newValue: string) { - this.setAttribute(name, newValue || '') + this.setAttribute(name, newValue) } } - if (typeof value === 'number') { - descriptor = { - configurable: true, - get(this: HTMLElement): number { - return Number(this.getAttribute(name) || 0) - }, - set(this: HTMLElement, newValue: string) { - this.setAttribute(name, newValue) - } - } - } else if (typeof value === 'boolean') { - descriptor = { - configurable: true, - get(this: HTMLElement): boolean { - return this.hasAttribute(name) - }, - set(this: HTMLElement, newValue: boolean) { - this.toggleAttribute(name, newValue) - } + } else if (typeof value === 'boolean') { + descriptor = { + configurable: true, + get(this: HTMLElement): boolean { + return this.hasAttribute(name) + }, + set(this: HTMLElement, newValue: boolean) { + this.toggleAttribute(name, newValue) } } - Object.defineProperty(instance, key, descriptor) - if (key in instance && !instance.hasAttribute(name)) { - descriptor.set!.call(instance, value) - } + } + Object.defineProperty(instance, key, descriptor) + if (key in instance && !instance.hasAttribute(name)) { + descriptor.set!.call(instance, value) } } -export function defineObservedAttributes(classObject: CustomElementClass): void { +// The legacy overload comes last, so `Parameters` reads it and callbacks such as `forEach` still accept the function. +export function defineObservedAttributes(classObject: C, context: ClassContext): void +export function defineObservedAttributes(classObject: CustomElementClass): void +export function defineObservedAttributes(classObject: CustomElementClass, context?: unknown): void { + // Standard class decorators run before the class's decorator metadata is attached, so wait for it. + if (isDecoratorContext(context)) { + assertClass('defineObservedAttributes', context) + ;(context as ClassContext).addInitializer(function (this: CustomElementClass) { + defineObservedAttributes(this) + }) + return + } + registerStandardAttrs(classObject) let observed = classObject.observedAttributes || [] const prefix = classObject.attrPrefix ?? 'data-' - const attrToAttributeName = (name: string) => mustDasherize(`${prefix}${name}`) + const attrToAttributeName = (name: string) => attrName(`${prefix}${name}`) Object.defineProperty(classObject, 'observedAttributes', { configurable: true, diff --git a/src/bind.ts b/src/bind.ts index fe6d91af..4f617af9 100644 --- a/src/bind.ts +++ b/src/bind.ts @@ -101,7 +101,7 @@ function* bindings(el: Element): Iterable { type: action.slice(0, eventSep), tag: action.slice(eventSep + 1, methodSep), method: action.slice(methodSep + 1) || 'handleEvent' - } || 'handleEvent' + } } } diff --git a/src/controller.ts b/src/controller.ts index 0b4b74d6..57927cb5 100644 --- a/src/controller.ts +++ b/src/controller.ts @@ -1,20 +1,47 @@ import {CatalystDelegate} from './core.js' import type {CustomElementClass} from './custom-element.js' +import type {ClassContext} from './decorator-context.js' +import {assertClass, isDecoratorContext} from './decorator-context.js' + +/** + * The decorator returned by `controller(name)`. It accepts both TypeScript's + * `experimentalDecorators` and standard decorator calls. + */ +export interface ControllerDecorator { + (classObject: C, context: ClassContext): void + (classObject: CustomElementClass): void +} + /** * Controller is a decorator to be used over a class that extends HTMLElement. * It will automatically `register()` the component in the customElement * registry, as well as ensuring `bind(this)` is called on `connectedCallback`, * wrapping the classes `connectedCallback` method if needed. + * + * It supports both TypeScript's `experimentalDecorators` and standard + * decorators. */ +export function controller(classObject: C, context: ClassContext): void export function controller(classObject: CustomElementClass): void -export function controller(name: string): (classObject: CustomElementClass) => void +export function controller(name: string): ControllerDecorator export function controller( - classObjectOrName: CustomElementClass | string -): void | ((classObject: CustomElementClass) => void) { + classObjectOrName: CustomElementClass | string, + context?: unknown +): void | ControllerDecorator { if (typeof classObjectOrName === 'string') { - return (classObject: CustomElementClass) => { - new CatalystDelegate(classObject, classObjectOrName) - } + const name = classObjectOrName + return (classObject: CustomElementClass, classContext?: unknown) => decorate(classObject, classContext, name) } - new CatalystDelegate(classObjectOrName) + decorate(classObjectOrName, context) +} + +function decorate(classObject: CustomElementClass, context: unknown, name?: string) { + if (!isDecoratorContext(context)) return void new CatalystDelegate(classObject, name) + assertClass('controller', context) + // Standard class decorators run before static fields such as `observedAttributes` and `attrPrefix` are assigned. + // Class initializers run after them, which is when legacy class decorators run. + const classContext = context as ClassContext + classContext.addInitializer(function (this: CustomElementClass) { + new CatalystDelegate(this, name) + }) } diff --git a/src/core.ts b/src/core.ts index de10ee75..c9f9bc93 100644 --- a/src/core.ts +++ b/src/core.ts @@ -96,3 +96,10 @@ export function meta(proto: Record, name: string): Set()) return map.get(name)! } + +// Like `meta`, but only reads the prototype's own metadata, and doesn't create it. +export function ownMeta(proto: object | undefined, name: string): Set | undefined { + if (proto && Object.prototype.hasOwnProperty.call(proto, symbol)) { + return (proto as Record>>)[symbol].get(name) + } +} diff --git a/src/decorator-context.ts b/src/decorator-context.ts new file mode 100644 index 00000000..d0d8b71d --- /dev/null +++ b/src/decorator-context.ts @@ -0,0 +1,62 @@ +/** + * The parts of standard (TC39) decorator contexts that Catalyst uses. Declared structurally rather than using + * TypeScript's `ClassDecoratorContext` and friends so the published types still load in TypeScript versions before + * 5.0, which lack them. + */ +export interface ClassContext { + readonly kind: 'class' + readonly name: string | undefined + readonly metadata?: object | undefined + addInitializer(initializer: (this: C) => void): void +} + +// Catalyst's member decorators only support public instance members with string names. TypeScript passes literal +// `static` and `private` types, so other members fail to type-check. +export interface MemberContext { + readonly kind: Kind + readonly name: string + readonly static: false + readonly private: false + readonly metadata?: object | undefined + readonly access: {get?(object: This): Value; set?(object: This, value: Value): void} + addInitializer(initializer: (this: This) => void): void +} + +export interface AccessorTarget { + get(this: This): Value + set(this: This, value: Value): void +} + +export interface AccessorResult { + get?(this: This): Value + set?(this: This, value: Value): void + init?(this: This, value: Value): Value +} + +// Lets compilers that only attach decorator metadata when `Symbol.metadata` exists (such as TypeScript) do so. Uses +// the same fallback key as the SWC and Babel helpers, and leaves an existing definition alone. +try { + ;(Symbol as {metadata?: symbol}).metadata ??= Symbol.for('Symbol.metadata') +} catch { + // `Symbol` is frozen, for example by SES `lockdown()`. Legacy decorators don't need metadata. +} + +export const hasOwn = (object: object, key: PropertyKey): boolean => Object.prototype.hasOwnProperty.call(object, key) + +// Standard decorators receive a context object as their second argument; legacy decorators receive the member name. +export function isDecoratorContext(value: unknown): value is ClassContext | MemberContext { + return typeof value === 'object' && value !== null && 'kind' in value && 'addInitializer' in value +} + +export function assertClass(decorator: string, context: ClassContext | MemberContext): void { + if (context.kind !== 'class') throw new TypeError(`@${decorator} must decorate a class`) +} + +export function memberName(decorator: string, context: ClassContext | MemberContext, kinds: string[]): string { + // `kinds` never includes 'class', so class contexts fail the first check. + const member = context as MemberContext + if (!kinds.includes(member.kind) || member.static || member.private || typeof member.name !== 'string') { + throw new TypeError(`@${decorator} must decorate a public instance ${kinds.join('/')}`) + } + return member.name +} diff --git a/src/register.ts b/src/register.ts index 6473ec5d..9c49adda 100644 --- a/src/register.ts +++ b/src/register.ts @@ -1,4 +1,6 @@ import type {CustomElementClass} from './custom-element.js' +import type {ClassContext} from './decorator-context.js' +import {assertClass, isDecoratorContext} from './decorator-context.js' import {dasherize} from './dasherize.js' /** @@ -7,8 +9,25 @@ import {dasherize} from './dasherize.js' * The classname is converted to a appropriate tag name. * * Example: HelloController => hello-controller + * + * It can be used as a class decorator with both TypeScript's + * `experimentalDecorators` and standard decorators. */ -export function register(classObject: CustomElementClass, name?: string): CustomElementClass { +// The legacy overload comes first, so calls with untyped arguments resolve to it, and last, so `ReturnType` and +// `Parameters` read it. +export function register(classObject: CustomElementClass, name?: string): CustomElementClass +export function register(classObject: C, context: ClassContext): void +export function register(classObject: CustomElementClass, name?: string): CustomElementClass +export function register(classObject: CustomElementClass, nameOrContext?: unknown): CustomElementClass | void { + if (isDecoratorContext(nameOrContext)) { + assertClass('register', nameOrContext) + // Like `@controller`, define the element once static fields are assigned. + ;(nameOrContext as ClassContext).addInitializer(function (this: CustomElementClass) { + register(this) + }) + return + } + const name = nameOrContext as string | undefined const tagName = name || dasherize(classObject.name).replace(/-element$/, '') try { diff --git a/src/target.ts b/src/target.ts index 0ce510e6..82cb1960 100644 --- a/src/target.ts +++ b/src/target.ts @@ -1,5 +1,7 @@ import {findTarget, findTargets} from './findtarget.js' import {meta} from './core.js' +import type {AccessorResult, AccessorTarget, MemberContext} from './decorator-context.js' +import {isDecoratorContext, memberName} from './decorator-context.js' /** * Target is a decorator which - when assigned to a property field on the @@ -7,9 +9,22 @@ import {meta} from './core.js' * returns a call to `findTarget(this, key)` where `key` is the name of the * property field. In other words, `@target foo` becomes a getter for * `findTarget(this, 'foo')`. + * + * With standard decorators it must decorate an accessor: + * `@target accessor foo!: HTMLElement`. */ -export function target(proto: Record, key: K): void { - meta(proto, 'target').add(key) +// The legacy overload comes first, so calls with untyped arguments resolve to it, and last, so `ReturnType` and +// `Parameters` read it. +export function target(proto: Record, key: K): void +export function target( + value: AccessorTarget, + context: MemberContext<'accessor', This, Value> +): AccessorResult +export function target(proto: Record, key: K): void +export function target(proto: unknown, keyOrContext: unknown): unknown { + if (isDecoratorContext(keyOrContext)) return standardTarget('target', keyOrContext, findTarget) + const key = keyOrContext as string + meta(proto as Record, 'target').add(key) Object.defineProperty(proto, key, { configurable: true, get() { @@ -24,9 +39,22 @@ export function target(proto: Record, key: K): voi * returns a call to `findTargets(this, key)` where `key` is the name of the * property field. In other words, `@targets foo` becomes a getter for * `findTargets(this, 'foo')`. + * + * With standard decorators it must decorate an accessor: + * `@targets accessor foos!: HTMLElement[]`. */ -export function targets(proto: Record, key: K): void { - meta(proto, 'targets').add(key) +// The legacy overload comes first, so calls with untyped arguments resolve to it, and last, so `ReturnType` and +// `Parameters` read it. +export function targets(proto: Record, key: K): void +export function targets( + value: AccessorTarget, + context: MemberContext<'accessor', This, Value> +): AccessorResult +export function targets(proto: Record, key: K): void +export function targets(proto: unknown, keyOrContext: unknown): unknown { + if (isDecoratorContext(keyOrContext)) return standardTarget('targets', keyOrContext, findTargets) + const key = keyOrContext as string + meta(proto as Record, 'targets').add(key) Object.defineProperty(proto, key, { configurable: true, get() { @@ -34,3 +62,20 @@ export function targets(proto: Record, key: K): vo } }) } + +function standardTarget( + decorator: string, + context: Parameters[1], + find: (controller: HTMLElement, name: string) => unknown +) { + const key = memberName(decorator, context, ['accessor']) + return { + get(this: HTMLElement) { + return find(this, key) + }, + // Legacy decorators define a getter-only property, so assigning to it throws. + set() { + throw new TypeError(`Cannot set @${decorator} ${key}`) + } + } +} diff --git a/test/attr.ts b/test/attr.ts index 7eab85bf..2a480797 100644 --- a/test/attr.ts +++ b/test/attr.ts @@ -1,6 +1,9 @@ import {expect, fixture, html} from '@open-wc/testing' import {controller} from '../src/controller.js' -import {attr} from '../src/attr.js' +import {attr, defineObservedAttributes, initializeAttrs} from '../src/attr.js' +import type {CustomElementClass} from '../src/custom-element.js' + +const observed = (classObject: CustomElementClass) => classObject.observedAttributes describe('Attr', () => { { @@ -177,4 +180,257 @@ describe('Attr', () => { expect(instance.getAttributeNames()).to.include('foo-clip-x') }) }) + + describe('initialization order', () => { + it('initializes field attrs in declaration order, so their callbacks keep HTML values', async () => { + @controller + class CallbackOrderAttrTest extends HTMLElement { + @attr ready = true + @attr status = 'default' + attributeChangedCallback(name: string) { + if (name === 'data-ready') this.status = 'updated' + } + } + const instance = await fixture( + html`` + ) + expect(instance).to.have.attribute('data-status', 'html') + }) + + it('initializes field attrs before getter attrs that read them, when both have HTML attributes', async () => { + @controller + class ParseOrderAttrTest extends HTMLElement { + @attr get count() { + return JSON.parse(this.payload).length + } + @attr payload = '' + } + const instance = await fixture( + html`` + ) + expect(instance).to.have.property('count', 7) + }) + + it('initializes fields named like built-in accessors in declaration order', async () => { + @controller + class BuiltinNameAttrTest extends HTMLElement { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore With define semantics TypeScript wants an initializer (TS2612). This tests a field without one. + @attr title!: string + @attr status = 'default' + attributeChangedCallback(name: string) { + if (name === 'data-title') this.status = 'updated' + } + } + const instance = await fixture( + html`` + ) + expect(instance).to.have.attribute('data-status', 'html') + }) + + it('orders getter attrs by the HTML attributes present after fields initialize', async () => { + @controller + class LatePresenceAttrTest extends HTMLElement { + @attr trigger = true + @attr get payload() { + return '' + } + @attr get count() { + return JSON.parse(this.payload).length + } + attributeChangedCallback(name: string) { + if (name === 'data-trigger') this.setAttribute('data-payload', '[1,2]') + } + } + const instance = await fixture( + html`` + ) + expect(instance).to.have.property('count', 7) + }) + + it('initializes fields without a value before getter attrs that read them', async () => { + @controller + class UnsetOrderAttrTest extends HTMLElement { + @attr get greeting() { + return this.name.toUpperCase() + } + @attr name!: string + } + const instance = await fixture(html``) + expect(instance).to.have.attribute('data-greeting', '') + }) + }) + + describe('inheritance', () => { + it('registers attrs from undecorated base classes, base class first', async () => { + class Base extends HTMLElement { + @attr baseValue = 'base' + } + class Middle extends Base { + @attr middleValue = 1 + } + @controller + class InheritedAttrTest extends Middle { + @attr ownValue = true + } + const instance = await fixture(html``) + expect(observed(InheritedAttrTest)).to.eql(['data-base-value', 'data-middle-value', 'data-own-value']) + expect(instance).to.have.attribute('data-base-value', 'base') + expect(instance).to.have.attribute('data-middle-value', '1') + expect(instance).to.have.attribute('data-own-value', '') + }) + + it('inherits attrs from a parent controller without adding to it', async () => { + @controller + class ParentAttrTest extends HTMLElement { + @attr parentValue = 'p' + } + @controller + class ChildAttrTest extends ParentAttrTest { + @attr childValue = 'c' + } + expect(observed(ParentAttrTest)).to.eql(['data-parent-value']) + // The inherited list repeats the parent's attributes. + expect([...new Set(observed(ChildAttrTest))]).to.eql(['data-parent-value', 'data-child-value']) + const child = await fixture(html``) + expect(child).to.have.attribute('data-parent-value', 'p') + expect(child).to.have.attribute('data-child-value', 'c') + }) + + it('keeps attrs of subclasses sharing an undecorated base class separate', () => { + class SharedBase extends HTMLElement { + @attr shared = '' + } + @controller + class FirstSiblingAttrTest extends SharedBase { + @attr first = '' + } + @controller + class SecondSiblingAttrTest extends SharedBase { + @attr second = '' + } + expect(observed(FirstSiblingAttrTest)).to.eql(['data-shared', 'data-first']) + expect(observed(SecondSiblingAttrTest)).to.eql(['data-shared', 'data-second']) + }) + + it('initializes getters that read an overridden attr from its HTML value', async () => { + class ReadOverrideBase extends HTMLElement { + @attr get label() { + return 'base' + } + @attr get derived() { + return `${this.label}-derived` + } + } + @controller + class ReadOverrideAttrTest extends ReadOverrideBase { + @attr get label() { + return 'sub' + } + } + const instance = await fixture( + html`` + ) + expect(instance).to.have.attribute('data-derived', 'attribute-derived') + }) + + it('initializes an overriding getter attr after the attrs it reads', async () => { + class OverrideBase extends HTMLElement { + @attr get label() { + return 'base' + } + } + @controller + class OverrideGetterAttrTest extends OverrideBase { + @attr input = 'field' + @attr get label() { + return `${this.input}-label` + } + } + const instance = await fixture( + html`` + ) + expect(instance).to.have.attribute('data-label', 'attribute-label') + }) + }) + + it('registers attrs when defineObservedAttributes decorates the class', async () => { + @controller + @defineObservedAttributes + class DecoratedObservedAttrTest extends HTMLElement { + @attr foo = 'bar' + } + expect(observed(DecoratedObservedAttrTest)).to.include('data-foo') + const instance = await fixture(html``) + expect(instance).to.have.attribute('data-foo', 'bar') + }) + + describe('without @controller', () => { + it('registers attrs for defineObservedAttributes and initializeAttrs', async () => { + class ManualAttrTest extends HTMLElement { + @attr foo = 'bar' + connectedCallback() { + initializeAttrs(this) + } + } + defineObservedAttributes(ManualAttrTest) + customElements.define('manual-attr-test', ManualAttrTest) + expect(observed(ManualAttrTest)).to.eql(['data-foo']) + + class InitializeOnlyAttrTest extends HTMLElement { + @attr foo = 'baz' + connectedCallback() { + initializeAttrs(this) + } + } + customElements.define('initialize-only-attr-test', InitializeOnlyAttrTest) + const instance = await fixture(html``) + expect(instance).to.have.attribute('data-foo', 'baz') + }) + + it('initializes an attr named constructor', () => { + class ConstructorAttrTest extends HTMLElement { + connectedCallback() { + initializeAttrs(this, ['constructor']) + } + } + Object.defineProperty(ConstructorAttrTest.prototype, 'constructor', {configurable: true, get: () => 'default'}) + customElements.define('constructor-attr-test', ConstructorAttrTest) + const instance = document.createElement('constructor-attr-test') + document.body.append(instance) + instance.remove() + expect(instance).to.have.attribute('data-constructor', 'default') + }) + + // Customized built-ins inherit accessors such as `value` from interfaces like HTMLInputElement. An attr declared + // without a value has no own property, and the inherited accessor must not make it initialize like a getter attr. + it('initializes attrs named like accessors of a built-in base element in registration order', function (this: Mocha.Context) { + const changes: unknown[] = [] + class BuiltinAttrInput extends HTMLInputElement { + declare value: string + status = 'idle' + connectedCallback() { + initializeAttrs(this) + } + attributeChangedCallback(name: string) { + changes.push([name, this.status]) + } + } + attr(BuiltinAttrInput.prototype as unknown as Record<'value', string>, 'value') + attr(BuiltinAttrInput.prototype as unknown as Record<'status', string>, 'status') + defineObservedAttributes(BuiltinAttrInput) + customElements.define('builtin-attr-input', BuiltinAttrInput, {extends: 'input'}) + const element = document.createElement('input', {is: 'builtin-attr-input'}) + // Safari doesn't support customized built-in elements. + if (!(element instanceof BuiltinAttrInput)) this.skip() + element.setAttribute('data-status', 'html') + document.body.append(element) + element.remove() + // `value` registers first, so it initializes and reflects before `status` reads its HTML value. + expect(changes).to.eql([ + ['data-status', 'idle'], + ['data-value', 'idle'] + ]) + }) + }) }) diff --git a/test/controller.ts b/test/controller.ts index 872a26e0..7c4a4095 100644 --- a/test/controller.ts +++ b/test/controller.ts @@ -27,6 +27,35 @@ describe('controller', () => { expect(instance).to.exist }) + it('registers attrs when called as a function', async () => { + class FunctionAttrElement extends HTMLElement { + @attr foo = 'bar' + } + controller('function-attr-element')(FunctionAttrElement) + instance = await fixture(html``) + expect(instance).to.have.attribute('data-foo', 'bar') + }) + + it('defines the element after static fields are assigned', async () => { + const changed: string[] = [] + @controller + class ControllerStaticsElement extends HTMLElement { + static observedAttributes = ['data-extra'] + static attrPrefix = 'x-' + @attr name = 'a' + attributeChangedCallback(name: string) { + changed.push(name) + } + } + const element = await fixture(html``) + expect(element).to.have.attribute('x-name', 'a') + changed.length = 0 + element.setAttribute('data-extra', '1') + element.setAttribute('x-name', 'b') + expect(changed).to.eql(['data-extra', 'x-name']) + expect(element.name).to.equal('b') + }) + it('adds data-catalyst to elements with custom names', async () => { @controller('custom-named-element') // eslint-disable-next-line @typescript-eslint/no-unused-vars diff --git a/test/frozen-symbol.ts b/test/frozen-symbol.ts new file mode 100644 index 00000000..8ab138b0 --- /dev/null +++ b/test/frozen-symbol.ts @@ -0,0 +1,13 @@ +import {expect} from '@open-wc/testing' + +describe('frozen Symbol', () => { + it('can still import Catalyst', async () => { + const symbolWithMetadata = Symbol as {metadata?: symbol} + // Lit, loaded by @open-wc/testing, defines `Symbol.metadata`. Remove it so Catalyst tries to define it. + delete symbolWithMetadata.metadata + Object.freeze(Symbol) + const catalyst = await import('../src/index.js') + expect(catalyst.controller).to.be.a('function') + expect(symbolWithMetadata.metadata).to.equal(undefined) + }) +}) diff --git a/test/helpers/target-tests.ts b/test/helpers/target-tests.ts new file mode 100644 index 00000000..c4c70255 --- /dev/null +++ b/test/helpers/target-tests.ts @@ -0,0 +1,94 @@ +import {expect, fixture, html} from '@open-wc/testing' + +/** + * Target tests shared by both decorator modes. test/target.ts (legacy decorators) and test/standard/target.ts + * (standard decorators) each define `` with `foo`, `baz`, `qux`, `shadow` and `bing` targets, a `foos` + * targets list and a plain `bar = 'hello'` field, then call this. + */ +export function targetTests() { + let instance: HTMLElement + beforeEach(async () => { + instance = await fixture(html` + +
+
+
+
+
+
+
+
+
+
`) + }) + + describe('target', () => { + it('returns the first element where closest tag is the controller', async () => { + expect(instance).to.have.property('foo').exist.with.attribute('id', 'el4') + expect(instance.querySelector('target-test')).to.have.property('foo').exist.with.attribute('id', 'el2') + }) + + it('does not assign to non-target decorated properties', async () => { + expect(instance).to.have.property('bar', 'hello') + }) + + it('returns the first element that has the exact target name', async () => { + expect(instance).to.have.property('baz').exist.with.attribute('id', 'el5') + }) + + it('returns target when there are mutliple target values', async () => { + expect(instance).to.have.property('bing').exist.with.attribute('id', 'el6') + }) + + it('returns targets when there are mutliple target values with different controllers', async () => { + expect(instance).to.have.property('qux').exist.with.attribute('id', 'el8') + }) + + it('returns targets from the shadowRoot, if available', async () => { + instance.attachShadow({mode: 'open'}) + const el = document.createElement('div') + el.setAttribute('data-target', 'target-test.shadow') + instance.shadowRoot!.appendChild(el) + expect(instance).to.have.property('shadow', el) + }) + + it('prioritises shadowRoot targets over others', async () => { + instance.attachShadow({mode: 'open'}) + const shadowEl = document.createElement('div') + shadowEl.setAttribute('data-target', 'target-test.foo') + instance.shadowRoot!.appendChild(shadowEl) + expect(instance).to.have.property('foo', shadowEl) + }) + }) + + it('throws when a target is assigned, because it is a getter', () => { + expect(() => { + ;(instance as unknown as Record).foo = document.body + }).to.throw(TypeError) + expect(() => { + ;(instance as unknown as Record).foos = [] + }).to.throw(TypeError) + }) + + describe('targets', () => { + it('returns all elements where closest tag is the controller', async () => { + expect(instance).to.have.property('foos').with.lengthOf(2) + expect(instance).to.have.nested.property('foos[0]').with.attribute('id', 'el4') + expect(instance).to.have.nested.property('foos[1]').with.attribute('id', 'el5') + }) + + it('returns all elements inside a shadow root', async () => { + instance.attachShadow({mode: 'open'}) + const els = [document.createElement('div'), document.createElement('div'), document.createElement('div')] + for (const el of els) el.setAttribute('data-targets', 'target-test.foos') + instance.shadowRoot!.append(...els) + + expect(instance).to.have.property('foos').with.lengthOf(5) + expect(instance).to.have.nested.property('foos[0]', els[0]) + expect(instance).to.have.nested.property('foos[1]', els[1]) + expect(instance).to.have.nested.property('foos[2]', els[2]) + expect(instance).to.have.nested.property('foos[3]').with.attribute('id', 'el4') + expect(instance).to.have.nested.property('foos[4]').with.attribute('id', 'el5') + }) + }) +} diff --git a/test/standard/attr.ts b/test/standard/attr.ts new file mode 100644 index 00000000..af0258e2 --- /dev/null +++ b/test/standard/attr.ts @@ -0,0 +1,508 @@ +import {expect, fixture, html} from '@open-wc/testing' +import {controller} from '../../src/controller.js' +import {attr, defineObservedAttributes, initializeAttrs} from '../../src/attr.js' +import type {CustomElementClass} from '../../src/custom-element.js' +import type {ClassContext} from '../../src/decorator-context.js' +import {register} from '../../src/register.js' + +const symbolWithMetadata = Symbol as {metadata?: symbol} +const observed = (classObject: CustomElementClass) => classObject.observedAttributes + +// Shared @attr behaviour is in test/attr.ts, which also runs with standard decorators. +describe('Attr (standard decorators)', () => { + { + @controller + class StandardAttrElement extends HTMLElement { + @attr fooBar = 'hello' + @attr accessor fooCount = 2 + fooBaz = 1 + + #bing = 'world' + get bingBaz() { + return this.#bing + } + @attr set bingBaz(value: string) { + this.#bing = value + } + + @attr get fooFlag() { + return false + } + } + + let instance: StandardAttrElement + beforeEach(async () => { + instance = await fixture(html``) + }) + + it('does not alter field values from their initial value', () => { + expect(instance).to.have.property('fooBar', 'hello') + expect(instance).to.have.property('fooCount', 2) + expect(instance).to.have.property('fooBaz', 1) + expect(instance).to.have.property('bingBaz', 'world') + expect(instance).to.have.property('fooFlag', false) + }) + + it('reflects the initial value as an attribute, if not present', () => { + expect(instance).to.have.attribute('data-foo-bar', 'hello') + expect(instance).to.have.attribute('data-foo-count', '2') + expect(instance).to.not.have.attribute('data-foo-baz') + expect(instance).to.have.attribute('data-bing-baz', 'world') + expect(instance).to.not.have.attribute('data-foo-flag') + }) + + it('prioritises the value in the attribute over the property', async () => { + instance = await fixture( + html`` + ) + expect(instance).to.have.property('fooBar', 'goodbye') + expect(instance).to.have.property('fooCount', 5) + expect(instance).to.have.property('bingBaz', 'universe') + }) + + it('changes the property when the attribute changes', () => { + instance.setAttribute('data-foo-bar', 'goodbye') + instance.setAttribute('data-foo-count', '7') + instance.setAttribute('data-foo-flag', '') + expect(instance).to.have.property('fooBar', 'goodbye') + expect(instance).to.have.property('fooCount', 7) + expect(instance).to.have.property('fooFlag', true) + }) + + it('changes the attribute when the property changes', () => { + instance.fooBar = 'goodbye' + instance.fooCount = 3 + instance.bingBaz = 'universe' + expect(instance).to.have.attribute('data-foo-bar', 'goodbye') + expect(instance).to.have.attribute('data-foo-count', '3') + expect(instance).to.have.attribute('data-bing-baz', 'universe') + }) + + it('observes the attributes', () => { + expect(observed(StandardAttrElement)).to.have.members([ + 'data-foo-bar', + 'data-foo-count', + 'data-bing-baz', + 'data-foo-flag' + ]) + }) + } + + it('initializes stored attrs before getter attrs that read them', async () => { + @controller + class StandardDependentElement extends HTMLElement { + @attr base = 'field' + @attr get derived() { + return `${this.base}-derived` + } + } + const instance = await fixture( + html`` + ) + expect(instance).to.have.attribute('data-derived', 'attribute-derived') + }) + + // Standard decorators apply accessor decorators before field decorators, so accessors register first. + it('registers accessor attrs before field attrs declared above them', () => { + @controller + class StandardRegistrationOrderElement extends HTMLElement { + @attr first = '' + @attr accessor second = '' + } + expect(observed(StandardRegistrationOrderElement)).to.eql(['data-second', 'data-first']) + }) + + // Setting a missing attr's attribute can run connectedCallback before the rest initialize, so the order is observable. + it('initializes accessor attrs in registration order, like fields, even when wrapped or overriding a getter', async () => { + const seen: Record = {field: [], accessor: [], wrapped: [], override: []} + const wrap = (value: ClassAccessorDecoratorTarget) => ({ + get(this: This) { + return value.get.call(this) + }, + set(this: This, newValue: Value) { + value.set.call(this, newValue) + } + }) + @controller + class FieldOrderElement extends HTMLElement { + @attr first = '' + @attr second = '' + connectedCallback() { + seen.field!.push(this.second) + } + } + @controller + class AccessorOrderElement extends HTMLElement { + @attr accessor first = '' + @attr accessor second = '' + connectedCallback() { + seen.accessor!.push(this.second) + } + } + @controller + class WrappedOrderElement extends HTMLElement { + @wrap @attr accessor first = '' + @attr accessor second = '' + connectedCallback() { + seen.wrapped!.push(this.second) + } + } + class GetterBase extends HTMLElement { + @attr get first() { + return '' + } + } + @controller + class OverrideOrderElement extends GetterBase { + @attr override accessor first = '' + @attr accessor second = '' + connectedCallback() { + seen.override!.push(this.second) + } + } + expect(FieldOrderElement).to.exist + expect(AccessorOrderElement).to.exist + expect(WrappedOrderElement).to.exist + expect(OverrideOrderElement).to.exist + const container = await fixture(html`
`) + // Elements from an inert document upgrade when inserted, with their attributes already set, as innerHTML does. + const inert = document.implementation.createHTMLDocument() + for (const tag of ['field-order', 'accessor-order', 'wrapped-order', 'override-order']) { + const element = inert.createElement(tag) + element.setAttribute('data-second', 'html') + container.append(document.adoptNode(element)) + } + expect(seen.field).to.have.length(1) + expect(seen.accessor).to.eql(seen.field) + expect(seen.wrapped).to.eql(seen.field) + expect(seen.override).to.eql(seen.field) + }) + + // Undecorated auto-accessors have no metadata recording that they store a value, but they have a setter, which + // computed getter attrs don't, so they initialize in registration order as in v1.8.1. + for (const registration of ['attr calls', 'explicit names'] as const) { + it(`initializes undecorated accessors registered by ${registration} in registration order`, () => { + class UndecoratedAccessorElement extends HTMLElement { + static observedAttributes = ['data-ready'] + accessor ready = true + accessor status = 'default' + connectedCallback() { + if (registration === 'explicit names') initializeAttrs(this, ['ready', 'status']) + else initializeAttrs(this) + } + attributeChangedCallback() { + this.status = 'updated' + } + } + if (registration === 'attr calls') { + attr(UndecoratedAccessorElement.prototype, 'ready') + attr(UndecoratedAccessorElement.prototype, 'status') + } + const tag = `undecorated-accessor-${registration.replace(' ', '-')}` + customElements.define(tag, UndecoratedAccessorElement) + const element = document.createElement(tag) as UndecoratedAccessorElement + element.setAttribute('data-status', 'html') + document.body.append(element) + element.remove() + expect(element.status).to.equal('html') + }) + } + + it('initializes explicitly named accessor attrs in the order given, like fields', () => { + class ExplicitNamesElement extends HTMLElement { + static observedAttributes = ['data-ready'] + @attr accessor ready = true + @attr accessor status = 'default' + connectedCallback() { + initializeAttrs(this, ['ready', 'status']) + } + attributeChangedCallback() { + this.status = 'updated' + } + } + customElements.define('explicit-names-element', ExplicitNamesElement) + const element = document.createElement('explicit-names-element') as ExplicitNamesElement + element.setAttribute('data-status', 'html') + document.body.append(element) + element.remove() + // `ready` initializes first, so its callback runs before `status` reads its HTML value. + expect(element.status).to.equal('html') + }) + + it('initializes getters that read a decorated getter and setter pair from its HTML value', async () => { + @controller + class StandardPairElement extends HTMLElement { + #name = 'field' + @attr get name() { + return this.#name + } + @attr get greeting() { + return `hi ${this.name}` + } + // eslint-disable-next-line @typescript-eslint/adjacent-overload-signatures + @attr set name(value: string) { + this.#name = value + } + } + const instance = await fixture(html``) + expect(instance).to.have.attribute('data-greeting', 'hi attribute') + }) + + // esbuild's `addInitializer` returns a value, and it throws if a class decorator returns anything but a function. + it('returns nothing from class decorators, whatever addInitializer returns', () => { + class ReturnCheckElement extends HTMLElement {} + const context: ClassContext = { + kind: 'class', + name: 'ReturnCheckElement', + addInitializer: () => 1 + } + expect(defineObservedAttributes(ReturnCheckElement, context)).to.equal(undefined) + expect(controller(ReturnCheckElement, context)).to.equal(undefined) + expect(controller('return-check')(ReturnCheckElement, context)).to.equal(undefined) + expect(register(ReturnCheckElement, context)).to.equal(undefined) + }) + + // A base compiled with standard decorators, extended by a class that registers attrs with legacy-style calls. + describe('mixed with legacy attrs', () => { + it('initializes standard base attrs before legacy subclass attrs', async () => { + class MixedOrderBase extends HTMLElement { + @attr base = 'field' + } + class MixedOrderChild extends MixedOrderBase { + get derived() { + return this.base + } + } + attr(MixedOrderChild.prototype, 'derived') + controller(MixedOrderChild) + + expect(observed(MixedOrderChild)).to.deep.equal(['data-base', 'data-derived']) + const instance = await fixture(html``) + expect(instance).to.have.attribute('data-derived', 'attribute') + }) + + it('initializes standard stored attrs before legacy attrs on the same class', async () => { + class MixedSameClass extends HTMLElement { + @attr base = 'field' + get derived() { + return this.base + } + } + attr(MixedSameClass.prototype, 'derived') + controller(MixedSameClass) + + const instance = await fixture(html``) + expect(instance).to.have.attribute('data-derived', 'attribute') + }) + + for (const registered of [false, true]) { + it(`initializes an overriding legacy getter after the attrs it reads${ + registered ? ', with a registered base' : '' + }`, async () => { + class Base extends HTMLElement { + @attr get label() { + return 'base' + } + } + class Child extends Base { + input = 'field' + get label() { + return `${this.input}-label` + } + } + if (registered) defineObservedAttributes(Base) + attr(Child.prototype, 'input') + attr(Child.prototype, 'label') + const name = registered ? 'mixed-override-registered' : 'mixed-override' + controller(name)(Child) + + const instance = document.createElement(name) + instance.setAttribute('data-input', 'attribute') + document.body.append(instance) + expect(instance).to.have.attribute('data-label', 'attribute-label') + instance.remove() + }) + } + + it('initializes a legacy getter overriding a standard accessor attr after the attrs it reads', async () => { + class Base extends HTMLElement { + @attr accessor label = 'base' + } + class Child extends Base { + input = 'field' + // A getter without a setter computes its value, so it initializes after the attrs it reads. + override get label() { + return `${this.input}-label` + } + } + attr(Child.prototype, 'input') + attr(Child.prototype, 'label') + controller('mixed-accessor-override')(Child) + + const instance = document.createElement('mixed-accessor-override') + instance.setAttribute('data-input', 'attribute') + document.body.append(instance) + expect(instance).to.have.attribute('data-label', 'attribute-label') + instance.remove() + }) + + it('initializes standard fields before legacy fields registered later on the same class', async () => { + class MixedCallbackOrder extends HTMLElement { + @attr ready = true + status = 'default' + attributeChangedCallback(name: string) { + if (name === 'data-ready') this.status = 'updated' + } + } + attr(MixedCallbackOrder.prototype, 'status') + controller(MixedCallbackOrder) + + const instance = await fixture(html``) + expect(instance).to.have.attribute('data-status', 'html') + }) + + it('initializes legacy base attrs before standard subclass attrs', async () => { + class MixedLegacyBase extends HTMLElement { + base = 'field' + } + attr(MixedLegacyBase.prototype, 'base') + @controller + class MixedLegacyChildElement extends MixedLegacyBase { + @attr get derived() { + return `${this.base}-derived` + } + } + + const instance = await fixture( + html`` + ) + expect(instance.getAttribute('data-derived')).to.equal('attribute-derived') + }) + + it('includes standard base attrs registered after a subclass recorded legacy attrs', async () => { + class MixedLateBase extends HTMLElement { + @attr base = '' + } + class MixedLateChild extends MixedLateBase { + child = '' + } + attr(MixedLateChild.prototype, 'child') + defineObservedAttributes(MixedLateBase) + controller(MixedLateChild) + + const instance = await fixture(html``) + expect(instance).to.have.property('base', 'attribute') + }) + }) + + it('reads metadata stored under a Symbol.metadata defined after Catalyst loaded', async () => { + const original = symbolWithMetadata.metadata + symbolWithMetadata.metadata = Symbol('late metadata') + try { + @controller + class StandardLateMetadataElement extends HTMLElement { + @attr late = 'yes' + } + const instance = await fixture( + html`` + ) + expect(instance.getAttribute('data-late')).to.equal('yes') + } finally { + symbolWithMetadata.metadata = original + } + }) + + it('reads base class metadata stored before Symbol.metadata changed', async () => { + const original = symbolWithMetadata.metadata + class StandardLateBase extends HTMLElement { + @attr early = 'early' + } + symbolWithMetadata.metadata = Symbol('late metadata') + let instance: HTMLElement + try { + @controller + class StandardLateChildElement extends StandardLateBase { + @attr late = 'late' + } + instance = await fixture(html``) + } finally { + symbolWithMetadata.metadata = original + } + expect(instance.getAttribute('data-early')).to.equal('early') + expect(instance.getAttribute('data-late')).to.equal('late') + }) + + it('records subclass attrs when the base class metadata is frozen', async () => { + const freeze = (_: unknown, context: ClassDecoratorContext) => void Object.freeze(context.metadata) + @freeze + class FrozenMetadataBase extends HTMLElement { + @attr base = 'base' + } + @controller + class FrozenMetadataChildElement extends FrozenMetadataBase { + @attr child = 'child' + } + expect(observed(FrozenMetadataChildElement)).to.eql(['data-base', 'data-child']) + const instance = await fixture(html``) + expect(instance).to.have.attribute('data-base', 'base') + expect(instance).to.have.attribute('data-child', 'child') + }) + + it('throws a clear error without decorator metadata', () => { + const original = symbolWithMetadata.metadata + delete symbolWithMetadata.metadata + try { + expect( + () => + class extends HTMLElement { + @attr foo = '' + } + ).to.throw(TypeError, '@attr requires decorator metadata') + } finally { + symbolWithMetadata.metadata = original + } + }) + + it('throws for unsupported members', () => { + const message = '@attr must decorate a public instance field/accessor/getter/setter' + expect( + () => + class extends HTMLElement { + // @ts-expect-error static members are not supported + @attr static foo = '' + } + ).to.throw(TypeError, message) + expect( + () => + class extends HTMLElement { + // @ts-expect-error private members are not supported + @attr #foo = '' + } + ).to.throw(TypeError, message) + expect( + () => + class extends HTMLElement { + // @ts-expect-error methods are not supported + @attr foo() { + return '' + } + } + ).to.throw(TypeError, message) + }) + + it('throws when a class decorator decorates a member', () => { + for (const [decorator, name] of [ + [controller, 'controller'], + [register, 'register'], + [defineObservedAttributes, 'defineObservedAttributes'] + ] as const) { + expect( + () => + class extends HTMLElement { + // @ts-expect-error class decorators can't decorate methods + @decorator foo() {} + } + ).to.throw(TypeError, `@${name} must decorate a class`) + } + }) +}) diff --git a/test/standard/metadata.ts b/test/standard/metadata.ts new file mode 100644 index 00000000..89a4ec5e --- /dev/null +++ b/test/standard/metadata.ts @@ -0,0 +1,29 @@ +// Imports Catalyst first and avoids @open-wc/testing, because Lit defines `Symbol.metadata` too. +import {controller} from '../../src/controller.js' +import {attr} from '../../src/attr.js' + +function assert(condition: boolean, message: string) { + if (!condition) throw new Error(message) +} + +describe('Symbol.metadata (standard decorators)', () => { + it('is defined when Catalyst loads, so TypeScript output includes decorator metadata', () => { + const metadata = (Symbol as {metadata?: symbol}).metadata + assert(typeof metadata === 'symbol', `expected Symbol.metadata, got ${String(metadata)}`) + }) + + it('registers attrs from TypeScript output', () => { + @controller + class StandardMetadataElement extends HTMLElement { + @attr foo = 'bar' + } + const instance = document.createElement('standard-metadata') + document.body.append(instance) + assert(instance instanceof StandardMetadataElement, 'expected the element to be defined') + assert( + instance.getAttribute('data-foo') === 'bar', + `expected data-foo="bar", got ${instance.getAttribute('data-foo')}` + ) + instance.remove() + }) +}) diff --git a/test/standard/target.ts b/test/standard/target.ts new file mode 100644 index 00000000..29d26794 --- /dev/null +++ b/test/standard/target.ts @@ -0,0 +1,63 @@ +import {expect, fixture, html} from '@open-wc/testing' +import {target, targets} from '../../src/target.js' +import {controller} from '../../src/controller.js' +import {targetTests} from '../helpers/target-tests.js' + +describe('Targetable (standard decorators)', () => { + @controller + class TargetTestElement extends HTMLElement { + @target accessor foo!: Element + bar = 'hello' + @target accessor baz!: Element + @target accessor qux!: Element + @target accessor shadow!: Element + @target accessor bing!: Element + @targets accessor foos!: Element[] + } + + targetTests() + + it('names the target in the assignment error', async () => { + const instance = await fixture(html``) + expect(() => { + instance.foo = document.body + }).to.throw(TypeError, 'Cannot set @target foo') + expect(() => { + instance.foos = [] + }).to.throw(TypeError, 'Cannot set @targets foos') + }) + + it('throws for members other than public instance accessors', () => { + const message = '@target must decorate a public instance accessor' + expect( + () => + class extends HTMLElement { + // @ts-expect-error fields would shadow the getter + @target foo!: Element + } + ).to.throw(TypeError, message) + expect( + () => + class extends HTMLElement { + // @ts-expect-error static members are not supported + @target static accessor foo: Element + } + ).to.throw(TypeError, message) + expect( + () => + class extends HTMLElement { + // @ts-expect-error private members are not supported + @target accessor #foo!: Element + } + ).to.throw(TypeError, message) + expect( + () => + class extends HTMLElement { + // @ts-expect-error methods are not supported + @targets foo() { + return [] + } + } + ).to.throw(TypeError, '@targets must decorate a public instance accessor') + }) +}) diff --git a/test/standard/tsconfig.json b/test/standard/tsconfig.json new file mode 100644 index 00000000..07a99134 --- /dev/null +++ b/test/standard/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.json", + "include": ["*.ts", "../attr.ts", "../bind.ts", "../controller.ts", "../register.ts", "../helpers/*.ts", "../types/*.ts"], + "exclude": [], + "compilerOptions": { + "experimentalDecorators": false, + "target": "ES2022" + } +} diff --git a/test/target.ts b/test/target.ts index 8967040c..4e496cc1 100644 --- a/test/target.ts +++ b/test/target.ts @@ -1,6 +1,6 @@ -import {expect, fixture, html} from '@open-wc/testing' import {target, targets} from '../src/target.js' import {controller} from '../src/controller.js' +import {targetTests} from './helpers/target-tests.js' describe('Targetable', () => { @controller @@ -19,80 +19,5 @@ describe('Targetable', () => { @target shadows!: Element[] } - let instance: HTMLElement - beforeEach(async () => { - instance = await fixture(html` - -
-
-
-
-
-
-
-
-
-
`) - }) - - describe('target', () => { - it('returns the first element where closest tag is the controller', async () => { - expect(instance).to.have.property('foo').exist.with.attribute('id', 'el4') - expect(instance.querySelector('target-test')).to.have.property('foo').exist.with.attribute('id', 'el2') - }) - - it('does not assign to non-target decorated properties', async () => { - expect(instance).to.have.property('bar', 'hello') - }) - - it('returns the first element that has the exact target name', async () => { - expect(instance).to.have.property('baz').exist.with.attribute('id', 'el5') - }) - - it('returns target when there are mutliple target values', async () => { - expect(instance).to.have.property('bing').exist.with.attribute('id', 'el6') - }) - - it('returns targets when there are mutliple target values with different controllers', async () => { - expect(instance).to.have.property('qux').exist.with.attribute('id', 'el8') - }) - - it('returns targets from the shadowRoot, if available', async () => { - instance.attachShadow({mode: 'open'}) - const el = document.createElement('div') - el.setAttribute('data-target', 'target-test.shadow') - instance.shadowRoot!.appendChild(el) - expect(instance).to.have.property('shadow', el) - }) - - it('prioritises shadowRoot targets over others', async () => { - instance.attachShadow({mode: 'open'}) - const shadowEl = document.createElement('div') - shadowEl.setAttribute('data-target', 'target-test.foo') - instance.shadowRoot!.appendChild(shadowEl) - expect(instance).to.have.property('foo', shadowEl) - }) - }) - - describe('targets', () => { - it('returns all elements where closest tag is the controller', async () => { - expect(instance).to.have.property('foos').with.lengthOf(2) - expect(instance).to.have.nested.property('foos[0]').with.attribute('id', 'el4') - expect(instance).to.have.nested.property('foos[1]').with.attribute('id', 'el5') - }) - - it('returns all elements inside a shadow root', async () => { - instance.attachShadow({mode: 'open'}) - const els = [document.createElement('div'), document.createElement('div'), document.createElement('div')] - for (const el of els) el.setAttribute('data-targets', 'target-test.foos') - instance.shadowRoot!.append(...els) - - expect(instance).to.have.property('foos').with.lengthOf(5) - expect(instance).to.have.nested.property('foos[0]', els[0]) - expect(instance).to.have.nested.property('foos[1]', els[1]) - expect(instance).to.have.nested.property('foos[2]', els[2]) - expect(instance).to.have.nested.property('foos[3]').with.attribute('id', 'el4') - expect(instance).to.have.nested.property('foos[4]').with.attribute('id', 'el5') - }) - }) + targetTests() }) diff --git a/test/types/decorators.ts b/test/types/decorators.ts new file mode 100644 index 00000000..d1971f25 --- /dev/null +++ b/test/types/decorators.ts @@ -0,0 +1,63 @@ +// Compile-time checks, run under both decorator modes: `tsc` (experimentalDecorators), and `tsc -p test/standard` and +// `tsc -p test/types` (standard decorators). test/types adds `exactOptionalPropertyTypes` without the `Symbol.metadata` +// declaration Lit adds in test/standard. Nothing here runs. `@target` and `@targets` need `accessor` in standard mode +// and a plain field in legacy mode, so they're covered by test/target.ts and test/standard/target.ts instead. +import {controller} from '../../src/controller.js' +import {attr, defineObservedAttributes} from '../../src/attr.js' +import {register} from '../../src/register.js' +import {target, targets} from '../../src/target.js' +import type {CustomElementClass} from '../../src/custom-element.js' + +@controller +export class TypesElement extends HTMLElement { + static attrPrefix = 'types-' + static observedAttributes = ['data-extra'] + + @attr text = '' + @attr count = 0 + @attr enabled = false + + @attr + get computed(): string { + return '' + } + set computed(value: string) { + this.text = value + } + + // @ts-expect-error attrs must be strings, numbers or booleans + @attr date = new Date() + + // @ts-expect-error attrs must be strings, numbers or booleans + @attr set untypedSetter(value: unknown) { + this.text = String(value) + } +} + +@controller('types-named-element') +export class TypesNamedElement extends HTMLElement {} + +controller('types-direct-element')(class TypesDirectElement extends HTMLElement {}) +controller(class TypesDirectUnnamedElement extends HTMLElement {}) +attr(TypesElement.prototype, 'text') + +// The decorator `controller(name)` returns is still assignable to the legacy class decorator type. +export const named: (classObject: CustomElementClass) => void = controller('types-assigned-element') + +// Legacy-style calls with untyped arguments keep their legacy return types. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +declare const untyped: any +export const targetResult: void = target(untyped, untyped) +export const targetsResult: void = targets(untyped, untyped) +export const registerResult: CustomElementClass = register(untyped, untyped) + +// Types read from the last overload, such as `ReturnType`, also keep their legacy types. +export const registerReturn: CustomElementClass = null as unknown as ReturnType +export const targetParameters: [Record, string] = null as unknown as Parameters +export const targetsReturn: void = null as unknown as ReturnType +export const defineObservedAttributesParameters: [CustomElementClass] = null as unknown as Parameters< + typeof defineObservedAttributes +> +// Callbacks such as `map` pass extra arguments, which the legacy overload accepts. +export const defineObservedAttributesCallback: (classObject: CustomElementClass, index: number) => void = + defineObservedAttributes diff --git a/test/types/tsconfig.json b/test/types/tsconfig.json new file mode 100644 index 00000000..39bdd72a --- /dev/null +++ b/test/types/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.json", + "include": ["*.ts"], + "exclude": [], + "compilerOptions": { + "experimentalDecorators": false, + "exactOptionalPropertyTypes": true, + "target": "ES2022" + } +} diff --git a/tsconfig.json b/tsconfig.json index ed9814a5..9b7b7916 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,5 +1,6 @@ { "include": ["src", "test"], + "exclude": ["test/standard"], "compilerOptions": { "baseUrl": ".", "esModuleInterop": true, diff --git a/web-test-runner-standard.config.js b/web-test-runner-standard.config.js new file mode 100644 index 00000000..cc641977 --- /dev/null +++ b/web-test-runner-standard.config.js @@ -0,0 +1,35 @@ +import ts from 'typescript' +import config from './web-test-runner.config.js' + +// Tests that use Catalyst's decorators with the same syntax in both modes. They run here with standard decorators, +// and in web-test-runner.config.js with legacy decorators. test/standard has tests that need standard-only syntax. +export const sharedFiles = ['test/attr.ts', 'test/bind.ts', 'test/controller.ts', 'test/register.ts'] + +// Compile tests and source the way a modern TypeScript build does: standard decorators and native ES2022 class fields +// with define semantics. This replaces the esbuild plugin, which only lowers legacy decorators, and whose class lowering +// renames classes, which Catalyst derives tag names from. +const standardDecorators = { + name: 'standard-decorators', + resolveMimeType(context) { + if (context.path.endsWith('.ts')) return 'js' + }, + transform(context) { + if (!/^\/(src|test)\/.*\.ts$/.test(context.path)) return + const {outputText} = ts.transpileModule(context.body, { + fileName: context.path, + compilerOptions: { + experimentalDecorators: false, + target: ts.ScriptTarget.ES2022, + useDefineForClassFields: true, + module: ts.ModuleKind.ESNext + } + }) + return {body: outputText} + } +} + +export default { + ...config, + files: [...sharedFiles, 'test/standard/*.ts'], + plugins: [standardDecorators] +} diff --git a/web-test-runner.config.js b/web-test-runner.config.js index 68d0a046..a1bbe3d7 100644 --- a/web-test-runner.config.js +++ b/web-test-runner.config.js @@ -1,7 +1,7 @@ import {esbuildPlugin} from '@web/dev-server-esbuild' export default { - files: ['test/*'], + files: ['test/*.ts'], nodeResolve: true, concurrency: 1, testsFinishTimeout: 30000,