@brightspace-ui/labs 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2022 D2L Corporation
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,115 @@
1
+ # @brightspace-ui/labs
2
+
3
+ [![NPM version](https://img.shields.io/npm/v/@brightspace-ui/labs.svg)](https://www.npmjs.org/package/@brightspace-ui/labs)
4
+
5
+ A collection of experimental web components and tools for building Brightspace applications.
6
+
7
+ ## Installation
8
+
9
+ Install from NPM:
10
+
11
+ ```shell
12
+ npm install @brightspace-ui/labs
13
+ ```
14
+
15
+ ## README Index
16
+
17
+
18
+ ## Developing, Testing and Contributing
19
+
20
+ After cloning the repo, run `npm install` to install dependencies.
21
+
22
+ ### Linting
23
+
24
+ ```shell
25
+ # eslint and lit-analyzer
26
+ npm run lint
27
+
28
+ # eslint only
29
+ npm run lint:eslint
30
+ ```
31
+
32
+ ### Testing
33
+
34
+ ```shell
35
+ # lint & run headless unit tests
36
+ npm test
37
+
38
+ # unit tests only
39
+ npm run test:headless
40
+
41
+ # debug or run a subset of local unit tests
42
+ npm run test:headless:watch
43
+ ```
44
+
45
+ ### Visual Diff Testing
46
+
47
+ This repo uses the [@brightspace-ui/visual-diff utility](https://github.com/BrightspaceUI/visual-diff/) to compare current snapshots against a set of golden snapshots stored in source control.
48
+
49
+ The golden snapshots in source control must be updated by the [visual-diff GitHub Action](https://github.com/BrightspaceUI/actions/tree/main/visual-diff). If a pull request results in visual differences, a draft pull request with the new goldens will automatically be opened against its branch.
50
+
51
+ To run the tests locally to help troubleshoot or develop new tests, first install these dependencies:
52
+
53
+ ```shell
54
+ npm install @brightspace-ui/visual-diff@X mocha@Y puppeteer@Z --no-save
55
+ ```
56
+
57
+ Replace `X`, `Y` and `Z` with [the current versions](https://github.com/BrightspaceUI/actions/tree/main/visual-diff#current-dependency-versions) the action is using.
58
+
59
+ Then run the tests:
60
+
61
+ ```shell
62
+ # run visual-diff tests
63
+ npx mocha './test/**/*.visual-diff.js' -t 10000
64
+ # subset of visual-diff tests:
65
+ npx mocha './test/**/*.visual-diff.js' -t 10000 -g some-pattern
66
+ # update visual-diff goldens
67
+ npx mocha './test/**/*.visual-diff.js' -t 10000 --golden
68
+ ```
69
+
70
+ ### Running the demos
71
+
72
+ To start a [@web/dev-server](https://modern-web.dev/docs/dev-server/overview/) that hosts the demo pages and tests:
73
+
74
+ ```shell
75
+ npm start
76
+ ```
77
+
78
+ ## Versioning & Releasing
79
+
80
+ > TL;DR: Commits prefixed with `fix:` and `feat:` will trigger patch and minor releases when merged to `main`. Read on for more details...
81
+
82
+ The [semantic-release GitHub Action](https://github.com/BrightspaceUI/actions/tree/main/semantic-release) is called from the `release.yml` GitHub Action workflow to handle version changes and releasing.
83
+
84
+ ### Version Changes
85
+
86
+ All version changes should obey [semantic versioning](https://semver.org/) rules:
87
+ 1. **MAJOR** version when you make incompatible API changes,
88
+ 2. **MINOR** version when you add functionality in a backwards compatible manner, and
89
+ 3. **PATCH** version when you make backwards compatible bug fixes.
90
+
91
+ The next version number will be determined from the commit messages since the previous release. Our semantic-release configuration uses the [Angular convention](https://github.com/conventional-changelog/conventional-changelog/tree/master/packages/conventional-changelog-angular) when analyzing commits:
92
+ * Commits which are prefixed with `fix:` or `perf:` will trigger a `patch` release. Example: `fix: validate input before using`
93
+ * Commits which are prefixed with `feat:` will trigger a `minor` release. Example: `feat: add toggle() method`
94
+ * To trigger a MAJOR release, include `BREAKING CHANGE:` with a space or two newlines in the footer of the commit message
95
+ * Other suggested prefixes which will **NOT** trigger a release: `build:`, `ci:`, `docs:`, `style:`, `refactor:` and `test:`. Example: `docs: adding README for new component`
96
+
97
+ To revert a change, add the `revert:` prefix to the original commit message. This will cause the reverted change to be omitted from the release notes. Example: `revert: fix: validate input before using`.
98
+
99
+ ### Releases
100
+
101
+ When a release is triggered, it will:
102
+ * Update the version in `package.json`
103
+ * Tag the commit
104
+ * Create a GitHub release (including release notes)
105
+ * Deploy a new package to NPM
106
+
107
+ ### Releasing from Maintenance Branches
108
+
109
+ Occasionally you'll want to backport a feature or bug fix to an older release. `semantic-release` refers to these as [maintenance branches](https://semantic-release.gitbook.io/semantic-release/usage/workflow-configuration#maintenance-branches).
110
+
111
+ Maintenance branch names should be of the form: `+([0-9])?(.{+([0-9]),x}).x`.
112
+
113
+ Regular expressions are complicated, but this essentially means branch names should look like:
114
+ * `1.15.x` for patch releases on top of the `1.15` release (after version `1.16` exists)
115
+ * `2.x` for feature releases on top of the `2` release (after version `3` exists)
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "labs",
3
+ "parser_plugin": {
4
+ "plugin": "parse_js"
5
+ },
6
+ "source_match": "en\\.js$",
7
+ "source_dir": "src/lang",
8
+ "output_file_path": "src/lang/%LANG%.js"
9
+ }
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@brightspace-ui/labs",
3
+ "description": "A collection of experimental web components and tools for building Brightspace applications.",
4
+ "type": "module",
5
+ "repository": "https://github.com/BrightspaceUI/labs.git",
6
+ "exports": {
7
+ "./controllers/computed-value.js": "./src/controllers/computed-values/computed-value.js",
8
+ "./controllers/computed-values.js": "./src/controllers/computed-values/computed-values.js"
9
+ },
10
+ "scripts": {
11
+ "lint": "npm run lint:eslint && npm run lint:lit && npm run lint:style",
12
+ "lint:eslint": "eslint . --ext .js,.html",
13
+ "lint:lit": "lit-analyzer \"src/**/*.js\" --strict",
14
+ "lint:style": "stylelint \"**/*.{js,html}\"",
15
+ "start": "web-dev-server --node-resolve --open --watch",
16
+ "test": "npm run lint && npm run test:headless",
17
+ "test:headless": "web-test-runner",
18
+ "test:headless:watch": "web-test-runner --watch"
19
+ },
20
+ "author": "D2L Corporation",
21
+ "license": "Apache-2.0",
22
+ "devDependencies": {
23
+ "@babel/core": "^7",
24
+ "@babel/eslint-parser": "^7",
25
+ "@brightspace-ui/stylelint-config": "^0.4",
26
+ "@open-wc/testing": "^2",
27
+ "@web/dev-server": "^0.1",
28
+ "@web/test-runner": "^0.13",
29
+ "eslint": "^8",
30
+ "eslint-config-brightspace": "^0.17",
31
+ "eslint-plugin-html": "^6",
32
+ "eslint-plugin-import": "^2",
33
+ "eslint-plugin-lit": "^1",
34
+ "eslint-plugin-sort-class-members": "^1",
35
+ "lit-analyzer": "^1",
36
+ "stylelint": "^14"
37
+ },
38
+ "files": [
39
+ "labs.serge.json",
40
+ "/src"
41
+ ],
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "dependencies": {
46
+ "@brightspace-ui/core": "^2",
47
+ "lit": "^2"
48
+ },
49
+ "version": "1.0.0"
50
+ }
@@ -0,0 +1,170 @@
1
+ # ComputedValues Controller
2
+
3
+ The `ComputedValues` (plural) controller allows you to define a collection of `ComputedValue` (singular) controllers. Each of these `ComputedValue` controllers holds a value that is dependent on other variables or properties within a component and will automatically update that value whenever the dependencies change.
4
+
5
+ The main benefit of this controller is that it gives a quick and clean way of definining the update and computation logic of an instance member that is dependent on other members or properties.
6
+
7
+ Some use cases for this controller include:
8
+ * Computing values that you want to show in render, but whose computation is too expensive to perform every render (ex: filtering or sorting a list in the front end based on user input).
9
+ * Asynchronously computing values whenever a dependency changes (ex: refetching a value from the API any time a specific property changes).
10
+ * Creating a reusable controller that knows how to recompute a value based on dependencies.
11
+
12
+ ## `ComputedValues` vs `ComputedValue`
13
+
14
+ Internally, the `ComputedValues` (plural) controller uses another controller called `ComputedValue` (singular). The `ComputedValue` controller holds the majority of the functionality that `ComputedValues` uses and the `ComputedValues` controller simply instantiates a collection of `ComputedValue` controllers and assigns them to itself for easy access.
15
+
16
+ While it's possible to use the `ComputedValue` controller directly, it is recommended that the `ComputedValues` controller be used in most cases, since it makes it easier to create a collection of computed values. Direct use of the `ComputedValue` controller should be reserved for creating reusable controllers.
17
+
18
+ ## Usage
19
+
20
+ Create an instance of the `ComputedValues` controller and assign it to a member variable. Pass the host and an array of objects to the constructor that each represent one value that will be computed based on dependencies.
21
+
22
+ ```js
23
+ import ComputedValues from '@brightspace-ui/labs/controllers/computed-values.js';
24
+
25
+ class DemoComponent extends LitElement {
26
+ static properties = {
27
+ firstName: { type: String },
28
+ lastName: { type: String }
29
+ };
30
+
31
+ constructor() {
32
+ super();
33
+ this.firstName = 'John';
34
+ this.lastName = 'Smith';
35
+ }
36
+
37
+ render() {
38
+ return html`
39
+ <p>
40
+ fullName: ${this._computed.fullName.value}<br>
41
+ screamingFullName: ${this._computed.screamingFullName.value}<br>
42
+ shortName: ${this._computed.shortName.value}<br>
43
+ asyncName: ${this._computed.asyncName.pending ? '<loading...>' : this._computed.asyncName.value}<br>
44
+ </p>
45
+ `;
46
+ }
47
+
48
+ _computed = new ComputedValues(this, [{
49
+ // This computed value is dependent on both firstName and lastName
50
+ name: 'fullName',
51
+ initialValue: '',
52
+ getDependencies: () => [this.firstName, this.lastName],
53
+ compute: (firstName, lastName) => `${firstName} ${lastName}`
54
+ }, {
55
+ // This computed value is dependent on the fullName computed value
56
+ name: 'screamingFullName',
57
+ initialValue: '',
58
+ getDependencies: () => [this._computed.fullName.value],
59
+ compute: (fullName) => fullName.toUpperCase()
60
+ }, {
61
+ // This computed value implements a custom shouldCompute method
62
+ name: 'shortName',
63
+ initialValue: '',
64
+ isAsync: true,
65
+ getDependencies: () => [this.firstName, this.lastName],
66
+ shouldCompute: (prevDeps, currDeps) => {
67
+ if (prevDeps === null) return true;
68
+
69
+ const [prevFirstName, prevLastName] = prevDeps;
70
+ const [currFirstName, currLastName] = currDeps;
71
+
72
+ return prevFirstName[0] !== currFirstName[0] || prevLastName !== currLastName;
73
+ },
74
+ compute: (firstName, lastName) => {
75
+ return `${firstName[0]}. ${lastName}`;
76
+ }
77
+ }, {
78
+ // This computed value is asynchronous
79
+ name: 'asyncName',
80
+ initialValue: '',
81
+ isAsync: true,
82
+ getDependencies: () => [this.firstName, this.lastName],
83
+ compute: async(firstName, lastName) => {
84
+ return await asyncApiCall(firstName, lastName);
85
+ }
86
+ }]);
87
+ }
88
+ ```
89
+
90
+ Check the demo page for additional working examples.
91
+
92
+ ## Compute Lifecycle
93
+
94
+ There is a flow of steps that each `ComputedValue` instance follows in order to compute its value. Being aware of how this controller works is important to understand how best to make use of it.
95
+
96
+ ### Host `update`
97
+
98
+ The compute lifecycle starts with the host executing its `update` method, which then triggers the controller's `hostUpdate`.
99
+
100
+ All computation logic for this controller starts here. So, if the host's `update` method isn't called (for example by never triggering one or by explicitly using `shouldUpdate` to skip updates), then computes will never be called.
101
+
102
+ This also means that `compute` functions should not look at the dom directly, since the logic for calculating the updated value happens before the render executes.
103
+
104
+ ### Controller `getDependencies` and `shouldCompute`
105
+
106
+ The `getDependencies` and `shouldCompute` functions are important in order to decide whether to execute the `compute` function. As such, these two functions are called every host `update` for each `ComputedValue` instance.
107
+
108
+ The `getDependencies` function must always be defined by the consumer, whereas the `shouldCompute` function has an internal default if the consumer does not define their own.
109
+
110
+ The default `shouldCompute` function will do an indentity comparison for each of the previous and current dependencies one by one and return true immediately if one of the dependencies has changed.
111
+
112
+ While this controller can be very helpful for making sure to only execute heavy computations when needed, be aware of the performance costs of using this approach. So, keep in mind what processes occur each `update` call.
113
+
114
+ ### Controller `compute`
115
+
116
+ Once the `shouldCompute` function returns true during the `update` step, the `compute` function will be called.
117
+
118
+ If the controller is set to run synchronously, the `compute` function will execute in its entirety and the return value will be assigned to the controller's `value` instance member. This all happens during the host's `update` step.
119
+
120
+ If the controller is set to run asynchronously, the controller will call the `compute` function and expect a promise as the return value. It will update its async statuses as appropriate before continuing with the host's `update` step. Once the promise returned from the `compute` function resolves, the controller will assign the result to the controller's `value` instance member, it will update its async statuses as appropriate, and will then request and update from the host using `requestUpdate`.
121
+
122
+ Note that if the controller is asynchronous and a controller's `compute` functions is called while a previous `compute` call is in progress, only the last `compute` function call will update the value and async statuses.
123
+
124
+ ## Order of `ComputeValue` Instances
125
+
126
+ The compute lifecycle for each `ComputeValue` controller instance will be executed in its entirety before moving on to the next. This means that the order that these instances are defined in the array matters in some cases. If one of the controller instances is dependent on the result from another, then the one that is being depended on must come first in the order to make sure the most up-to-date value is passed to the dependant.
127
+
128
+ ## `ComputedValues` Instance Methods
129
+
130
+ ### Constructor
131
+
132
+ | Parameter Name | Type | Description | Required |
133
+ |---|---|---|---|
134
+ | `host` | LitElement | The host for the controller. | Yes |
135
+ | `valuesOptions` | Array | The array of objects that each define a computed value. | Yes |
136
+ | `valuesOptions[i].name` | String | The name of the computed value. Used to assign the internal `ComputedValue` instance to the `ComputedValues` instance. | Yes |
137
+ | `...valuesOptions[i]` | Object | The rest of the attributes for the object are passed to the internal `ComputedValue` instance constructor. See the `ComputedValue` constructor for details. | Yes |
138
+
139
+ ## `ComputedValues` Instance Members
140
+
141
+ | Member Name | Type | Description |
142
+ |---|---|---|
143
+ |`this[name]` | `ComputedValue` controller | For each of the objects in the `valuesOptions` array, a `ComputedValue` controller is instantiated and assigned to a memeber on the `ComputedValues` controller instance.<br><br>For example, the following `ComputedValues` instance...<br><br><pre>class MyElement extends LitElement {<br> _computed = new ComputedValues(this, [{<br> name: 'myValue',<br> ...<br> }]);<br>}</pre><br>...will end up with a `ComputedValue` instance assigned to `this._computed.myValue`.<br><br>For details on what instance members each `ComputedValue` instance has, see the `ComputedValue` Instance Members section below. |
144
+
145
+ ## `ComputedValue` Instance Methods
146
+
147
+ ### Constructor
148
+
149
+ | Parameter Name | Type | Description | Required |
150
+ |---|---|---|---|
151
+ | `host` | Lit Element | The host for the controller. | Yes |
152
+ | `options` | Object | A collection of options for the controller. | Yes |
153
+ | `options.getDependencies` | Function() : Array | The function used to get the array of dependencies for this value. Must return an array and the array should always be the same length. The previous and current dependencies will be used to decide whether or not to update, so they should be kept in the same order as well. | Yes |
154
+ | `options.compute` | Function(...Any) : Any | The function used to calculate the computed value. It's passed the most recent dependencies every time it is called, and the return value is assigned to the controller value member before each render. | Yes |
155
+ | `options.initialValue` | Any | The value of the controller value member before the first update occurs. | |
156
+ | `options.shouldCompute` | Function(Array, Array) : Bool | The function used to decide whether or not to run the compute function.<br><br>This function is passed an array of the previous dependencies and an array of the current dependencies. It must return a boolean representing whether to call the compute function or not.<br><br>If not assigned, the default `shouldCompute` function will do an indentity comparison for each of the previous and current dependencies one by one and return true immediately if one of the dependencies has changed. | |
157
+ | `options.isAsync` | Bool | This tells the controller whether the compute function is asynchronous. If this is true, the compute function must return a promise. | |
158
+ | `options.shouldRequestUpdate` | Function(Object, Object) : Bool | This function is used to decide whether or not to call the host's `requestUpdate` method after an async `compute` function finished updating the value.<br><br>This function is passed an object that contains the value and async status before the compute finished executing, and one object with the current value and async status. It must return a boolean representing whether to call the `requestUpdate` method or not.<br><br>If not assigned, this defaults to a function that always returns true. | |
159
+
160
+ ## `ComputedValue` Instance Members
161
+
162
+ | Member Name | Type | Description |
163
+ |---|---|---|
164
+ | `host` | LitElement | The host element of this controller. |
165
+ | `value` | Any | This holds the computed value of the controller. |
166
+ | `pending` | Bool | Only used when the controller is async. This will be true while an async compute is processing, and false otherwise. |
167
+ | `success` | Bool\|Null | Only used when the controller is async. This will be set to true if the previous async compute resolved successfully. This will be set to false if the previous async compute threw an error. This will be set to null if no async compute function has completed yet. |
168
+ | `error` | Any | Only used when the controller is async. This will hold error info in the event that previous async compute threw an error. This will be assigned null otherwise. |
169
+ | `asyncStatus` | String | Only used when the controller is async. This holds a string representing the current async status of the controller.<br>`"initial"`: Before the first compute function is called.<br>`"pending"`: While an async compute function is in progress.<br>`"success"`: If the last async compute was successful (and another is not currently pending).<br>`"error"`: If the last async compute ended in error (and another is not currently pending). |
170
+ | `computeComplete` | Promise | This member is assigned a promise whenever the value starts being computed, and that promise resolves when the value is done being computed. Note that this is intended to be used for testing and should not be relied on for normal use cases. |
@@ -0,0 +1,159 @@
1
+ export const ASYNC_STATUSES = Object.freeze({
2
+ INITIAL: 'initial',
3
+ PENDING: 'pending',
4
+ SUCCESS: 'success',
5
+ ERROR: 'error'
6
+ });
7
+
8
+ function defaultShouldCompute(prevDependencies, currDependencies) {
9
+ // If no dependencies exist yet, then this is the first update
10
+ if (prevDependencies === null) {
11
+ return true;
12
+ }
13
+
14
+ return prevDependencies.some((prev, index) => prev !== currDependencies[index]);
15
+ }
16
+
17
+ export default class ComputedValue {
18
+ computeComplete = Promise.resolve();
19
+ error = null;
20
+ host;
21
+ pending = false;
22
+ success = null;
23
+ value;
24
+
25
+ constructor(host, options = {}) {
26
+ const {
27
+ compute,
28
+ shouldCompute = defaultShouldCompute,
29
+ getDependencies,
30
+ isAsync = false,
31
+ shouldRequestUpdate = () => true,
32
+ initialValue
33
+ } = options;
34
+
35
+ if (typeof compute !== 'function') {
36
+ throw new TypeError('Failed to initialize ComputedValueController: compute parameter must be a function.');
37
+ }
38
+
39
+ if (typeof getDependencies !== 'function') {
40
+ throw new TypeError('Failed to initialize ComputedValueController: getDependencies parameter must be a function.');
41
+ }
42
+
43
+ this._compute = compute;
44
+ this._shouldCompute = shouldCompute;
45
+ this._getDependencies = getDependencies;
46
+ this._isAsync = isAsync;
47
+ this._shouldRequestUpdate = shouldRequestUpdate;
48
+ this.value = initialValue;
49
+
50
+ (this.host = host).addController(this);
51
+ }
52
+
53
+ get asyncStatus() {
54
+ if (this.pending) {
55
+ return ASYNC_STATUSES.PENDING;
56
+ }
57
+
58
+ if (this.success === null) {
59
+ return ASYNC_STATUSES.INITIAL;
60
+ }
61
+
62
+ if (this.success) {
63
+ return ASYNC_STATUSES.SUCCESS;
64
+ }
65
+
66
+ return ASYNC_STATUSES.ERROR;
67
+ }
68
+
69
+ hostUpdate() {
70
+ const currDependencies = this._getDependencies();
71
+
72
+ if (this._shouldCompute(this._prevDependencies, currDependencies)) {
73
+ this._prevDependencies = currDependencies;
74
+ this._updateValue(currDependencies);
75
+ }
76
+ }
77
+
78
+ _compute;
79
+ _computeCompleteResolve = () => {};
80
+ _getDependencies;
81
+ _isAsync;
82
+ _latestPromise;
83
+ _prevDependencies = null;
84
+ _shouldCompute;
85
+ _shouldRequestUpdate;
86
+
87
+ _updateAsyncValue(dependencies) {
88
+ this._latestPromise = null; // Prevent any ongoing compute update from completing as this is the latest now
89
+
90
+ // If there's still an ongoing compute update, don't replace the computeComplete promise.
91
+ // Instead, this effectively extends the computeComplete promise resolution until the _latestPromise is done.
92
+ if (this.pending === false) {
93
+ this.computeComplete = new Promise((resolve) => {
94
+ this._computeCompleteResolve = resolve;
95
+ });
96
+ }
97
+ this.pending = true;
98
+
99
+ const promise = this._compute(...dependencies);
100
+ this._latestPromise = promise;
101
+
102
+ (async() => {
103
+ let newValue;
104
+ let success;
105
+ let error = null;
106
+
107
+ try {
108
+ newValue = await promise;
109
+ success = true;
110
+ } catch (err) {
111
+ error = err;
112
+ success = false;
113
+ }
114
+
115
+ // Make sure this promise is still the latest so as not to overwrite a more recent async value
116
+ if (this._latestPromise === promise) {
117
+ const prevState = {
118
+ value: this.value,
119
+ success: this.success,
120
+ error: this.error,
121
+ pending: this.pending
122
+ };
123
+
124
+ if (success) {
125
+ this.value = newValue;
126
+ }
127
+
128
+ this.success = success;
129
+ this.error = error;
130
+ this.pending = false;
131
+
132
+ const currState = {
133
+ value: this.value,
134
+ success: this.success,
135
+ error: this.error,
136
+ pending: this.pending
137
+ };
138
+
139
+ if (this._shouldRequestUpdate(prevState, currState)) {
140
+ this.host.requestUpdate();
141
+ }
142
+
143
+ this._computeCompleteResolve();
144
+ }
145
+ })();
146
+ }
147
+
148
+ _updateValue(dependencies) {
149
+ if (this._isAsync) {
150
+ this._updateAsyncValue(dependencies);
151
+ } else {
152
+ this.computeComplete = new Promise((resolve) => {
153
+ this._computeCompleteResolve = resolve;
154
+ });
155
+ this.value = this._compute(...dependencies);
156
+ this._computeCompleteResolve();
157
+ }
158
+ }
159
+ }
@@ -0,0 +1,9 @@
1
+ import ComputedValue from './computed-value.js';
2
+
3
+ export default class ComputedValues {
4
+ constructor(host, valuesOptions = []) {
5
+ valuesOptions.forEach(({ name, ...options }) => {
6
+ this[name] = new ComputedValue(host, options);
7
+ });
8
+ }
9
+ }
package/src/lang/ar.js ADDED
@@ -0,0 +1,4 @@
1
+ /* eslint quotes: 0 */
2
+
3
+ export default {
4
+ };
package/src/lang/cy.js ADDED
@@ -0,0 +1,4 @@
1
+ /* eslint quotes: 0 */
2
+
3
+ export default {
4
+ };
package/src/lang/da.js ADDED
@@ -0,0 +1,4 @@
1
+ /* eslint quotes: 0 */
2
+
3
+ export default {
4
+ };
package/src/lang/de.js ADDED
@@ -0,0 +1,4 @@
1
+ /* eslint quotes: 0 */
2
+
3
+ export default {
4
+ };
package/src/lang/en.js ADDED
@@ -0,0 +1,4 @@
1
+ /* eslint quotes: 0 */
2
+
3
+ export default {
4
+ };
@@ -0,0 +1,4 @@
1
+ /* eslint quotes: 0 */
2
+
3
+ export default {
4
+ };
package/src/lang/es.js ADDED
@@ -0,0 +1,4 @@
1
+ /* eslint quotes: 0 */
2
+
3
+ export default {
4
+ };
@@ -0,0 +1,4 @@
1
+ /* eslint quotes: 0 */
2
+
3
+ export default {
4
+ };
package/src/lang/fr.js ADDED
@@ -0,0 +1,4 @@
1
+ /* eslint quotes: 0 */
2
+
3
+ export default {
4
+ };
package/src/lang/ja.js ADDED
@@ -0,0 +1,4 @@
1
+ /* eslint quotes: 0 */
2
+
3
+ export default {
4
+ };
package/src/lang/ko.js ADDED
@@ -0,0 +1,4 @@
1
+ /* eslint quotes: 0 */
2
+
3
+ export default {
4
+ };
package/src/lang/nl.js ADDED
@@ -0,0 +1,4 @@
1
+ /* eslint quotes: 0 */
2
+
3
+ export default {
4
+ };
package/src/lang/pt.js ADDED
@@ -0,0 +1,4 @@
1
+ /* eslint quotes: 0 */
2
+
3
+ export default {
4
+ };
package/src/lang/sv.js ADDED
@@ -0,0 +1,4 @@
1
+ /* eslint quotes: 0 */
2
+
3
+ export default {
4
+ };
package/src/lang/tr.js ADDED
@@ -0,0 +1,4 @@
1
+ /* eslint quotes: 0 */
2
+
3
+ export default {
4
+ };
@@ -0,0 +1,4 @@
1
+ /* eslint quotes: 0 */
2
+
3
+ export default {
4
+ };
@@ -0,0 +1,4 @@
1
+ /* eslint quotes: 0 */
2
+
3
+ export default {
4
+ };