Initial OSS commit
This commit is contained in:
commit
4a7303f40a
391 changed files with 245738 additions and 0 deletions
3
.editorconfig
Normal file
3
.editorconfig
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
indent_style = space
|
||||||
|
indent_size = 2
|
||||||
|
end_of_line = lf
|
48
.eslintrc.js
Normal file
48
.eslintrc.js
Normal file
|
@ -0,0 +1,48 @@
|
||||||
|
module.exports = {
|
||||||
|
root: true,
|
||||||
|
parser: '@typescript-eslint/parser',
|
||||||
|
plugins: ['@typescript-eslint', 'unused-imports'],
|
||||||
|
parserOptions: {
|
||||||
|
project: ['./packages/**/tsconfig.json', './theatre/**/tsconfig.json'],
|
||||||
|
},
|
||||||
|
extends: [],
|
||||||
|
rules: {
|
||||||
|
'@typescript-eslint/await-thenable': 'warn',
|
||||||
|
'@typescript-eslint/no-throw-literal': 'warn',
|
||||||
|
'@typescript-eslint/switch-exhaustiveness-check': 'error',
|
||||||
|
'@typescript-eslint/consistent-type-imports': [
|
||||||
|
'warn',
|
||||||
|
{
|
||||||
|
prefer: 'type-imports',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
'@typescript-eslint/ban-types': [
|
||||||
|
'error',
|
||||||
|
{
|
||||||
|
extendDefaults: true,
|
||||||
|
types: {
|
||||||
|
any: {
|
||||||
|
message:
|
||||||
|
"Don't use any. Use $FixMe or another alternative listed at defs.d.ts",
|
||||||
|
fixWith: '$FixMe',
|
||||||
|
},
|
||||||
|
'{}': false,
|
||||||
|
object: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
'@typescript-eslint/no-unused-vars': 'off',
|
||||||
|
'unused-imports/no-unused-imports-ts': 'warn',
|
||||||
|
'no-restricted-imports': [
|
||||||
|
'error',
|
||||||
|
{
|
||||||
|
paths: [
|
||||||
|
{
|
||||||
|
name: 'lodash',
|
||||||
|
message: 'Use lodash-es which is tree-shaking friendly',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
19
.gitignore
vendored
Normal file
19
.gitignore
vendored
Normal file
|
@ -0,0 +1,19 @@
|
||||||
|
**/node_modules
|
||||||
|
**/xeno
|
||||||
|
/packages/*/dist
|
||||||
|
/theatre/*/dist
|
||||||
|
*.log
|
||||||
|
*.temp
|
||||||
|
/.vscode
|
||||||
|
/.history
|
||||||
|
**/.DS_Store
|
||||||
|
*.tsbuildinfo
|
||||||
|
.eslintcache
|
||||||
|
|
||||||
|
.yarn/*
|
||||||
|
# !.yarn/cache
|
||||||
|
!.yarn/patches
|
||||||
|
!.yarn/plugins
|
||||||
|
!.yarn/releases
|
||||||
|
!.yarn/sdks
|
||||||
|
!.yarn/versions
|
1
.husky/.gitignore
vendored
Normal file
1
.husky/.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
||||||
|
_
|
4
.husky/pre-commit
Executable file
4
.husky/pre-commit
Executable file
|
@ -0,0 +1,4 @@
|
||||||
|
#!/bin/sh
|
||||||
|
. "$(dirname "$0")/_/husky.sh"
|
||||||
|
|
||||||
|
yarn lint-staged
|
0
.prettierignore
Normal file
0
.prettierignore
Normal file
8
.prettierrc
Normal file
8
.prettierrc
Normal file
|
@ -0,0 +1,8 @@
|
||||||
|
{
|
||||||
|
"printWidth": 80,
|
||||||
|
"semi": false,
|
||||||
|
"singleQuote": true,
|
||||||
|
"trailingComma": "all",
|
||||||
|
"bracketSpacing": false,
|
||||||
|
"proseWrap": "always"
|
||||||
|
}
|
10
.vscode/launch.json
vendored
Normal file
10
.vscode/launch.json
vendored
Normal file
|
@ -0,0 +1,10 @@
|
||||||
|
{
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"type": "pwa-chrome",
|
||||||
|
"name": "Browser",
|
||||||
|
"request": "launch",
|
||||||
|
"url": "https://dev.theatre.local:10022/"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
24
.vscode/settings.json
vendored
Normal file
24
.vscode/settings.json
vendored
Normal file
|
@ -0,0 +1,24 @@
|
||||||
|
{
|
||||||
|
"typescript.tsdk": "node_modules/typescript/lib",
|
||||||
|
"files.exclude": {
|
||||||
|
"**/node_modules": true,
|
||||||
|
// "**/.yarn": true,
|
||||||
|
"**/.cache": true,
|
||||||
|
"**/.temp": true,
|
||||||
|
"**/.history": true
|
||||||
|
},
|
||||||
|
"search.exclude": {
|
||||||
|
"**/node_modules": true,
|
||||||
|
"**/bower_components": true,
|
||||||
|
"**/*.code-search": true,
|
||||||
|
"**/dist": true
|
||||||
|
},
|
||||||
|
"eslint.workingDirectories": ["./"],
|
||||||
|
"eslint.options": {
|
||||||
|
"rulePaths": ["./devEnv/eslint/rules"],
|
||||||
|
"ignorePath": ".gitignore"
|
||||||
|
},
|
||||||
|
"eslint.run": "onSave",
|
||||||
|
"eslint.lintTask.enable": true,
|
||||||
|
"eslint.lintTask.options": ". --ext ts,tsx --ignore-path=.gitignore --rulesdir ./devEnv/eslint/rules"
|
||||||
|
}
|
20
.vscode/tasks.json
vendored
Normal file
20
.vscode/tasks.json
vendored
Normal file
|
@ -0,0 +1,20 @@
|
||||||
|
{
|
||||||
|
// See https://go.microsoft.com/fwlink/?LinkId=733558
|
||||||
|
// for the documentation about the tasks.json format
|
||||||
|
"version": "2.0.0",
|
||||||
|
"tasks": [
|
||||||
|
{
|
||||||
|
"type": "npm",
|
||||||
|
"script": "test -- --watch",
|
||||||
|
"group": "test",
|
||||||
|
"problemMatcher": [],
|
||||||
|
"label": "npm: test"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "TypeScript watch",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "yarn tsc --build --watch ./devEnv/typecheck-all-projects/tsconfig.all.json",
|
||||||
|
"problemMatcher": ["$tsc-watch"]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
7
.yarn/plugins/@yarnpkg/plugin-compat.cjs
vendored
Normal file
7
.yarn/plugins/@yarnpkg/plugin-compat.cjs
vendored
Normal file
|
@ -0,0 +1,7 @@
|
||||||
|
module.exports = {
|
||||||
|
name: `@yarnpkg/plugin-compat`,
|
||||||
|
factory: (require) => {
|
||||||
|
// dummy implementation to override the built-in version of this plugin
|
||||||
|
return {}
|
||||||
|
},
|
||||||
|
}
|
77
.yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs
vendored
Normal file
77
.yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs
vendored
Normal file
File diff suppressed because one or more lines are too long
55
.yarn/releases/yarn-2.4.1.cjs
vendored
Executable file
55
.yarn/releases/yarn-2.4.1.cjs
vendored
Executable file
File diff suppressed because one or more lines are too long
9
.yarnrc.yml
Normal file
9
.yarnrc.yml
Normal file
|
@ -0,0 +1,9 @@
|
||||||
|
nodeLinker: node-modules
|
||||||
|
|
||||||
|
plugins:
|
||||||
|
- path: .yarn/plugins/@yarnpkg/plugin-compat.cjs
|
||||||
|
spec: "@yarnpkg/plugin-compat"
|
||||||
|
- path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs
|
||||||
|
spec: "@yarnpkg/plugin-interactive-tools"
|
||||||
|
|
||||||
|
yarnPath: .yarn/releases/yarn-2.4.1.cjs
|
202
LICENSE
Normal file
202
LICENSE
Normal file
|
@ -0,0 +1,202 @@
|
||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
|
|
661
LICENSE-AGPL-3.0
Normal file
661
LICENSE-AGPL-3.0
Normal file
|
@ -0,0 +1,661 @@
|
||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
Developers that use our General Public Licenses protect your rights
|
||||||
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
|
||||||
|
A secondary benefit of defending all users' freedom is that
|
||||||
|
improvements made in alternate versions of the program, if they
|
||||||
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
|
||||||
|
The GNU Affero General Public License is designed specifically to
|
||||||
|
ensure that, in such cases, the modified source code becomes available
|
||||||
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
|
||||||
|
An older license, called the Affero General Public License and
|
||||||
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero General Public License from time to time. Such new versions
|
||||||
|
will be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU Affero General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU Affero General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU Affero General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as published
|
||||||
|
by the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
20
README.md
Normal file
20
README.md
Normal file
|
@ -0,0 +1,20 @@
|
||||||
|
# Theatre.js
|
||||||
|
|
||||||
|
Theatre.js is an animation library for high-fidelity motion graphics. It is designed to help you express detailed animation, enabling you to create intricate movement, and convey nuance.
|
||||||
|
|
||||||
|
Theatre can be used both programmatically _and_ visually:
|
||||||
|
|
||||||
|
![Video showing a browser window containing three divs falling from the middle of the screen, and bouncing back up, animated with the help of Theatre.js](https://docs.theatrejs.com/public/preview-1.gif)
|
||||||
|
|
||||||
|
Theatre works with all rendering stacks. You can use it to animate DOM elements, THREE.js objects, or any kind of JavaScript variable.
|
||||||
|
|
||||||
|
## Guide
|
||||||
|
|
||||||
|
TODO
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Your use of Theatre.js is governed under the Apache License Version 2.0:
|
||||||
|
|
||||||
|
* Theatre's core (`@theatre/core`) is released under the Apache License. Same goes for most packages in this repository.
|
||||||
|
* The studio (`@theatre/studio`) is released under the AGPL 3.0 License. This is the package that you use to edit your animations, setup your scenes, etc. You only use the studio during design/development. Your project's final bundle only includes `@theatre/core`, so only the Apache License applies.
|
24
babel.config.js
Normal file
24
babel.config.js
Normal file
|
@ -0,0 +1,24 @@
|
||||||
|
module.exports = function (api) {
|
||||||
|
const env = api.env()
|
||||||
|
|
||||||
|
const config = {
|
||||||
|
presets: [['@babel/preset-react'], ['@babel/preset-typescript']],
|
||||||
|
babelrcRoots: ['.', './packages/*', './theatre/*'],
|
||||||
|
}
|
||||||
|
if (env === 'test') {
|
||||||
|
config.presets.unshift(['@babel/preset-env', {targets: {node: 'current'}}])
|
||||||
|
} else {
|
||||||
|
if (env === 'development' || env === 'production') {
|
||||||
|
config.plugins.unshift(
|
||||||
|
['@babel/plugin-proposal-class-properties', {loose: true}],
|
||||||
|
['@babel/plugin-proposal-optional-chaining'],
|
||||||
|
['@babel/plugin-proposal-nullish-coalescing-operator'],
|
||||||
|
['@babel/plugin-proposal-logical-assignment-operators'],
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
throw Error(`Babel env ` + env + ' is not yet configured.')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return config
|
||||||
|
}
|
131
devEnv/eslint/rules/no-relative-imports.js
Normal file
131
devEnv/eslint/rules/no-relative-imports.js
Normal file
|
@ -0,0 +1,131 @@
|
||||||
|
const path = require('path')
|
||||||
|
const minimatch = require('minimatch')
|
||||||
|
|
||||||
|
// @todo find and acknowledge the original source of this (it was a github gist)
|
||||||
|
// @todo this rule is clearly ignoring a bunch of files that do have parent
|
||||||
|
// relative paths but don't get caught.
|
||||||
|
|
||||||
|
const replace = {
|
||||||
|
meta: {
|
||||||
|
type: 'layout',
|
||||||
|
fixable: 'code',
|
||||||
|
schema: [
|
||||||
|
{
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
ignore: {
|
||||||
|
type: 'array',
|
||||||
|
items: {
|
||||||
|
type: 'string',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
method: {
|
||||||
|
type: 'string',
|
||||||
|
enum: ['all', 'only-parent'],
|
||||||
|
},
|
||||||
|
aliases: {
|
||||||
|
type: 'array',
|
||||||
|
minItems: 1,
|
||||||
|
items: {
|
||||||
|
properties: {
|
||||||
|
name: {
|
||||||
|
type: 'string',
|
||||||
|
},
|
||||||
|
path: {
|
||||||
|
type: 'string',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
required: ['name', 'path'],
|
||||||
|
additionalProperties: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
required: ['aliases'],
|
||||||
|
additionalProperties: false,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
messages: {
|
||||||
|
'can-replace':
|
||||||
|
'Relative import found. Run autofix to replace these relative imports!',
|
||||||
|
'cannot-replace':
|
||||||
|
'Relative import found. No alias has been defined which matches this import path',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
create: (context) => {
|
||||||
|
return {
|
||||||
|
ImportDeclaration: (node) => {
|
||||||
|
const config = getConfiguration(context)
|
||||||
|
|
||||||
|
if (
|
||||||
|
config.ignorePatterns.some((pattern) =>
|
||||||
|
minimatch(context.getFilename(), pattern),
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
evaluateImport(node, config, context)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
function evaluateImport(node, config, context) {
|
||||||
|
const {
|
||||||
|
source: {value, range, loc},
|
||||||
|
} = node
|
||||||
|
if (value.startsWith('./') && config.replaceMethod === 'only-parent') {
|
||||||
|
return
|
||||||
|
} else if (!value.startsWith('../')) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
let canFix = false
|
||||||
|
const currentFileDirectory = path.dirname(context.getFilename())
|
||||||
|
for (const alias of config.replaceAliases) {
|
||||||
|
const {replaceDir, replaceWith} = alias
|
||||||
|
const fullImportPath = path.resolve(currentFileDirectory, value)
|
||||||
|
|
||||||
|
if (fullImportPath.startsWith(replaceDir)) {
|
||||||
|
canFix = true
|
||||||
|
|
||||||
|
context.report({
|
||||||
|
messageId: 'can-replace',
|
||||||
|
loc,
|
||||||
|
fix: (fixer) =>
|
||||||
|
fixer.replaceTextRange(
|
||||||
|
range,
|
||||||
|
`'${fullImportPath.replace(replaceDir, replaceWith)}'`,
|
||||||
|
),
|
||||||
|
})
|
||||||
|
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!canFix) {
|
||||||
|
context.report({
|
||||||
|
messageId: 'cannot-replace',
|
||||||
|
loc,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getConfiguration(context) {
|
||||||
|
const options = {
|
||||||
|
ignore: [],
|
||||||
|
method: 'only-parent',
|
||||||
|
...context.options[0],
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
ignorePatterns: options.ignore,
|
||||||
|
replaceMethod: options.method,
|
||||||
|
replaceAliases: options.aliases.map((alias) => ({
|
||||||
|
replaceDir: alias.path,
|
||||||
|
replaceWith: alias.name,
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = replace
|
2
devEnv/getAliasesFromTSConfig.d.ts
vendored
Normal file
2
devEnv/getAliasesFromTSConfig.d.ts
vendored
Normal file
|
@ -0,0 +1,2 @@
|
||||||
|
export function getAliasesFromTsConfigForWebpack(): Record<string, string>
|
||||||
|
export function getAliasesFromTsConfigForJest(): Record<string, string>
|
58
devEnv/getAliasesFromTSConfig.js
Normal file
58
devEnv/getAliasesFromTSConfig.js
Normal file
|
@ -0,0 +1,58 @@
|
||||||
|
const path = require('path')
|
||||||
|
|
||||||
|
const monorepoRoot = path.resolve(__dirname, '../')
|
||||||
|
|
||||||
|
function getAliasesFromTsConfigForWebpack() {
|
||||||
|
const tsConfigPaths = require('../tsconfig.base.json').compilerOptions.paths
|
||||||
|
|
||||||
|
const aliases = {}
|
||||||
|
|
||||||
|
for (let [key, value] of Object.entries(tsConfigPaths)) {
|
||||||
|
if (key.match(/\*$/)) {
|
||||||
|
key = key.replace(/\/\*$/, '')
|
||||||
|
} else {
|
||||||
|
key = key + '$'
|
||||||
|
}
|
||||||
|
aliases[key] = path.join(monorepoRoot, value[0].replace(/\/\*$/, ''))
|
||||||
|
}
|
||||||
|
|
||||||
|
return aliases
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports.getAliasesFromTsConfigForWebpack = getAliasesFromTsConfigForWebpack
|
||||||
|
|
||||||
|
function getAliasesFromTsConfigForESLint() {
|
||||||
|
const tsConfigPaths = require('../tsconfig.base.json').compilerOptions.paths
|
||||||
|
|
||||||
|
const aliases = []
|
||||||
|
|
||||||
|
for (const [key, value] of Object.entries(tsConfigPaths)) {
|
||||||
|
aliases.push({
|
||||||
|
name: key.replace(/\/\*$/, ''),
|
||||||
|
path: value[0].replace(/\/\*$/, ''),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return aliases
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports.getAliasesFromTsConfigForESLint = getAliasesFromTsConfigForESLint
|
||||||
|
|
||||||
|
function getAliasesFromTsConfigForJest() {
|
||||||
|
const tsConfigPaths = require('../tsconfig.base.json').compilerOptions.paths
|
||||||
|
|
||||||
|
const aliases = {}
|
||||||
|
|
||||||
|
for (let [key, value] of Object.entries(tsConfigPaths)) {
|
||||||
|
if (key.match(/\/\*$/)) {
|
||||||
|
key = key.replace(/\/\*$/, '/(.*)')
|
||||||
|
} else {
|
||||||
|
key = key + '$'
|
||||||
|
}
|
||||||
|
aliases[key] = path.join('<rootDir>', value[0].replace(/\/\*$/, '/$1'))
|
||||||
|
}
|
||||||
|
|
||||||
|
return aliases
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports.getAliasesFromTsConfigForJest = getAliasesFromTsConfigForJest
|
14
devEnv/typecheck-all-projects/tsconfig.all.json
Normal file
14
devEnv/typecheck-all-projects/tsconfig.all.json
Normal file
|
@ -0,0 +1,14 @@
|
||||||
|
{
|
||||||
|
"extends": "../../tsconfig.base.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"composite": true,
|
||||||
|
"rootDir": "../.."
|
||||||
|
},
|
||||||
|
"files": [],
|
||||||
|
"references": [
|
||||||
|
{"path": "../../theatre"},
|
||||||
|
{"path": "../../packages/dataverse"},
|
||||||
|
{"path": "../../packages/playground"},
|
||||||
|
{"path": "../../packages/plugin-r3f"}
|
||||||
|
]
|
||||||
|
}
|
20
jest.config.js
Normal file
20
jest.config.js
Normal file
|
@ -0,0 +1,20 @@
|
||||||
|
module.exports = {
|
||||||
|
testMatch: [
|
||||||
|
'<rootDir>/packages/*/src/**/*.test.ts',
|
||||||
|
'<rootDir>/theatre/*/src/**/*.test.ts',
|
||||||
|
],
|
||||||
|
moduleNameMapper: {
|
||||||
|
...require('./devEnv/getAliasesFromTSConfig').getAliasesFromTsConfigForJest(),
|
||||||
|
'\\.(css)$': 'identity-obj-proxy',
|
||||||
|
'lodash-es/(.*)': 'lodash/$1',
|
||||||
|
'react-use/esm/(.*)': 'react-use/lib/$1',
|
||||||
|
'lodash-es': 'lodash',
|
||||||
|
},
|
||||||
|
setupFiles: ['./theatre/shared/src/setupTestEnv.ts'],
|
||||||
|
automock: false,
|
||||||
|
transform: {
|
||||||
|
'^.+\\.tsx?$': 'esbuild-jest',
|
||||||
|
'^.+\\.js$': 'esbuild-jest',
|
||||||
|
},
|
||||||
|
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
|
||||||
|
}
|
6
lerna.json
Normal file
6
lerna.json
Normal file
|
@ -0,0 +1,6 @@
|
||||||
|
{
|
||||||
|
"packages": ["packages/*", "theatre/*"],
|
||||||
|
"version": "independent",
|
||||||
|
"npmClient": "yarn",
|
||||||
|
"useWorkspaces": true
|
||||||
|
}
|
46
package.json
Normal file
46
package.json
Normal file
|
@ -0,0 +1,46 @@
|
||||||
|
{
|
||||||
|
"name": "theatre-monorepo",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"workspaces": [
|
||||||
|
"packages/*",
|
||||||
|
"theatre"
|
||||||
|
],
|
||||||
|
"scripts": {
|
||||||
|
"typecheck": "tsc --build ./devEnv/typecheck-all-projects/tsconfig.all.json",
|
||||||
|
"test": "jest",
|
||||||
|
"postinstall": "husky install",
|
||||||
|
"lint:all": "eslint . --ext ts,tsx --ignore-path=.gitignore --rulesdir ./devEnv/eslint/rules"
|
||||||
|
},
|
||||||
|
"lint-staged": {
|
||||||
|
"**/*.(t|j)s?(x)": [
|
||||||
|
"eslint --rulesdir ./devEnv/eslint/rules --fix",
|
||||||
|
"prettier --write"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@babel/core": "^7.14.3",
|
||||||
|
"@babel/plugin-proposal-class-properties": "^7.13.0",
|
||||||
|
"@babel/plugin-proposal-nullish-coalescing-operator": "^7.14.2",
|
||||||
|
"@babel/plugin-proposal-optional-chaining": "^7.14.2",
|
||||||
|
"@babel/preset-env": "^7.14.4",
|
||||||
|
"@babel/preset-react": "^7.13.13",
|
||||||
|
"@babel/preset-typescript": "^7.13.0",
|
||||||
|
"@typescript-eslint/eslint-plugin": "^4.26.0",
|
||||||
|
"@typescript-eslint/parser": "^4.26.0",
|
||||||
|
"esbuild": "^0.12.5",
|
||||||
|
"esbuild-jest": "^0.5.0",
|
||||||
|
"eslint": "^7.27.0",
|
||||||
|
"eslint-plugin-jsx-a11y": "^6.4.1",
|
||||||
|
"eslint-plugin-react-hooks": "^4.2.0",
|
||||||
|
"eslint-plugin-unused-imports": "^1.1.1",
|
||||||
|
"husky": "^6.0.0",
|
||||||
|
"jest": "^27.0.3",
|
||||||
|
"lerna": "^4.0.0",
|
||||||
|
"lint-staged": "^11.0.0",
|
||||||
|
"prettier": "^2.3.1",
|
||||||
|
"typescript": "^4.3.2"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"node-gyp": "^8.1.0"
|
||||||
|
}
|
||||||
|
}
|
1
packages/dataverse/.babelrc.js
Normal file
1
packages/dataverse/.babelrc.js
Normal file
|
@ -0,0 +1 @@
|
||||||
|
module.exports = {}
|
1
packages/dataverse/.gitignore
vendored
Normal file
1
packages/dataverse/.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
||||||
|
/dist
|
203
packages/dataverse/LICENSE
Normal file
203
packages/dataverse/LICENSE
Normal file
|
@ -0,0 +1,203 @@
|
||||||
|
|
||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
|
|
31
packages/dataverse/package.json
Normal file
31
packages/dataverse/package.json
Normal file
|
@ -0,0 +1,31 @@
|
||||||
|
{
|
||||||
|
"name": "@theatre/dataverse",
|
||||||
|
"version": "1.0.0-dev",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"author": {
|
||||||
|
"name": "Aria Minaei",
|
||||||
|
"email": "aria@theatrejs.com",
|
||||||
|
"url": "https://github.com/AriaMinaei"
|
||||||
|
},
|
||||||
|
"source": "src/index.ts",
|
||||||
|
"main": "dist/index.js",
|
||||||
|
"types": "dist/index.d.ts",
|
||||||
|
"files": [
|
||||||
|
"dist/**/*"
|
||||||
|
],
|
||||||
|
"scripts": {
|
||||||
|
"prepack": "yarn run build",
|
||||||
|
"typecheck": "yarn run build",
|
||||||
|
"build": "tsc --build ./tsconfig.json"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/jest": "^26.0.23",
|
||||||
|
"@types/lodash-es": "^4.17.4",
|
||||||
|
"@types/node": "^15.6.2",
|
||||||
|
"@types/react": "^17.0.9",
|
||||||
|
"typescript": "^4.3.2"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"lodash-es": "^4.17.21"
|
||||||
|
}
|
||||||
|
}
|
241
packages/dataverse/src/Atom.ts
Normal file
241
packages/dataverse/src/Atom.ts
Normal file
|
@ -0,0 +1,241 @@
|
||||||
|
import get from 'lodash-es/get'
|
||||||
|
import isPlainObject from 'lodash-es/isPlainObject'
|
||||||
|
import last from 'lodash-es/last'
|
||||||
|
import DerivationFromSource from './derivations/DerivationFromSource'
|
||||||
|
import type {IDerivation} from './derivations/IDerivation'
|
||||||
|
import {isDerivation} from './derivations/IDerivation'
|
||||||
|
import type {Pointer, PointerType} from './pointer'
|
||||||
|
import pointer, {getPointerMeta} from './pointer'
|
||||||
|
import type {$FixMe, $IntentionalAny} from './types'
|
||||||
|
import type {PathBasedReducer} from './utils/PathBasedReducer'
|
||||||
|
import updateDeep from './utils/updateDeep'
|
||||||
|
|
||||||
|
type Listener = (newVal: unknown) => void
|
||||||
|
|
||||||
|
enum ValueTypes {
|
||||||
|
Dict,
|
||||||
|
Array,
|
||||||
|
Other,
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IdentityDerivationProvider {
|
||||||
|
readonly $$isIdentityDerivationProvider: true
|
||||||
|
getIdentityDerivation(path: Array<string | number>): IDerivation<unknown>
|
||||||
|
}
|
||||||
|
|
||||||
|
const getTypeOfValue = (v: unknown): ValueTypes => {
|
||||||
|
if (Array.isArray(v)) return ValueTypes.Array
|
||||||
|
if (isPlainObject(v)) return ValueTypes.Dict
|
||||||
|
return ValueTypes.Other
|
||||||
|
}
|
||||||
|
|
||||||
|
const getKeyOfValue = (
|
||||||
|
v: unknown,
|
||||||
|
key: string | number,
|
||||||
|
vType: ValueTypes = getTypeOfValue(v),
|
||||||
|
): unknown => {
|
||||||
|
if (vType === ValueTypes.Dict && typeof key === 'string') {
|
||||||
|
return (v as $IntentionalAny)[key]
|
||||||
|
} else if (vType === ValueTypes.Array && isValidArrayIndex(key)) {
|
||||||
|
return (v as $IntentionalAny)[key]
|
||||||
|
} else {
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const isValidArrayIndex = (key: string | number): boolean => {
|
||||||
|
const inNumber = typeof key === 'number' ? key : parseInt(key, 10)
|
||||||
|
return (
|
||||||
|
!isNaN(inNumber) &&
|
||||||
|
inNumber >= 0 &&
|
||||||
|
inNumber < Infinity &&
|
||||||
|
(inNumber | 0) === inNumber
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
class Scope {
|
||||||
|
children: Map<string | number, Scope> = new Map()
|
||||||
|
identityChangeListeners: Set<Listener> = new Set()
|
||||||
|
constructor(
|
||||||
|
readonly _parent: undefined | Scope,
|
||||||
|
readonly _path: (string | number)[],
|
||||||
|
) {}
|
||||||
|
|
||||||
|
addIdentityChangeListener(cb: Listener) {
|
||||||
|
this.identityChangeListeners.add(cb)
|
||||||
|
}
|
||||||
|
|
||||||
|
removeIdentityChangeListener(cb: Listener) {
|
||||||
|
this.identityChangeListeners.delete(cb)
|
||||||
|
this._checkForGC()
|
||||||
|
}
|
||||||
|
|
||||||
|
removeChild(key: string | number) {
|
||||||
|
this.children.delete(key)
|
||||||
|
this._checkForGC()
|
||||||
|
}
|
||||||
|
|
||||||
|
getChild(key: string | number) {
|
||||||
|
return this.children.get(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
getOrCreateChild(key: string | number) {
|
||||||
|
let child = this.children.get(key)
|
||||||
|
if (!child) {
|
||||||
|
child = child = new Scope(this, this._path.concat([key]))
|
||||||
|
this.children.set(key, child)
|
||||||
|
}
|
||||||
|
return child
|
||||||
|
}
|
||||||
|
|
||||||
|
_checkForGC() {
|
||||||
|
if (this.identityChangeListeners.size > 0) return
|
||||||
|
if (this.children.size > 0) return
|
||||||
|
|
||||||
|
if (this._parent) {
|
||||||
|
this._parent.removeChild(last(this._path) as string | number)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default class Atom<State extends {}>
|
||||||
|
implements IdentityDerivationProvider
|
||||||
|
{
|
||||||
|
private _currentState: State
|
||||||
|
readonly $$isIdentityDerivationProvider = true
|
||||||
|
private readonly _rootScope: Scope
|
||||||
|
readonly pointer: Pointer<State>
|
||||||
|
|
||||||
|
constructor(initialState: State) {
|
||||||
|
this._currentState = initialState
|
||||||
|
this._rootScope = new Scope(undefined, [])
|
||||||
|
this.pointer = pointer({root: this as $FixMe, path: []})
|
||||||
|
}
|
||||||
|
|
||||||
|
setState(newState: State) {
|
||||||
|
const oldState = this._currentState
|
||||||
|
this._currentState = newState
|
||||||
|
|
||||||
|
this._checkUpdates(this._rootScope, oldState, newState)
|
||||||
|
}
|
||||||
|
|
||||||
|
getState() {
|
||||||
|
return this._currentState
|
||||||
|
}
|
||||||
|
|
||||||
|
getIn(path: (string | number)[]): unknown {
|
||||||
|
return path.length === 0 ? this.getState() : get(this.getState(), path)
|
||||||
|
}
|
||||||
|
|
||||||
|
reduceState: PathBasedReducer<State, State> = (
|
||||||
|
path: $IntentionalAny[],
|
||||||
|
reducer: $IntentionalAny,
|
||||||
|
) => {
|
||||||
|
const newState = updateDeep(this.getState(), path, reducer)
|
||||||
|
this.setState(newState)
|
||||||
|
return newState
|
||||||
|
}
|
||||||
|
|
||||||
|
setIn(path: $FixMe[], val: $FixMe) {
|
||||||
|
return this.reduceState(path, () => val)
|
||||||
|
}
|
||||||
|
|
||||||
|
private _checkUpdates(scope: Scope, oldState: unknown, newState: unknown) {
|
||||||
|
if (oldState === newState) return
|
||||||
|
scope.identityChangeListeners.forEach((cb) => cb(newState))
|
||||||
|
|
||||||
|
if (scope.children.size === 0) return
|
||||||
|
const oldValueType = getTypeOfValue(oldState)
|
||||||
|
const newValueType = getTypeOfValue(newState)
|
||||||
|
|
||||||
|
if (oldValueType === ValueTypes.Other && oldValueType === newValueType)
|
||||||
|
return
|
||||||
|
|
||||||
|
scope.children.forEach((childScope, childKey) => {
|
||||||
|
const oldChildVal = getKeyOfValue(oldState, childKey, oldValueType)
|
||||||
|
const newChildVal = getKeyOfValue(newState, childKey, newValueType)
|
||||||
|
this._checkUpdates(childScope, oldChildVal, newChildVal)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
private _getOrCreateScopeForPath(path: (string | number)[]): Scope {
|
||||||
|
let curScope = this._rootScope
|
||||||
|
for (const pathEl of path) {
|
||||||
|
curScope = curScope.getOrCreateChild(pathEl)
|
||||||
|
}
|
||||||
|
return curScope
|
||||||
|
}
|
||||||
|
|
||||||
|
private _onPathValueChange = (
|
||||||
|
path: (string | number)[],
|
||||||
|
cb: (v: unknown) => void,
|
||||||
|
) => {
|
||||||
|
const scope = this._getOrCreateScopeForPath(path)
|
||||||
|
scope.identityChangeListeners.add(cb)
|
||||||
|
const untap = () => {
|
||||||
|
scope.identityChangeListeners.delete(cb)
|
||||||
|
}
|
||||||
|
return untap
|
||||||
|
}
|
||||||
|
|
||||||
|
getIdentityDerivation(path: Array<string | number>): IDerivation<unknown> {
|
||||||
|
return new DerivationFromSource<$IntentionalAny>(
|
||||||
|
(listener) => this._onPathValueChange(path, listener),
|
||||||
|
() => this.getIn(path),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const identityDerivationWeakMap = new WeakMap<{}, IDerivation<unknown>>()
|
||||||
|
|
||||||
|
export const valueDerivation = <P extends PointerType<$IntentionalAny>>(
|
||||||
|
pointer: P,
|
||||||
|
): IDerivation<P extends PointerType<infer T> ? T : void> => {
|
||||||
|
const meta = getPointerMeta(pointer)
|
||||||
|
|
||||||
|
let derivation = identityDerivationWeakMap.get(meta)
|
||||||
|
if (!derivation) {
|
||||||
|
const root = meta.root
|
||||||
|
if (!isIdentityChangeProvider(root)) {
|
||||||
|
throw new Error(
|
||||||
|
`Cannot run valueDerivation() on a pointer whose root is not an IdentityChangeProvider`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
const {path} = meta
|
||||||
|
derivation = root.getIdentityDerivation(path)
|
||||||
|
identityDerivationWeakMap.set(meta, derivation)
|
||||||
|
}
|
||||||
|
return derivation as $IntentionalAny
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isIdentityChangeProvider(
|
||||||
|
val: unknown,
|
||||||
|
): val is IdentityDerivationProvider {
|
||||||
|
return (
|
||||||
|
typeof val === 'object' &&
|
||||||
|
val !== null &&
|
||||||
|
(val as $IntentionalAny)['$$isIdentityDerivationProvider'] === true
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const val = <P>(
|
||||||
|
pointerOrDerivationOrPlainValue: P,
|
||||||
|
): P extends PointerType<infer T>
|
||||||
|
? T
|
||||||
|
: P extends IDerivation<infer T>
|
||||||
|
? T
|
||||||
|
: unknown => {
|
||||||
|
if (isPointer(pointerOrDerivationOrPlainValue)) {
|
||||||
|
return valueDerivation(
|
||||||
|
pointerOrDerivationOrPlainValue,
|
||||||
|
).getValue() as $IntentionalAny
|
||||||
|
} else if (isDerivation(pointerOrDerivationOrPlainValue)) {
|
||||||
|
return pointerOrDerivationOrPlainValue.getValue() as $IntentionalAny
|
||||||
|
} else {
|
||||||
|
return pointerOrDerivationOrPlainValue as $IntentionalAny
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const isPointer = (p: $IntentionalAny): p is Pointer<unknown> => {
|
||||||
|
return p && p.$pointerMeta ? true : false
|
||||||
|
}
|
34
packages/dataverse/src/Box.ts
Normal file
34
packages/dataverse/src/Box.ts
Normal file
|
@ -0,0 +1,34 @@
|
||||||
|
import DerivationFromSource from './derivations/DerivationFromSource'
|
||||||
|
import type {IDerivation} from './derivations/IDerivation'
|
||||||
|
import Emitter from './utils/Emitter'
|
||||||
|
export interface IBox<V> {
|
||||||
|
set(v: V): void
|
||||||
|
get(): V
|
||||||
|
derivation: IDerivation<V>
|
||||||
|
}
|
||||||
|
|
||||||
|
export default class Box<V> implements IBox<V> {
|
||||||
|
private _publicDerivation: IDerivation<V>
|
||||||
|
private _emitter = new Emitter<V>()
|
||||||
|
|
||||||
|
constructor(protected _value: V) {
|
||||||
|
this._publicDerivation = new DerivationFromSource(
|
||||||
|
(listener) => this._emitter.tappable.tap(listener),
|
||||||
|
this.get.bind(this),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
set(v: V) {
|
||||||
|
if (v === this._value) return
|
||||||
|
this._value = v
|
||||||
|
this._emitter.emit(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
get() {
|
||||||
|
return this._value
|
||||||
|
}
|
||||||
|
|
||||||
|
get derivation() {
|
||||||
|
return this._publicDerivation
|
||||||
|
}
|
||||||
|
}
|
84
packages/dataverse/src/Freshener.ts
Normal file
84
packages/dataverse/src/Freshener.ts
Normal file
|
@ -0,0 +1,84 @@
|
||||||
|
type ICallback = (t: number) => void
|
||||||
|
|
||||||
|
export default class Freshener {
|
||||||
|
private _scheduledForThisOrNextTick: Set<ICallback>
|
||||||
|
private _scheduledForNextTick: Set<ICallback>
|
||||||
|
private _timeAtCurrentTick: number
|
||||||
|
private _freshening: boolean = false
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this._scheduledForThisOrNextTick = new Set()
|
||||||
|
this._scheduledForNextTick = new Set()
|
||||||
|
this._timeAtCurrentTick = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers for fn to be called either on this freshen or the next freshen.
|
||||||
|
*
|
||||||
|
* If registerSideEffect() is called while Freshener.freshen() is running, the
|
||||||
|
* side effect _will_ be called within the running freshen. If you don't want this
|
||||||
|
* behavior, you can use registerSideEffectForNextTick().
|
||||||
|
*
|
||||||
|
* Note that fn will be added to a Set(). Which means, if you call registerSideEffect(fn)
|
||||||
|
* with the same fn twice in a single freshen, it'll only run once.
|
||||||
|
*/
|
||||||
|
onThisOrNextTick(fn: ICallback) {
|
||||||
|
this._scheduledForThisOrNextTick.add(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers a side effect to be called on the next freshen.
|
||||||
|
*
|
||||||
|
* @see Freshener:onThisOrNextTick()
|
||||||
|
*/
|
||||||
|
onNextTick(fn: ICallback) {
|
||||||
|
this._scheduledForNextTick.add(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
offThisOrNextTick(fn: ICallback) {
|
||||||
|
this._scheduledForThisOrNextTick.delete(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
offNextTick(fn: ICallback) {
|
||||||
|
this._scheduledForNextTick.delete(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
get time() {
|
||||||
|
if (this._freshening) {
|
||||||
|
return this._timeAtCurrentTick
|
||||||
|
} else return performance.now()
|
||||||
|
}
|
||||||
|
|
||||||
|
freshen(t: number = performance.now()) {
|
||||||
|
this._freshening = true
|
||||||
|
this._timeAtCurrentTick = t
|
||||||
|
this._scheduledForNextTick.forEach((v) =>
|
||||||
|
this._scheduledForThisOrNextTick.add(v),
|
||||||
|
)
|
||||||
|
this._scheduledForNextTick.clear()
|
||||||
|
this._freshen(0)
|
||||||
|
this._freshening = false
|
||||||
|
}
|
||||||
|
|
||||||
|
private _freshen(iterationNumber: number): void {
|
||||||
|
const time = this.time
|
||||||
|
|
||||||
|
if (iterationNumber > 10) {
|
||||||
|
console.warn('_freshen() recursing for 10 times')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (iterationNumber > 100) {
|
||||||
|
throw new Error(`Maximum recursion limit for _tick()`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const oldSet = this._scheduledForThisOrNextTick
|
||||||
|
this._scheduledForThisOrNextTick = new Set()
|
||||||
|
oldSet.forEach((fn) => {
|
||||||
|
fn(time)
|
||||||
|
})
|
||||||
|
|
||||||
|
if (this._scheduledForThisOrNextTick.size > 0) {
|
||||||
|
return this._freshen(iterationNumber + 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
34
packages/dataverse/src/PointerProxy.ts
Normal file
34
packages/dataverse/src/PointerProxy.ts
Normal file
|
@ -0,0 +1,34 @@
|
||||||
|
import type {IdentityDerivationProvider} from './Atom'
|
||||||
|
import type {Pointer} from './pointer';
|
||||||
|
import pointer from './pointer'
|
||||||
|
import type {IBox} from './Box';
|
||||||
|
import Box from './Box'
|
||||||
|
import type {$FixMe, $IntentionalAny} from './types'
|
||||||
|
import {valueDerivation} from '@theatre/dataverse'
|
||||||
|
|
||||||
|
export default class PointerProxy<O extends {}>
|
||||||
|
implements IdentityDerivationProvider
|
||||||
|
{
|
||||||
|
readonly $$isIdentityDerivationProvider = true
|
||||||
|
private readonly _currentPointerBox: IBox<Pointer<O>>
|
||||||
|
readonly pointer: Pointer<O>
|
||||||
|
|
||||||
|
constructor(currentPointer: Pointer<O>) {
|
||||||
|
this._currentPointerBox = new Box(currentPointer)
|
||||||
|
this.pointer = pointer({root: this as $FixMe, path: []})
|
||||||
|
}
|
||||||
|
|
||||||
|
setPointer(p: Pointer<O>) {
|
||||||
|
this._currentPointerBox.set(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
getIdentityDerivation(path: Array<string | number>) {
|
||||||
|
return this._currentPointerBox.derivation.flatMap((p) => {
|
||||||
|
const subPointer = path.reduce(
|
||||||
|
(pointerSoFar, pathItem) => (pointerSoFar as $IntentionalAny)[pathItem],
|
||||||
|
p,
|
||||||
|
)
|
||||||
|
return valueDerivation(subPointer)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
84
packages/dataverse/src/Ticker.ts
Normal file
84
packages/dataverse/src/Ticker.ts
Normal file
|
@ -0,0 +1,84 @@
|
||||||
|
type ICallback = (t: number) => void
|
||||||
|
|
||||||
|
export default class Ticker {
|
||||||
|
private _scheduledForThisOrNextTick: Set<ICallback>
|
||||||
|
private _scheduledForNextTick: Set<ICallback>
|
||||||
|
private _timeAtCurrentTick: number
|
||||||
|
private _ticking: boolean = false
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this._scheduledForThisOrNextTick = new Set()
|
||||||
|
this._scheduledForNextTick = new Set()
|
||||||
|
this._timeAtCurrentTick = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers for fn to be called either on this tick or the next tick.
|
||||||
|
*
|
||||||
|
* If registerSideEffect() is called while Ticker.tick() is running, the
|
||||||
|
* side effect _will_ be called within the running tick. If you don't want this
|
||||||
|
* behavior, you can use registerSideEffectForNextTick().
|
||||||
|
*
|
||||||
|
* Note that fn will be added to a Set(). Which means, if you call registerSideEffect(fn)
|
||||||
|
* with the same fn twice in a single tick, it'll only run once.
|
||||||
|
*/
|
||||||
|
onThisOrNextTick(fn: ICallback) {
|
||||||
|
this._scheduledForThisOrNextTick.add(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers a side effect to be called on the next tick.
|
||||||
|
*
|
||||||
|
* @see Ticker:onThisOrNextTick()
|
||||||
|
*/
|
||||||
|
onNextTick(fn: ICallback) {
|
||||||
|
this._scheduledForNextTick.add(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
offThisOrNextTick(fn: ICallback) {
|
||||||
|
this._scheduledForThisOrNextTick.delete(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
offNextTick(fn: ICallback) {
|
||||||
|
this._scheduledForNextTick.delete(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
get time() {
|
||||||
|
if (this._ticking) {
|
||||||
|
return this._timeAtCurrentTick
|
||||||
|
} else return performance.now()
|
||||||
|
}
|
||||||
|
|
||||||
|
tick(t: number = performance.now()) {
|
||||||
|
this._ticking = true
|
||||||
|
this._timeAtCurrentTick = t
|
||||||
|
this._scheduledForNextTick.forEach((v) =>
|
||||||
|
this._scheduledForThisOrNextTick.add(v),
|
||||||
|
)
|
||||||
|
this._scheduledForNextTick.clear()
|
||||||
|
this._tick(0)
|
||||||
|
this._ticking = false
|
||||||
|
}
|
||||||
|
|
||||||
|
private _tick(iterationNumber: number): void {
|
||||||
|
const time = this.time
|
||||||
|
|
||||||
|
if (iterationNumber > 10) {
|
||||||
|
console.warn('_tick() recursing for 10 times')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (iterationNumber > 100) {
|
||||||
|
throw new Error(`Maximum recursion limit for _tick()`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const oldSet = this._scheduledForThisOrNextTick
|
||||||
|
this._scheduledForThisOrNextTick = new Set()
|
||||||
|
oldSet.forEach((fn) => {
|
||||||
|
fn(time)
|
||||||
|
})
|
||||||
|
|
||||||
|
if (this._scheduledForThisOrNextTick.size > 0) {
|
||||||
|
return this._tick(iterationNumber + 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
24
packages/dataverse/src/atom.typeTest.ts
Normal file
24
packages/dataverse/src/atom.typeTest.ts
Normal file
|
@ -0,0 +1,24 @@
|
||||||
|
import Atom, {val} from './Atom'
|
||||||
|
import {expectType, _any} from './utils/typeTestUtils'
|
||||||
|
;() => {
|
||||||
|
const p = new Atom<{foo: string; bar: number; optional?: boolean}>(_any)
|
||||||
|
.pointer
|
||||||
|
expectType<string>(val(p.foo))
|
||||||
|
// @ts-expect-error TypeTest
|
||||||
|
expectType<number>(val(p.foo))
|
||||||
|
|
||||||
|
expectType<number>(val(p.bar))
|
||||||
|
// @ts-expect-error TypeTest
|
||||||
|
expectType<string>(val(p.bar))
|
||||||
|
|
||||||
|
// @ts-expect-error TypeTest
|
||||||
|
expectType<{}>(val(p.nonExistent))
|
||||||
|
|
||||||
|
expectType<undefined | boolean>(val(p.optional))
|
||||||
|
// @ts-expect-error TypeTest
|
||||||
|
expectType<boolean>(val(p.optional))
|
||||||
|
// @ts-expect-error TypeTest
|
||||||
|
expectType<undefined>(val(p.optional))
|
||||||
|
// @ts-expect-error TypeTest
|
||||||
|
expectType<undefined | string>(val(p.optional))
|
||||||
|
}
|
160
packages/dataverse/src/derivations/AbstractDerivation.ts
Normal file
160
packages/dataverse/src/derivations/AbstractDerivation.ts
Normal file
|
@ -0,0 +1,160 @@
|
||||||
|
import type Ticker from '../Ticker'
|
||||||
|
import type {$IntentionalAny, VoidFn} from '../types'
|
||||||
|
import type Tappable from '../utils/Tappable'
|
||||||
|
import DerivationEmitter from './DerivationEmitter'
|
||||||
|
import DerivationValuelessEmitter from './DerivationValuelessEmitter'
|
||||||
|
import flatMap from './flatMap'
|
||||||
|
import type {IDerivation} from './IDerivation'
|
||||||
|
import map from './map'
|
||||||
|
import {
|
||||||
|
reportResolutionEnd,
|
||||||
|
reportResolutionStart,
|
||||||
|
} from './prism/discoveryMechanism'
|
||||||
|
|
||||||
|
type IDependent = (msgComingFrom: IDerivation<$IntentionalAny>) => void
|
||||||
|
export default abstract class AbstractDerivation<V> implements IDerivation<V> {
|
||||||
|
readonly isDerivation: true = true
|
||||||
|
private _didMarkDependentsAsStale: boolean = false
|
||||||
|
private _isHot: boolean = false
|
||||||
|
|
||||||
|
private _isFresh: boolean = false
|
||||||
|
protected _lastValue: undefined | V = undefined
|
||||||
|
|
||||||
|
protected _dependents: Set<IDependent> = new Set()
|
||||||
|
protected _dependencies: Set<IDerivation<$IntentionalAny>> = new Set()
|
||||||
|
|
||||||
|
protected abstract _recalculate(): V
|
||||||
|
protected abstract _reactToDependencyBecomingStale(
|
||||||
|
which: IDerivation<unknown>,
|
||||||
|
): void
|
||||||
|
|
||||||
|
constructor() {}
|
||||||
|
|
||||||
|
get isHot(): boolean {
|
||||||
|
return this._isHot
|
||||||
|
}
|
||||||
|
|
||||||
|
protected _addDependency(d: IDerivation<$IntentionalAny>) {
|
||||||
|
if (this._dependencies.has(d)) return
|
||||||
|
this._dependencies.add(d)
|
||||||
|
if (this._isHot) d.addDependent(this._internal_markAsStale)
|
||||||
|
}
|
||||||
|
|
||||||
|
protected _removeDependency(d: IDerivation<$IntentionalAny>) {
|
||||||
|
if (!this._dependencies.has(d)) return
|
||||||
|
this._dependencies.delete(d)
|
||||||
|
if (this._isHot) d.removeDependent(this._internal_markAsStale)
|
||||||
|
}
|
||||||
|
|
||||||
|
changes(ticker: Ticker): Tappable<V> {
|
||||||
|
return new DerivationEmitter(this, ticker).tappable()
|
||||||
|
}
|
||||||
|
|
||||||
|
changesWithoutValues(): Tappable<void> {
|
||||||
|
return new DerivationValuelessEmitter(this).tappable()
|
||||||
|
}
|
||||||
|
|
||||||
|
keepHot() {
|
||||||
|
return this.changesWithoutValues().tap(() => {})
|
||||||
|
}
|
||||||
|
|
||||||
|
tapImmediate(ticker: Ticker, fn: (cb: V) => void): VoidFn {
|
||||||
|
const untap = this.changes(ticker).tap(fn)
|
||||||
|
fn(this.getValue())
|
||||||
|
return untap
|
||||||
|
}
|
||||||
|
|
||||||
|
addDependent(d: IDependent) {
|
||||||
|
const hadDepsBefore = this._dependents.size > 0
|
||||||
|
this._dependents.add(d)
|
||||||
|
const hasDepsNow = this._dependents.size > 0
|
||||||
|
if (hadDepsBefore !== hasDepsNow) {
|
||||||
|
this._reactToNumberOfDependentsChange()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @sealed
|
||||||
|
*/
|
||||||
|
removeDependent(d: IDependent) {
|
||||||
|
const hadDepsBefore = this._dependents.size > 0
|
||||||
|
this._dependents.delete(d)
|
||||||
|
const hasDepsNow = this._dependents.size > 0
|
||||||
|
if (hadDepsBefore !== hasDepsNow) {
|
||||||
|
this._reactToNumberOfDependentsChange()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This is meant to be called by subclasses
|
||||||
|
*
|
||||||
|
* @sealed
|
||||||
|
*/
|
||||||
|
protected _markAsStale(which: IDerivation<$IntentionalAny>) {
|
||||||
|
this._internal_markAsStale(which)
|
||||||
|
}
|
||||||
|
|
||||||
|
private _internal_markAsStale = (which: IDerivation<$IntentionalAny>) => {
|
||||||
|
this._reactToDependencyBecomingStale(which)
|
||||||
|
|
||||||
|
if (this._didMarkDependentsAsStale) return
|
||||||
|
|
||||||
|
this._didMarkDependentsAsStale = true
|
||||||
|
this._isFresh = false
|
||||||
|
|
||||||
|
this._dependents.forEach((dependent) => {
|
||||||
|
dependent(this)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
getValue(): V {
|
||||||
|
reportResolutionStart(this)
|
||||||
|
|
||||||
|
if (!this._isFresh) {
|
||||||
|
const newValue = this._recalculate()
|
||||||
|
this._lastValue = newValue
|
||||||
|
if (this.isHot) {
|
||||||
|
this._isFresh = true
|
||||||
|
this._didMarkDependentsAsStale = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
reportResolutionEnd(this)
|
||||||
|
return this._lastValue!
|
||||||
|
}
|
||||||
|
|
||||||
|
private _reactToNumberOfDependentsChange() {
|
||||||
|
const shouldBecomeHot = this._dependents.size > 0
|
||||||
|
|
||||||
|
if (shouldBecomeHot === this._isHot) return
|
||||||
|
|
||||||
|
this._isHot = shouldBecomeHot
|
||||||
|
this._didMarkDependentsAsStale = false
|
||||||
|
this._isFresh = false
|
||||||
|
if (shouldBecomeHot) {
|
||||||
|
this._dependencies.forEach((d) => {
|
||||||
|
d.addDependent(this._internal_markAsStale)
|
||||||
|
})
|
||||||
|
this._keepHot()
|
||||||
|
} else {
|
||||||
|
this._dependencies.forEach((d) => {
|
||||||
|
d.removeDependent(this._internal_markAsStale)
|
||||||
|
})
|
||||||
|
this._becomeCold()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected _keepHot() {}
|
||||||
|
|
||||||
|
protected _becomeCold() {}
|
||||||
|
|
||||||
|
map<T>(fn: (v: V) => T): IDerivation<T> {
|
||||||
|
return map(this, fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
flatMap<R>(
|
||||||
|
fn: (v: V) => R,
|
||||||
|
): IDerivation<R extends IDerivation<infer T> ? T : R> {
|
||||||
|
return flatMap(this, fn)
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,36 @@
|
||||||
|
import type {$IntentionalAny} from '../types'
|
||||||
|
import type {IDerivation} from './IDerivation'
|
||||||
|
|
||||||
|
const _any: $IntentionalAny = null
|
||||||
|
|
||||||
|
// map
|
||||||
|
;() => {
|
||||||
|
const a: IDerivation<string> = _any
|
||||||
|
|
||||||
|
// $ExpectType IDerivation<number>
|
||||||
|
// eslint-disable-next-line unused-imports/no-unused-vars-ts
|
||||||
|
a.map((s: string) => 10)
|
||||||
|
|
||||||
|
// @ts-expect-error
|
||||||
|
// eslint-disable-next-line unused-imports/no-unused-vars-ts
|
||||||
|
a.map((s: number) => 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
// flatMap()
|
||||||
|
/* eslint-disable unused-imports/no-unused-vars-ts */
|
||||||
|
;() => {
|
||||||
|
const a: IDerivation<string> = _any
|
||||||
|
|
||||||
|
// okay
|
||||||
|
a.flatMap((s: string) => {})
|
||||||
|
|
||||||
|
// @ts-expect-error TypeTest
|
||||||
|
a.flatMap((s: number) => {})
|
||||||
|
|
||||||
|
// $ExpectType IDerivation<number>
|
||||||
|
a.flatMap((s): IDerivation<number> => _any)
|
||||||
|
|
||||||
|
// $ExpectType IDerivation<number>
|
||||||
|
a.flatMap((s): number => _any)
|
||||||
|
}
|
||||||
|
/* eslint-enable unused-imports/no-unused-vars-ts */
|
17
packages/dataverse/src/derivations/ConstantDerivation.ts
Normal file
17
packages/dataverse/src/derivations/ConstantDerivation.ts
Normal file
|
@ -0,0 +1,17 @@
|
||||||
|
import AbstractDerivation from './AbstractDerivation'
|
||||||
|
|
||||||
|
export default class ConstantDerivation<V> extends AbstractDerivation<V> {
|
||||||
|
_v: V
|
||||||
|
|
||||||
|
constructor(v: V) {
|
||||||
|
super()
|
||||||
|
this._v = v
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
_recalculate() {
|
||||||
|
return this._v
|
||||||
|
}
|
||||||
|
|
||||||
|
_reactToDependencyBecomingStale() {}
|
||||||
|
}
|
54
packages/dataverse/src/derivations/DerivationEmitter.ts
Normal file
54
packages/dataverse/src/derivations/DerivationEmitter.ts
Normal file
|
@ -0,0 +1,54 @@
|
||||||
|
import type Ticker from '../Ticker'
|
||||||
|
import Emitter from '../utils/Emitter'
|
||||||
|
import type {default as Tappable} from '../utils/Tappable'
|
||||||
|
import type {IDerivation} from './IDerivation'
|
||||||
|
|
||||||
|
export default class DerivationEmitter<V> {
|
||||||
|
private _derivation: IDerivation<V>
|
||||||
|
private _ticker: Ticker
|
||||||
|
private _emitter: Emitter<V>
|
||||||
|
private _lastValue: undefined | V
|
||||||
|
private _lastValueRecorded: boolean
|
||||||
|
private _hadTappers: boolean
|
||||||
|
|
||||||
|
constructor(derivation: IDerivation<V>, ticker: Ticker) {
|
||||||
|
this._derivation = derivation
|
||||||
|
this._ticker = ticker
|
||||||
|
this._emitter = new Emitter()
|
||||||
|
this._emitter.onNumberOfTappersChange(() => {
|
||||||
|
this._reactToNumberOfTappersChange()
|
||||||
|
})
|
||||||
|
this._hadTappers = false
|
||||||
|
this._lastValueRecorded = false
|
||||||
|
this._lastValue = undefined
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
private _possiblyMarkAsStale = () => {
|
||||||
|
this._ticker.onThisOrNextTick(this._refresh)
|
||||||
|
}
|
||||||
|
|
||||||
|
private _reactToNumberOfTappersChange() {
|
||||||
|
const hasTappers = this._emitter.hasTappers()
|
||||||
|
if (hasTappers !== this._hadTappers) {
|
||||||
|
this._hadTappers = hasTappers
|
||||||
|
if (hasTappers) {
|
||||||
|
this._derivation.addDependent(this._possiblyMarkAsStale)
|
||||||
|
} else {
|
||||||
|
this._derivation.removeDependent(this._possiblyMarkAsStale)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tappable(): Tappable<V> {
|
||||||
|
return this._emitter.tappable
|
||||||
|
}
|
||||||
|
|
||||||
|
private _refresh = () => {
|
||||||
|
const newValue = this._derivation.getValue()
|
||||||
|
if (newValue === this._lastValue && this._lastValueRecorded === true) return
|
||||||
|
this._lastValue = newValue
|
||||||
|
this._lastValueRecorded = true
|
||||||
|
this._emitter.emit(newValue)
|
||||||
|
}
|
||||||
|
}
|
53
packages/dataverse/src/derivations/DerivationFromSource.ts
Normal file
53
packages/dataverse/src/derivations/DerivationFromSource.ts
Normal file
|
@ -0,0 +1,53 @@
|
||||||
|
import type {VoidFn} from '../types'
|
||||||
|
import AbstractDerivation from './AbstractDerivation'
|
||||||
|
|
||||||
|
const noop = () => {}
|
||||||
|
|
||||||
|
export default class DerivationFromSource<V> extends AbstractDerivation<V> {
|
||||||
|
private _untapFromChanges: () => void
|
||||||
|
private _cachedValue: undefined | V
|
||||||
|
private _hasCachedValue: boolean
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly _tapToSource: (listener: (newValue: V) => void) => VoidFn,
|
||||||
|
private readonly _getValueFromSource: () => V,
|
||||||
|
) {
|
||||||
|
super()
|
||||||
|
this._untapFromChanges = noop
|
||||||
|
this._cachedValue = undefined
|
||||||
|
this._hasCachedValue = false
|
||||||
|
}
|
||||||
|
|
||||||
|
_recalculate() {
|
||||||
|
if (this.isHot) {
|
||||||
|
if (!this._hasCachedValue) {
|
||||||
|
this._cachedValue = this._getValueFromSource()
|
||||||
|
this._hasCachedValue = true
|
||||||
|
}
|
||||||
|
return this._cachedValue as V
|
||||||
|
} else {
|
||||||
|
return this._getValueFromSource()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_keepHot() {
|
||||||
|
this._hasCachedValue = false
|
||||||
|
this._cachedValue = undefined
|
||||||
|
|
||||||
|
this._untapFromChanges = this._tapToSource((newValue) => {
|
||||||
|
this._hasCachedValue = true
|
||||||
|
this._cachedValue = newValue
|
||||||
|
this._markAsStale(this)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
_becomeCold() {
|
||||||
|
this._untapFromChanges()
|
||||||
|
this._untapFromChanges = noop
|
||||||
|
|
||||||
|
this._hasCachedValue = false
|
||||||
|
this._cachedValue = undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
_reactToDependencyBecomingStale() {}
|
||||||
|
}
|
|
@ -0,0 +1,45 @@
|
||||||
|
import Emitter from '../utils/Emitter'
|
||||||
|
import type {default as Tappable} from '../utils/Tappable'
|
||||||
|
import type {IDerivation} from './IDerivation'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Just like DerivationEmitter, except it doesn't emit the value and doesn't need a ticker
|
||||||
|
*/
|
||||||
|
export default class DerivationValuelessEmitter<V> {
|
||||||
|
_derivation: IDerivation<V>
|
||||||
|
_emitter: Emitter<void>
|
||||||
|
_hadTappers: boolean
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
derivation: IDerivation<V>,
|
||||||
|
readonly dontEmitValues: boolean = false,
|
||||||
|
) {
|
||||||
|
this._derivation = derivation
|
||||||
|
this._emitter = new Emitter()
|
||||||
|
this._emitter.onNumberOfTappersChange(() => {
|
||||||
|
this._reactToNumberOfTappersChange()
|
||||||
|
})
|
||||||
|
this._hadTappers = false
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
private _possiblyMarkAsStale = () => {
|
||||||
|
this._emitter.emit(undefined)
|
||||||
|
}
|
||||||
|
|
||||||
|
_reactToNumberOfTappersChange() {
|
||||||
|
const hasTappers = this._emitter.hasTappers()
|
||||||
|
if (hasTappers !== this._hadTappers) {
|
||||||
|
this._hadTappers = hasTappers
|
||||||
|
if (hasTappers) {
|
||||||
|
this._derivation.addDependent(this._possiblyMarkAsStale)
|
||||||
|
} else {
|
||||||
|
this._derivation.removeDependent(this._possiblyMarkAsStale)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tappable(): Tappable<void> {
|
||||||
|
return this._emitter.tappable
|
||||||
|
}
|
||||||
|
}
|
28
packages/dataverse/src/derivations/IDerivation.ts
Normal file
28
packages/dataverse/src/derivations/IDerivation.ts
Normal file
|
@ -0,0 +1,28 @@
|
||||||
|
import type Ticker from '../Ticker'
|
||||||
|
import type {$IntentionalAny, VoidFn} from '../types'
|
||||||
|
import type Tappable from '../utils/Tappable'
|
||||||
|
|
||||||
|
type IDependent = (msgComingFrom: IDerivation<$IntentionalAny>) => void
|
||||||
|
export interface IDerivation<V> {
|
||||||
|
isDerivation: true
|
||||||
|
isHot: boolean
|
||||||
|
changes(ticker: Ticker): Tappable<V>
|
||||||
|
|
||||||
|
changesWithoutValues(): Tappable<void>
|
||||||
|
keepHot(): VoidFn
|
||||||
|
tapImmediate(ticker: Ticker, fn: (cb: V) => void): VoidFn
|
||||||
|
addDependent(d: IDependent): void
|
||||||
|
removeDependent(d: IDependent): void
|
||||||
|
|
||||||
|
getValue(): V
|
||||||
|
|
||||||
|
map<T>(fn: (v: V) => T): IDerivation<T>
|
||||||
|
|
||||||
|
flatMap<R>(
|
||||||
|
fn: (v: V) => R,
|
||||||
|
): IDerivation<R extends IDerivation<infer T> ? T : R>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isDerivation(d: any): d is IDerivation<unknown> {
|
||||||
|
return d && d.isDerivation && d.isDerivation === true
|
||||||
|
}
|
128
packages/dataverse/src/derivations/flatMap.ts
Normal file
128
packages/dataverse/src/derivations/flatMap.ts
Normal file
|
@ -0,0 +1,128 @@
|
||||||
|
import type {$FixMe} from '../types'
|
||||||
|
import AbstractDerivation from './AbstractDerivation'
|
||||||
|
import type {IDerivation} from './IDerivation'
|
||||||
|
import {isDerivation} from './IDerivation'
|
||||||
|
|
||||||
|
enum UPDATE_NEEDED_FROM {
|
||||||
|
none = 0,
|
||||||
|
dep = 1,
|
||||||
|
inner = 2,
|
||||||
|
}
|
||||||
|
|
||||||
|
const makeFlatMapDerivationClass = () => {
|
||||||
|
class FlatMapDerivation<V, DepType> extends AbstractDerivation<V> {
|
||||||
|
private _innerDerivation: undefined | null | IDerivation<V>
|
||||||
|
private _staleDependency: UPDATE_NEEDED_FROM
|
||||||
|
|
||||||
|
static displayName = 'flatMap'
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
readonly _depDerivation: IDerivation<DepType>,
|
||||||
|
readonly _fn: (v: DepType) => IDerivation<V> | V,
|
||||||
|
) {
|
||||||
|
super()
|
||||||
|
this._innerDerivation = undefined
|
||||||
|
this._staleDependency = UPDATE_NEEDED_FROM.dep
|
||||||
|
|
||||||
|
this._addDependency(_depDerivation)
|
||||||
|
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
_recalculateHot() {
|
||||||
|
const updateNeededFrom = this._staleDependency
|
||||||
|
this._staleDependency = UPDATE_NEEDED_FROM.none
|
||||||
|
|
||||||
|
if (updateNeededFrom === UPDATE_NEEDED_FROM.inner) {
|
||||||
|
// @ts-ignore
|
||||||
|
return this._innerDerivation.getValue()
|
||||||
|
}
|
||||||
|
|
||||||
|
const possibleInnerDerivation = this._fn(this._depDerivation.getValue())
|
||||||
|
|
||||||
|
if (isDerivation(possibleInnerDerivation)) {
|
||||||
|
this._innerDerivation = possibleInnerDerivation
|
||||||
|
this._addDependency(possibleInnerDerivation)
|
||||||
|
return possibleInnerDerivation.getValue()
|
||||||
|
} else {
|
||||||
|
return possibleInnerDerivation
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected _recalculateCold() {
|
||||||
|
const possibleInnerDerivation = this._fn(this._depDerivation.getValue())
|
||||||
|
|
||||||
|
if (isDerivation(possibleInnerDerivation)) {
|
||||||
|
return possibleInnerDerivation.getValue()
|
||||||
|
} else {
|
||||||
|
return possibleInnerDerivation
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected _recalculate() {
|
||||||
|
return this.isHot ? this._recalculateHot() : this._recalculateCold()
|
||||||
|
}
|
||||||
|
|
||||||
|
protected _reactToDependencyBecomingStale(
|
||||||
|
msgComingFrom: IDerivation<unknown>,
|
||||||
|
) {
|
||||||
|
const updateNeededFrom =
|
||||||
|
msgComingFrom === this._depDerivation
|
||||||
|
? UPDATE_NEEDED_FROM.dep
|
||||||
|
: UPDATE_NEEDED_FROM.inner
|
||||||
|
|
||||||
|
if (
|
||||||
|
updateNeededFrom === UPDATE_NEEDED_FROM.inner &&
|
||||||
|
msgComingFrom !== this._innerDerivation
|
||||||
|
) {
|
||||||
|
throw Error(
|
||||||
|
`got a _reactToDependencyBecomingStale() from neither the dep nor the inner derivation`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this._staleDependency === UPDATE_NEEDED_FROM.none) {
|
||||||
|
this._staleDependency = updateNeededFrom
|
||||||
|
|
||||||
|
if (updateNeededFrom === UPDATE_NEEDED_FROM.dep) {
|
||||||
|
this._removeInnerDerivation()
|
||||||
|
}
|
||||||
|
} else if (this._staleDependency === UPDATE_NEEDED_FROM.dep) {
|
||||||
|
} else {
|
||||||
|
if (updateNeededFrom === UPDATE_NEEDED_FROM.dep) {
|
||||||
|
this._staleDependency = UPDATE_NEEDED_FROM.dep
|
||||||
|
this._removeInnerDerivation()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private _removeInnerDerivation() {
|
||||||
|
if (this._innerDerivation) {
|
||||||
|
this._removeDependency(this._innerDerivation)
|
||||||
|
this._innerDerivation = undefined
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected _keepHot() {
|
||||||
|
this._staleDependency = UPDATE_NEEDED_FROM.dep
|
||||||
|
this.getValue()
|
||||||
|
}
|
||||||
|
|
||||||
|
protected _becomeCold() {
|
||||||
|
this._staleDependency = UPDATE_NEEDED_FROM.dep
|
||||||
|
this._removeInnerDerivation()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return FlatMapDerivation
|
||||||
|
}
|
||||||
|
|
||||||
|
let cls: ReturnType<typeof makeFlatMapDerivationClass> | undefined = undefined
|
||||||
|
|
||||||
|
export default function flatMap<V, R>(
|
||||||
|
dep: IDerivation<V>,
|
||||||
|
fn: (v: V) => R,
|
||||||
|
): IDerivation<R extends IDerivation<infer T> ? T : R> {
|
||||||
|
if (!cls) {
|
||||||
|
cls = makeFlatMapDerivationClass()
|
||||||
|
}
|
||||||
|
return new cls(dep, fn) as $FixMe
|
||||||
|
}
|
32
packages/dataverse/src/derivations/iterateAndCountTicks.ts
Normal file
32
packages/dataverse/src/derivations/iterateAndCountTicks.ts
Normal file
|
@ -0,0 +1,32 @@
|
||||||
|
import {isPointer, valueDerivation} from '../Atom'
|
||||||
|
import type {Pointer} from '../pointer'
|
||||||
|
import type {IDerivation} from './IDerivation'
|
||||||
|
import {isDerivation} from './IDerivation'
|
||||||
|
|
||||||
|
export default function* iterateAndCountTicks<V>(
|
||||||
|
pointerOrDerivation: IDerivation<V> | Pointer<V>,
|
||||||
|
): Generator<{value: V; ticks: number}, void, void> {
|
||||||
|
let d
|
||||||
|
if (isPointer(pointerOrDerivation)) {
|
||||||
|
d = valueDerivation(pointerOrDerivation) as IDerivation<V>
|
||||||
|
} else if (isDerivation(pointerOrDerivation)) {
|
||||||
|
d = pointerOrDerivation
|
||||||
|
} else {
|
||||||
|
throw new Error(`Only pointers and derivations are supported`)
|
||||||
|
}
|
||||||
|
|
||||||
|
let ticksCountedSinceLastYield = 0
|
||||||
|
const untap = d.changesWithoutValues().tap(() => {
|
||||||
|
ticksCountedSinceLastYield++
|
||||||
|
})
|
||||||
|
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
const ticks = ticksCountedSinceLastYield
|
||||||
|
ticksCountedSinceLastYield = 0
|
||||||
|
yield {value: d.getValue(), ticks}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
untap()
|
||||||
|
}
|
||||||
|
}
|
22
packages/dataverse/src/derivations/iterateOver.test.ts
Normal file
22
packages/dataverse/src/derivations/iterateOver.test.ts
Normal file
|
@ -0,0 +1,22 @@
|
||||||
|
/**
|
||||||
|
* @jest-environment jsdom
|
||||||
|
*/
|
||||||
|
import Atom from '../Atom'
|
||||||
|
import iterateOver from './iterateOver'
|
||||||
|
|
||||||
|
describe(`iterateOver()`, () => {
|
||||||
|
test('it should work', () => {
|
||||||
|
const a = new Atom({a: 0})
|
||||||
|
let iter = iterateOver(a.pointer.a)
|
||||||
|
expect(iter.next().value).toEqual(0)
|
||||||
|
a.setIn(['a'], 1)
|
||||||
|
a.setIn(['a'], 2)
|
||||||
|
expect(iter.next()).toMatchObject({value: 2, done: false})
|
||||||
|
iter.return()
|
||||||
|
iter = iterateOver(a.pointer.a)
|
||||||
|
expect(iter.next().value).toEqual(2)
|
||||||
|
a.setIn(['a'], 3)
|
||||||
|
expect(iter.next()).toMatchObject({done: false, value: 3})
|
||||||
|
iter.return()
|
||||||
|
})
|
||||||
|
})
|
32
packages/dataverse/src/derivations/iterateOver.ts
Normal file
32
packages/dataverse/src/derivations/iterateOver.ts
Normal file
|
@ -0,0 +1,32 @@
|
||||||
|
import {isPointer, valueDerivation} from '../Atom'
|
||||||
|
import type {Pointer} from '../pointer'
|
||||||
|
import Ticker from '../Ticker'
|
||||||
|
import type {IDerivation} from './IDerivation'
|
||||||
|
import {isDerivation} from './IDerivation'
|
||||||
|
|
||||||
|
export default function* iterateOver<V>(
|
||||||
|
pointerOrDerivation: IDerivation<V> | Pointer<V>,
|
||||||
|
): Generator<V, void, void> {
|
||||||
|
let d
|
||||||
|
if (isPointer(pointerOrDerivation)) {
|
||||||
|
d = valueDerivation(pointerOrDerivation) as IDerivation<V>
|
||||||
|
} else if (isDerivation(pointerOrDerivation)) {
|
||||||
|
d = pointerOrDerivation
|
||||||
|
} else {
|
||||||
|
throw new Error(`Only pointers and derivations are supported`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const ticker = new Ticker()
|
||||||
|
|
||||||
|
const untap = d.changes(ticker).tap((v) => {})
|
||||||
|
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
ticker.tick()
|
||||||
|
|
||||||
|
yield d.getValue()
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
untap()
|
||||||
|
}
|
||||||
|
}
|
32
packages/dataverse/src/derivations/map.ts
Normal file
32
packages/dataverse/src/derivations/map.ts
Normal file
|
@ -0,0 +1,32 @@
|
||||||
|
import AbstractDerivation from './AbstractDerivation'
|
||||||
|
import type {IDerivation} from './IDerivation'
|
||||||
|
|
||||||
|
// Exporting from a function because of the circular dependency with AbstractDerivation
|
||||||
|
const makeMapDerivationClass = () =>
|
||||||
|
class MapDerivation<T, V> extends AbstractDerivation<V> {
|
||||||
|
constructor(
|
||||||
|
private readonly _dep: IDerivation<T>,
|
||||||
|
private readonly _fn: (t: T) => V,
|
||||||
|
) {
|
||||||
|
super()
|
||||||
|
this._addDependency(_dep)
|
||||||
|
}
|
||||||
|
|
||||||
|
_recalculate() {
|
||||||
|
return this._fn(this._dep.getValue())
|
||||||
|
}
|
||||||
|
|
||||||
|
_reactToDependencyBecomingStale() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
let cls: ReturnType<typeof makeMapDerivationClass> | undefined = undefined
|
||||||
|
|
||||||
|
export default function flatMap<V, R>(
|
||||||
|
dep: IDerivation<V>,
|
||||||
|
fn: (v: V) => R,
|
||||||
|
): IDerivation<R> {
|
||||||
|
if (!cls) {
|
||||||
|
cls = makeMapDerivationClass()
|
||||||
|
}
|
||||||
|
return new cls(dep, fn)
|
||||||
|
}
|
|
@ -0,0 +1,94 @@
|
||||||
|
import type {$IntentionalAny} from '../../types'
|
||||||
|
import Stack from '../../utils/Stack'
|
||||||
|
import type {IDerivation} from '../IDerivation'
|
||||||
|
|
||||||
|
function createMechanism() {
|
||||||
|
const noop = () => {}
|
||||||
|
|
||||||
|
const stack = new Stack<Collector>()
|
||||||
|
const noopCollector: Collector = noop
|
||||||
|
|
||||||
|
type Collector = (d: IDerivation<$IntentionalAny>) => void
|
||||||
|
|
||||||
|
const collectObservedDependencies = (
|
||||||
|
cb: () => void,
|
||||||
|
collector: Collector,
|
||||||
|
) => {
|
||||||
|
stack.push(collector)
|
||||||
|
cb()
|
||||||
|
stack.pop()
|
||||||
|
}
|
||||||
|
|
||||||
|
const startIgnoringDependencies = () => {
|
||||||
|
stack.push(noopCollector)
|
||||||
|
}
|
||||||
|
|
||||||
|
const stopIgnoringDependencies = () => {
|
||||||
|
if (stack.peek() !== noopCollector) {
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('This should never happen')
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
stack.pop()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const reportResolutionStart = (d: IDerivation<$IntentionalAny>) => {
|
||||||
|
const possibleCollector = stack.peek()
|
||||||
|
if (possibleCollector) {
|
||||||
|
possibleCollector(d)
|
||||||
|
}
|
||||||
|
|
||||||
|
stack.push(noopCollector)
|
||||||
|
}
|
||||||
|
|
||||||
|
const reportResolutionEnd = (_d: IDerivation<$IntentionalAny>) => {
|
||||||
|
stack.pop()
|
||||||
|
}
|
||||||
|
|
||||||
|
const isCollectingDependencies = () => {
|
||||||
|
return stack.peek() !== noopCollector
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: 'Dataverse_discoveryMechanism' as 'Dataverse_discoveryMechanism',
|
||||||
|
collectObservedDependencies,
|
||||||
|
startIgnoringDependencies,
|
||||||
|
stopIgnoringDependencies,
|
||||||
|
reportResolutionStart,
|
||||||
|
reportResolutionEnd,
|
||||||
|
isCollectingDependencies,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getSharedMechanism(): ReturnType<typeof createMechanism> {
|
||||||
|
const varName = '__dataverse_discoveryMechanism_sharedStack'
|
||||||
|
if (global) {
|
||||||
|
const existingMechanism: ReturnType<typeof createMechanism> | undefined =
|
||||||
|
// @ts-ignore ignore
|
||||||
|
global[varName]
|
||||||
|
if (
|
||||||
|
existingMechanism &&
|
||||||
|
typeof existingMechanism === 'object' &&
|
||||||
|
existingMechanism.type === 'Dataverse_discoveryMechanism'
|
||||||
|
) {
|
||||||
|
return existingMechanism
|
||||||
|
} else {
|
||||||
|
const mechanism = createMechanism()
|
||||||
|
// @ts-ignore ignore
|
||||||
|
global[varName] = mechanism
|
||||||
|
return mechanism
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return createMechanism()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const {
|
||||||
|
collectObservedDependencies,
|
||||||
|
startIgnoringDependencies,
|
||||||
|
stopIgnoringDependencies,
|
||||||
|
reportResolutionEnd,
|
||||||
|
reportResolutionStart,
|
||||||
|
isCollectingDependencies,
|
||||||
|
} = getSharedMechanism()
|
228
packages/dataverse/src/derivations/prism/prism.test.ts
Normal file
228
packages/dataverse/src/derivations/prism/prism.test.ts
Normal file
|
@ -0,0 +1,228 @@
|
||||||
|
/**
|
||||||
|
* @jest-environment jsdom
|
||||||
|
*/
|
||||||
|
import Atom, {val} from '../../Atom'
|
||||||
|
import Ticker from '../../Ticker'
|
||||||
|
import type {$FixMe, $IntentionalAny} from '../../types'
|
||||||
|
import ConstantDerivation from '../ConstantDerivation'
|
||||||
|
import iterateAndCountTicks from '../iterateAndCountTicks'
|
||||||
|
import prism, {PrismDerivation} from './prism'
|
||||||
|
|
||||||
|
describe('prism', () => {
|
||||||
|
let ticker: Ticker
|
||||||
|
beforeEach(() => {
|
||||||
|
ticker = new Ticker()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should work', () => {
|
||||||
|
const o = new Atom({foo: 'foo'})
|
||||||
|
const d = new PrismDerivation(() => {
|
||||||
|
return val(o.pointer.foo) + 'boo'
|
||||||
|
})
|
||||||
|
expect(d.getValue()).toEqual('fooboo')
|
||||||
|
|
||||||
|
const changes: Array<$FixMe> = []
|
||||||
|
d.changes(ticker).tap((c) => {
|
||||||
|
changes.push(c)
|
||||||
|
})
|
||||||
|
|
||||||
|
o.reduceState(['foo'], () => 'foo2')
|
||||||
|
ticker.tick()
|
||||||
|
expect(changes).toMatchObject(['foo2boo'])
|
||||||
|
})
|
||||||
|
it('should only collect immediate dependencies', () => {
|
||||||
|
const aD = new ConstantDerivation(1)
|
||||||
|
const bD = aD.map((v) => v * 2)
|
||||||
|
const cD = prism(() => {
|
||||||
|
return bD.getValue()
|
||||||
|
})
|
||||||
|
expect(cD.getValue()).toEqual(2)
|
||||||
|
expect((cD as $IntentionalAny)._dependencies.size).toEqual(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('prism.ref()', () => {
|
||||||
|
it('should work', () => {
|
||||||
|
const theAtom: Atom<{n: number}> = new Atom({n: 2})
|
||||||
|
|
||||||
|
const isEvenD = prism((): {isEven: boolean} => {
|
||||||
|
const ref = prism.ref<{isEven: boolean} | undefined>('cache', undefined)
|
||||||
|
const currentN = val(theAtom.pointer.n)
|
||||||
|
|
||||||
|
const isEven = currentN % 2 === 0
|
||||||
|
if (ref.current && ref.current.isEven === isEven) {
|
||||||
|
return ref.current
|
||||||
|
} else {
|
||||||
|
ref.current = {isEven}
|
||||||
|
return ref.current
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const iterator = iterateAndCountTicks(isEvenD)
|
||||||
|
|
||||||
|
theAtom.reduceState(['n'], () => 3)
|
||||||
|
|
||||||
|
expect(iterator.next().value).toMatchObject({
|
||||||
|
value: {isEven: false},
|
||||||
|
ticks: 0,
|
||||||
|
})
|
||||||
|
theAtom.reduceState(['n'], () => 5)
|
||||||
|
theAtom.reduceState(['n'], () => 7)
|
||||||
|
expect(iterator.next().value).toMatchObject({
|
||||||
|
value: {isEven: false},
|
||||||
|
ticks: 1,
|
||||||
|
})
|
||||||
|
theAtom.reduceState(['n'], () => 2)
|
||||||
|
theAtom.reduceState(['n'], () => 4)
|
||||||
|
expect(iterator.next().value).toMatchObject({
|
||||||
|
value: {isEven: true},
|
||||||
|
ticks: 1,
|
||||||
|
})
|
||||||
|
expect(iterator.next().value).toMatchObject({
|
||||||
|
value: {isEven: true},
|
||||||
|
ticks: 0,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('prism.effect()', () => {
|
||||||
|
it('should work', async () => {
|
||||||
|
let iteration = 0
|
||||||
|
const sequence: unknown[] = []
|
||||||
|
let deps: unknown[] = []
|
||||||
|
|
||||||
|
const a = new Atom({letter: 'a'})
|
||||||
|
|
||||||
|
const derivation = prism(() => {
|
||||||
|
const n = val(a.pointer.letter)
|
||||||
|
const iterationAtTimeOfCall = iteration
|
||||||
|
sequence.push({derivationCall: iterationAtTimeOfCall})
|
||||||
|
|
||||||
|
prism.effect(
|
||||||
|
'f',
|
||||||
|
() => {
|
||||||
|
sequence.push({effectCall: iterationAtTimeOfCall})
|
||||||
|
return () => {
|
||||||
|
sequence.push({cleanupCall: iterationAtTimeOfCall})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[...deps],
|
||||||
|
)
|
||||||
|
|
||||||
|
return n
|
||||||
|
})
|
||||||
|
|
||||||
|
const untap = derivation.changes(ticker).tap((change) => {
|
||||||
|
sequence.push({change})
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(sequence).toMatchObject([{derivationCall: 0}, {effectCall: 0}])
|
||||||
|
sequence.length = 0
|
||||||
|
|
||||||
|
iteration++
|
||||||
|
a.setIn(['letter'], 'b')
|
||||||
|
ticker.tick()
|
||||||
|
expect(sequence).toMatchObject([{derivationCall: 1}, {change: 'b'}])
|
||||||
|
sequence.length = 0
|
||||||
|
|
||||||
|
deps = [1]
|
||||||
|
iteration++
|
||||||
|
a.setIn(['letter'], 'c')
|
||||||
|
ticker.tick()
|
||||||
|
expect(sequence).toMatchObject([
|
||||||
|
{derivationCall: 2},
|
||||||
|
{cleanupCall: 0},
|
||||||
|
{effectCall: 2},
|
||||||
|
{change: 'c'},
|
||||||
|
])
|
||||||
|
sequence.length = 0
|
||||||
|
|
||||||
|
untap()
|
||||||
|
|
||||||
|
// takes a tick before untap takes effect
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 1))
|
||||||
|
expect(sequence).toMatchObject([{cleanupCall: 2}])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('prism.memo()', () => {
|
||||||
|
it('should work', async () => {
|
||||||
|
let iteration = 0
|
||||||
|
const sequence: unknown[] = []
|
||||||
|
let deps: unknown[] = []
|
||||||
|
|
||||||
|
const a = new Atom({letter: 'a'})
|
||||||
|
|
||||||
|
const derivation = prism(() => {
|
||||||
|
const n = val(a.pointer.letter)
|
||||||
|
const iterationAtTimeOfCall = iteration
|
||||||
|
sequence.push({derivationCall: iterationAtTimeOfCall})
|
||||||
|
|
||||||
|
const resultOfMemo = prism.memo(
|
||||||
|
'memo',
|
||||||
|
() => {
|
||||||
|
sequence.push({memoCall: iterationAtTimeOfCall})
|
||||||
|
return iterationAtTimeOfCall
|
||||||
|
},
|
||||||
|
[...deps],
|
||||||
|
)
|
||||||
|
|
||||||
|
sequence.push({resultOfMemo})
|
||||||
|
|
||||||
|
return n
|
||||||
|
})
|
||||||
|
|
||||||
|
const untap = derivation.changes(ticker).tap((change) => {
|
||||||
|
sequence.push({change})
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(sequence).toMatchObject([
|
||||||
|
{derivationCall: 0},
|
||||||
|
{memoCall: 0},
|
||||||
|
{resultOfMemo: 0},
|
||||||
|
])
|
||||||
|
sequence.length = 0
|
||||||
|
|
||||||
|
iteration++
|
||||||
|
a.setIn(['letter'], 'b')
|
||||||
|
ticker.tick()
|
||||||
|
expect(sequence).toMatchObject([
|
||||||
|
{derivationCall: 1},
|
||||||
|
{resultOfMemo: 0},
|
||||||
|
{change: 'b'},
|
||||||
|
])
|
||||||
|
sequence.length = 0
|
||||||
|
|
||||||
|
deps = [1]
|
||||||
|
iteration++
|
||||||
|
a.setIn(['letter'], 'c')
|
||||||
|
ticker.tick()
|
||||||
|
expect(sequence).toMatchObject([
|
||||||
|
{derivationCall: 2},
|
||||||
|
{memoCall: 2},
|
||||||
|
{resultOfMemo: 2},
|
||||||
|
{change: 'c'},
|
||||||
|
])
|
||||||
|
sequence.length = 0
|
||||||
|
|
||||||
|
untap()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe(`prism.scope()`, () => {
|
||||||
|
it('should prevent name conflicts', () => {
|
||||||
|
const d = prism(() => {
|
||||||
|
const thisNameWillBeUsedForBothMemos = 'blah'
|
||||||
|
const a = prism.scope('a', () => {
|
||||||
|
return prism.memo(thisNameWillBeUsedForBothMemos, () => 'a', [])
|
||||||
|
})
|
||||||
|
|
||||||
|
const b = prism.scope('b', () => {
|
||||||
|
return prism.memo(thisNameWillBeUsedForBothMemos, () => 'b', [])
|
||||||
|
})
|
||||||
|
|
||||||
|
return {a, b}
|
||||||
|
})
|
||||||
|
expect(d.getValue()).toMatchObject({a: 'a', b: 'b'})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
347
packages/dataverse/src/derivations/prism/prism.ts
Normal file
347
packages/dataverse/src/derivations/prism/prism.ts
Normal file
|
@ -0,0 +1,347 @@
|
||||||
|
import Box from '../../Box'
|
||||||
|
import type {$IntentionalAny, VoidFn} from '../../types'
|
||||||
|
import Stack from '../../utils/Stack'
|
||||||
|
import AbstractDerivation from '../AbstractDerivation'
|
||||||
|
import type {IDerivation} from '../IDerivation'
|
||||||
|
import {
|
||||||
|
collectObservedDependencies,
|
||||||
|
startIgnoringDependencies,
|
||||||
|
stopIgnoringDependencies,
|
||||||
|
} from './discoveryMechanism'
|
||||||
|
|
||||||
|
const voidFn = () => {}
|
||||||
|
|
||||||
|
export class PrismDerivation<V> extends AbstractDerivation<V> {
|
||||||
|
protected _cacheOfDendencyValues: Map<IDerivation<unknown>, unknown> =
|
||||||
|
new Map()
|
||||||
|
protected _possiblyStaleDeps = new Set<IDerivation<unknown>>()
|
||||||
|
private _prismScope = new PrismScope()
|
||||||
|
|
||||||
|
constructor(readonly _fn: () => V) {
|
||||||
|
super()
|
||||||
|
}
|
||||||
|
|
||||||
|
_recalculate() {
|
||||||
|
let value: V
|
||||||
|
|
||||||
|
if (this._possiblyStaleDeps.size > 0) {
|
||||||
|
let anActuallyStaleDepWasFound = false
|
||||||
|
startIgnoringDependencies()
|
||||||
|
for (const dep of this._possiblyStaleDeps) {
|
||||||
|
if (this._cacheOfDendencyValues.get(dep) !== dep.getValue()) {
|
||||||
|
anActuallyStaleDepWasFound = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
stopIgnoringDependencies()
|
||||||
|
this._possiblyStaleDeps.clear()
|
||||||
|
if (!anActuallyStaleDepWasFound) {
|
||||||
|
// console.log('ok')
|
||||||
|
|
||||||
|
return this._lastValue!
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const newDeps: Set<IDerivation<unknown>> = new Set()
|
||||||
|
this._cacheOfDendencyValues.clear()
|
||||||
|
collectObservedDependencies(
|
||||||
|
() => {
|
||||||
|
hookScopeStack.push(this._prismScope)
|
||||||
|
try {
|
||||||
|
value = this._fn()
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error)
|
||||||
|
} finally {
|
||||||
|
const topOfTheStack = hookScopeStack.pop()
|
||||||
|
if (topOfTheStack !== this._prismScope) {
|
||||||
|
console.warn(
|
||||||
|
// @todo guide the user to report the bug in an issue
|
||||||
|
`The Prism hook stack has slipped. This is a bug.`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
(observedDep) => {
|
||||||
|
newDeps.add(observedDep)
|
||||||
|
this._addDependency(observedDep)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
this._dependencies.forEach((dep) => {
|
||||||
|
if (!newDeps.has(dep)) {
|
||||||
|
this._removeDependency(dep)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
this._dependencies = newDeps
|
||||||
|
|
||||||
|
startIgnoringDependencies()
|
||||||
|
newDeps.forEach((dep) => {
|
||||||
|
this._cacheOfDendencyValues.set(dep, dep.getValue())
|
||||||
|
})
|
||||||
|
stopIgnoringDependencies()
|
||||||
|
|
||||||
|
return value!
|
||||||
|
}
|
||||||
|
|
||||||
|
_reactToDependencyBecomingStale(msgComingFrom: IDerivation<unknown>) {
|
||||||
|
this._possiblyStaleDeps.add(msgComingFrom)
|
||||||
|
}
|
||||||
|
|
||||||
|
_keepHot() {
|
||||||
|
this._prismScope = new PrismScope()
|
||||||
|
startIgnoringDependencies()
|
||||||
|
this.getValue()
|
||||||
|
stopIgnoringDependencies()
|
||||||
|
}
|
||||||
|
|
||||||
|
_becomeCold() {
|
||||||
|
cleanupScopeStack(this._prismScope)
|
||||||
|
this._prismScope = new PrismScope()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class PrismScope {
|
||||||
|
isPrismScope = true
|
||||||
|
private _subs: Record<string, PrismScope> = {}
|
||||||
|
|
||||||
|
sub(key: string) {
|
||||||
|
if (!this._subs[key]) {
|
||||||
|
this._subs[key] = new PrismScope()
|
||||||
|
}
|
||||||
|
return this._subs[key]
|
||||||
|
}
|
||||||
|
|
||||||
|
get subs() {
|
||||||
|
return this._subs
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function cleanupScopeStack(scope: PrismScope) {
|
||||||
|
for (const [_, sub] of Object.entries(scope.subs)) {
|
||||||
|
cleanupScopeStack(sub)
|
||||||
|
}
|
||||||
|
cleanupEffects(scope)
|
||||||
|
}
|
||||||
|
|
||||||
|
function cleanupEffects(scope: PrismScope) {
|
||||||
|
const effects = effectsWeakMap.get(scope)
|
||||||
|
if (effects) {
|
||||||
|
for (const k of Object.keys(effects)) {
|
||||||
|
const effect = effects[k]
|
||||||
|
safelyRun(effect.cleanup, undefined)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
effectsWeakMap.delete(scope)
|
||||||
|
}
|
||||||
|
|
||||||
|
function safelyRun<T, U>(
|
||||||
|
fn: () => T,
|
||||||
|
returnValueInCaseOfError: U,
|
||||||
|
): {success: boolean; returnValue: T | U} {
|
||||||
|
let returnValue: T | U = returnValueInCaseOfError
|
||||||
|
let success = false
|
||||||
|
try {
|
||||||
|
returnValue = fn()
|
||||||
|
success = true
|
||||||
|
} catch (error) {
|
||||||
|
setTimeout(() => {
|
||||||
|
throw error
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return {success, returnValue}
|
||||||
|
}
|
||||||
|
|
||||||
|
const hookScopeStack = new Stack<PrismScope>()
|
||||||
|
|
||||||
|
const refsWeakMap = new WeakMap<PrismScope, Record<string, IRef<unknown>>>()
|
||||||
|
|
||||||
|
type IRef<T> = {
|
||||||
|
current: T
|
||||||
|
}
|
||||||
|
const effectsWeakMap = new WeakMap<PrismScope, Record<string, IEffect>>()
|
||||||
|
|
||||||
|
type IEffect = {
|
||||||
|
deps: undefined | unknown[]
|
||||||
|
cleanup: VoidFn
|
||||||
|
}
|
||||||
|
|
||||||
|
const memosWeakMap = new WeakMap<PrismScope, Record<string, IMemo>>()
|
||||||
|
|
||||||
|
type IMemo = {
|
||||||
|
deps: undefined | unknown[]
|
||||||
|
cachedValue: unknown
|
||||||
|
}
|
||||||
|
|
||||||
|
function ref<T>(key: string, initialValue: T): IRef<T> {
|
||||||
|
const scope = hookScopeStack.peek()
|
||||||
|
if (!scope) {
|
||||||
|
throw new Error(`prism.ref() is called outside of a prism() call.`)
|
||||||
|
}
|
||||||
|
let refs = refsWeakMap.get(scope)
|
||||||
|
if (!refs) {
|
||||||
|
refs = {}
|
||||||
|
refsWeakMap.set(scope, refs)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (refs[key]) {
|
||||||
|
return refs[key] as $IntentionalAny as IRef<T>
|
||||||
|
} else {
|
||||||
|
const ref: IRef<T> = {
|
||||||
|
current: initialValue,
|
||||||
|
}
|
||||||
|
refs[key] = ref
|
||||||
|
return ref
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function effect(key: string, cb: () => () => void, deps?: unknown[]): void {
|
||||||
|
const scope = hookScopeStack.peek()
|
||||||
|
if (!scope) {
|
||||||
|
throw new Error(`prism.effect() is called outside of a prism() call.`)
|
||||||
|
}
|
||||||
|
let effects = effectsWeakMap.get(scope)
|
||||||
|
|
||||||
|
if (!effects) {
|
||||||
|
effects = {}
|
||||||
|
effectsWeakMap.set(scope, effects)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!effects[key]) {
|
||||||
|
effects[key] = {
|
||||||
|
cleanup: voidFn,
|
||||||
|
deps: [{}],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const effect = effects[key]
|
||||||
|
if (depsHaveChanged(effect.deps, deps)) {
|
||||||
|
effect.cleanup()
|
||||||
|
|
||||||
|
startIgnoringDependencies()
|
||||||
|
effect.cleanup = safelyRun(cb, voidFn).returnValue
|
||||||
|
stopIgnoringDependencies()
|
||||||
|
effect.deps = deps
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function depsHaveChanged(
|
||||||
|
oldDeps: undefined | unknown[],
|
||||||
|
newDeps: undefined | unknown[],
|
||||||
|
): boolean {
|
||||||
|
if (oldDeps === undefined || newDeps === undefined) {
|
||||||
|
return true
|
||||||
|
} else if (oldDeps.length !== newDeps.length) {
|
||||||
|
return true
|
||||||
|
} else {
|
||||||
|
return oldDeps.some((el, i) => el !== newDeps[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function memo<T>(
|
||||||
|
key: string,
|
||||||
|
fn: () => T,
|
||||||
|
deps: undefined | $IntentionalAny[],
|
||||||
|
): T {
|
||||||
|
const scope = hookScopeStack.peek()
|
||||||
|
if (!scope) {
|
||||||
|
throw new Error(`prism.memo() is called outside of a prism() call.`)
|
||||||
|
}
|
||||||
|
|
||||||
|
let memos = memosWeakMap.get(scope)
|
||||||
|
|
||||||
|
if (!memos) {
|
||||||
|
memos = {}
|
||||||
|
memosWeakMap.set(scope, memos)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!memos[key]) {
|
||||||
|
memos[key] = {
|
||||||
|
cachedValue: null,
|
||||||
|
deps: [{}],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const memo = memos[key]
|
||||||
|
if (depsHaveChanged(memo.deps, deps)) {
|
||||||
|
startIgnoringDependencies()
|
||||||
|
|
||||||
|
memo.cachedValue = safelyRun(fn, undefined).returnValue
|
||||||
|
stopIgnoringDependencies()
|
||||||
|
memo.deps = deps
|
||||||
|
}
|
||||||
|
|
||||||
|
return memo.cachedValue as $IntentionalAny as T
|
||||||
|
}
|
||||||
|
|
||||||
|
function state<T>(key: string, initialValue: T): [T, (val: T) => void] {
|
||||||
|
const {b, setValue} = prism.memo(
|
||||||
|
'state/' + key,
|
||||||
|
() => {
|
||||||
|
const b = new Box<T>(initialValue)
|
||||||
|
const setValue = (val: T) => b.set(val)
|
||||||
|
return {b, setValue}
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
)
|
||||||
|
|
||||||
|
return [b.derivation.getValue(), setValue]
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensurePrism(): void {
|
||||||
|
const scope = hookScopeStack.peek()
|
||||||
|
if (!scope) {
|
||||||
|
throw new Error(`The parent function is called outside of a prism() call.`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function scope<T>(key: string, fn: () => T): T {
|
||||||
|
const parentScope = hookScopeStack.peek()
|
||||||
|
if (!parentScope) {
|
||||||
|
throw new Error(`prism.scope() is called outside of a prism() call.`)
|
||||||
|
}
|
||||||
|
const subScope = parentScope.sub(key)
|
||||||
|
hookScopeStack.push(subScope)
|
||||||
|
const ret = safelyRun(fn, undefined).returnValue
|
||||||
|
hookScopeStack.pop()
|
||||||
|
return ret as $IntentionalAny as T
|
||||||
|
}
|
||||||
|
|
||||||
|
function sub<T>(
|
||||||
|
key: string,
|
||||||
|
fn: () => T,
|
||||||
|
deps: undefined | $IntentionalAny[],
|
||||||
|
): T {
|
||||||
|
return memo(key, () => prism(fn), deps).getValue()
|
||||||
|
}
|
||||||
|
|
||||||
|
function inPrism(): boolean {
|
||||||
|
return !!hookScopeStack.peek()
|
||||||
|
}
|
||||||
|
|
||||||
|
type IPrismFn = {
|
||||||
|
<T>(fn: () => T): IDerivation<T>
|
||||||
|
ref: typeof ref
|
||||||
|
effect: typeof effect
|
||||||
|
memo: typeof memo
|
||||||
|
ensurePrism: typeof ensurePrism
|
||||||
|
state: typeof state
|
||||||
|
scope: typeof scope
|
||||||
|
sub: typeof sub
|
||||||
|
inPrism: typeof inPrism
|
||||||
|
}
|
||||||
|
|
||||||
|
const prism: IPrismFn = (fn) => {
|
||||||
|
return new PrismDerivation(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
prism.ref = ref
|
||||||
|
prism.effect = effect
|
||||||
|
prism.memo = memo
|
||||||
|
prism.ensurePrism = ensurePrism
|
||||||
|
prism.state = state
|
||||||
|
prism.scope = scope
|
||||||
|
prism.sub = sub
|
||||||
|
prism.inPrism = inPrism
|
||||||
|
|
||||||
|
export default prism
|
15
packages/dataverse/src/index.ts
Normal file
15
packages/dataverse/src/index.ts
Normal file
|
@ -0,0 +1,15 @@
|
||||||
|
export {default as Atom, isPointer, val, valueDerivation} from './Atom'
|
||||||
|
export {default as Box} from './Box'
|
||||||
|
export type {IBox} from './Box'
|
||||||
|
export {default as AbstractDerivation} from './derivations/AbstractDerivation'
|
||||||
|
export {default as ConstantDerivation} from './derivations/ConstantDerivation'
|
||||||
|
export {default as DerivationFromSource} from './derivations/DerivationFromSource'
|
||||||
|
export {isDerivation} from './derivations/IDerivation'
|
||||||
|
export type {IDerivation} from './derivations/IDerivation'
|
||||||
|
export {default as iterateAndCountTicks} from './derivations/iterateAndCountTicks'
|
||||||
|
export {default as iterateOver} from './derivations/iterateOver'
|
||||||
|
export {default as prism} from './derivations/prism/prism'
|
||||||
|
export {default as pointer, getPointerParts} from './pointer'
|
||||||
|
export type {Pointer} from './pointer'
|
||||||
|
export {default as Ticker} from './Ticker'
|
||||||
|
export {default as PointerProxy} from './PointerProxy'
|
35
packages/dataverse/src/integration.test.ts
Normal file
35
packages/dataverse/src/integration.test.ts
Normal file
|
@ -0,0 +1,35 @@
|
||||||
|
/**
|
||||||
|
* @jest-environment jsdom
|
||||||
|
*/
|
||||||
|
import Atom, {val} from './Atom'
|
||||||
|
import prism from './derivations/prism/prism'
|
||||||
|
import Ticker from './Ticker'
|
||||||
|
|
||||||
|
describe(`v2 atom`, () => {
|
||||||
|
describe(`identity pointers`, () => {
|
||||||
|
it(`should work`, () => {
|
||||||
|
const data = {foo: 'hi', bar: 0}
|
||||||
|
const a = new Atom(data)
|
||||||
|
const dataP = a.pointer
|
||||||
|
const bar = dataP.bar
|
||||||
|
expect(val(bar)).toEqual(0)
|
||||||
|
|
||||||
|
const d = prism(() => {
|
||||||
|
return val(bar)
|
||||||
|
})
|
||||||
|
expect(d.getValue()).toEqual(0)
|
||||||
|
const ticker = new Ticker()
|
||||||
|
const changes: number[] = []
|
||||||
|
d.changes(ticker).tap((c) => {
|
||||||
|
changes.push(c)
|
||||||
|
})
|
||||||
|
a.setState({...data, bar: 1})
|
||||||
|
ticker.tick()
|
||||||
|
expect(changes).toHaveLength(1)
|
||||||
|
expect(changes[0]).toEqual(1)
|
||||||
|
a.setState({...data, bar: 1})
|
||||||
|
ticker.tick()
|
||||||
|
expect(changes).toHaveLength(1)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
104
packages/dataverse/src/pointer.ts
Normal file
104
packages/dataverse/src/pointer.ts
Normal file
|
@ -0,0 +1,104 @@
|
||||||
|
import type {$IntentionalAny} from './types'
|
||||||
|
|
||||||
|
type PathToProp = Array<string | number>
|
||||||
|
|
||||||
|
type PointerMeta = {
|
||||||
|
root: {}
|
||||||
|
path: (string | number)[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export type UnindexableTypesForPointer =
|
||||||
|
| number
|
||||||
|
| string
|
||||||
|
| boolean
|
||||||
|
| null
|
||||||
|
| void
|
||||||
|
| undefined
|
||||||
|
| Function // eslint-disable-line @typescript-eslint/ban-types
|
||||||
|
|
||||||
|
export type UnindexablePointer = {
|
||||||
|
[K in $IntentionalAny]: Pointer<undefined>
|
||||||
|
}
|
||||||
|
|
||||||
|
const pointerMetaWeakMap = new WeakMap<{}, PointerMeta>()
|
||||||
|
|
||||||
|
export type PointerType<O> = {
|
||||||
|
$$__pointer_type: O
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Pointer<O> = PointerType<O> &
|
||||||
|
(O extends UnindexableTypesForPointer
|
||||||
|
? UnindexablePointer
|
||||||
|
: unknown extends O
|
||||||
|
? UnindexablePointer
|
||||||
|
: O extends (infer T)[]
|
||||||
|
? Pointer<T>[]
|
||||||
|
: O extends {}
|
||||||
|
? {
|
||||||
|
[K in keyof O]-?: Pointer<O[K]>
|
||||||
|
} /*&
|
||||||
|
{[K in string | number]: Pointer<K extends keyof O ? O[K] : undefined>}*/
|
||||||
|
: UnindexablePointer)
|
||||||
|
|
||||||
|
const pointerMetaSymbol = Symbol('pointerMeta')
|
||||||
|
|
||||||
|
const cachedSubPointersWeakMap = new WeakMap<
|
||||||
|
{},
|
||||||
|
Record<string | number, Pointer<unknown>>
|
||||||
|
>()
|
||||||
|
|
||||||
|
const handler = {
|
||||||
|
get(obj: {}, prop: string | typeof pointerMetaSymbol): $IntentionalAny {
|
||||||
|
if (prop === pointerMetaSymbol) return pointerMetaWeakMap.get(obj)!
|
||||||
|
|
||||||
|
let subs = cachedSubPointersWeakMap.get(obj)
|
||||||
|
if (!subs) {
|
||||||
|
subs = {}
|
||||||
|
cachedSubPointersWeakMap.set(obj, subs)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (subs[prop]) return subs[prop]
|
||||||
|
|
||||||
|
const meta = pointerMetaWeakMap.get(obj)!
|
||||||
|
|
||||||
|
const subPointer = pointer({root: meta.root, path: [...meta.path, prop]})
|
||||||
|
subs[prop] = subPointer
|
||||||
|
return subPointer
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getPointerMeta = (
|
||||||
|
p: Pointer<$IntentionalAny> | Pointer<{}> | Pointer<unknown>,
|
||||||
|
): PointerMeta => {
|
||||||
|
// @ts-ignore @todo
|
||||||
|
const meta: PointerMeta = p[
|
||||||
|
pointerMetaSymbol as unknown as $IntentionalAny
|
||||||
|
] as $IntentionalAny
|
||||||
|
return meta
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getPointerParts = (
|
||||||
|
p: Pointer<$IntentionalAny> | Pointer<{}> | Pointer<unknown>,
|
||||||
|
): {root: {}; path: PathToProp} => {
|
||||||
|
const {root, path} = getPointerMeta(p)
|
||||||
|
return {root, path}
|
||||||
|
}
|
||||||
|
|
||||||
|
function pointer<O>({
|
||||||
|
root,
|
||||||
|
path,
|
||||||
|
}: {
|
||||||
|
root: {}
|
||||||
|
path: Array<string | number>
|
||||||
|
}): Pointer<O>
|
||||||
|
function pointer(args: {root: {}; path?: Array<string | number>}) {
|
||||||
|
const meta: PointerMeta = {
|
||||||
|
root: args.root as $IntentionalAny,
|
||||||
|
path: args.path ?? [],
|
||||||
|
}
|
||||||
|
const hiddenObj = {}
|
||||||
|
pointerMetaWeakMap.set(hiddenObj, meta)
|
||||||
|
return new Proxy(hiddenObj, handler) as Pointer<$IntentionalAny>
|
||||||
|
}
|
||||||
|
|
||||||
|
export default pointer
|
1
packages/dataverse/src/setupTestEnv.ts
Normal file
1
packages/dataverse/src/setupTestEnv.ts
Normal file
|
@ -0,0 +1 @@
|
||||||
|
export {}
|
6
packages/dataverse/src/types.ts
Normal file
6
packages/dataverse/src/types.ts
Normal file
|
@ -0,0 +1,6 @@
|
||||||
|
/** For `any`s that aren't meant to stay `any`*/
|
||||||
|
export type $FixMe = any
|
||||||
|
/** For `any`s that we don't care about */
|
||||||
|
export type $IntentionalAny = any
|
||||||
|
|
||||||
|
export type VoidFn = () => void
|
19
packages/dataverse/src/utils/Emitter.test.ts
Normal file
19
packages/dataverse/src/utils/Emitter.test.ts
Normal file
|
@ -0,0 +1,19 @@
|
||||||
|
import Emitter from './Emitter'
|
||||||
|
|
||||||
|
describe.only('DataVerse.Emitter', () => {
|
||||||
|
it('should work', () => {
|
||||||
|
const e: Emitter<string> = new Emitter()
|
||||||
|
e.emit('no one will see this')
|
||||||
|
e.emit('nor this')
|
||||||
|
|
||||||
|
const tappedEvents: string[] = []
|
||||||
|
const untap = e.tappable.tap((payload) => {
|
||||||
|
tappedEvents.push(payload)
|
||||||
|
})
|
||||||
|
e.emit('foo')
|
||||||
|
e.emit('bar')
|
||||||
|
untap()
|
||||||
|
e.emit('baz')
|
||||||
|
expect(tappedEvents).toMatchObject(['foo', 'bar'])
|
||||||
|
})
|
||||||
|
})
|
55
packages/dataverse/src/utils/Emitter.ts
Normal file
55
packages/dataverse/src/utils/Emitter.ts
Normal file
|
@ -0,0 +1,55 @@
|
||||||
|
import Tappable from './Tappable'
|
||||||
|
|
||||||
|
type Tapper<V> = (v: V) => void
|
||||||
|
type Untap = () => void
|
||||||
|
|
||||||
|
export default class Emitter<V> {
|
||||||
|
private _tappers: Map<any, (v: V) => void>
|
||||||
|
private _lastTapperId: number
|
||||||
|
readonly tappable: Tappable<V>
|
||||||
|
private _onNumberOfTappersChangeListener: undefined | ((n: number) => void)
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this._lastTapperId = 0
|
||||||
|
this._tappers = new Map()
|
||||||
|
this.tappable = new Tappable({
|
||||||
|
tapToSource: (cb: Tapper<V>) => {
|
||||||
|
return this._tap(cb)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
_tap(cb: Tapper<V>): Untap {
|
||||||
|
const tapperId = this._lastTapperId++
|
||||||
|
this._tappers.set(tapperId, cb)
|
||||||
|
this._onNumberOfTappersChangeListener &&
|
||||||
|
this._onNumberOfTappersChangeListener(this._tappers.size)
|
||||||
|
return () => {
|
||||||
|
this._removeTapperById(tapperId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_removeTapperById(id: number) {
|
||||||
|
const oldSize = this._tappers.size
|
||||||
|
this._tappers.delete(id)
|
||||||
|
const newSize = this._tappers.size
|
||||||
|
if (oldSize !== newSize) {
|
||||||
|
this._onNumberOfTappersChangeListener &&
|
||||||
|
this._onNumberOfTappersChangeListener(this._tappers.size)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
emit(payload: V) {
|
||||||
|
this._tappers.forEach((cb) => {
|
||||||
|
cb(payload)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
hasTappers() {
|
||||||
|
return this._tappers.size !== 0
|
||||||
|
}
|
||||||
|
|
||||||
|
onNumberOfTappersChange(cb: (n: number) => void) {
|
||||||
|
this._onNumberOfTappersChangeListener = cb
|
||||||
|
}
|
||||||
|
}
|
56
packages/dataverse/src/utils/EventEmitter.ts
Normal file
56
packages/dataverse/src/utils/EventEmitter.ts
Normal file
|
@ -0,0 +1,56 @@
|
||||||
|
import forEach from 'lodash-es/forEach'
|
||||||
|
import without from 'lodash-es/without'
|
||||||
|
import type {$FixMe} from '../types'
|
||||||
|
|
||||||
|
type Listener = (v: $FixMe) => void
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A simple barebones event emitter
|
||||||
|
*/
|
||||||
|
export default class EventEmitter {
|
||||||
|
_listenersByType: {[eventName: string]: Array<Listener>}
|
||||||
|
constructor() {
|
||||||
|
this._listenersByType = {}
|
||||||
|
}
|
||||||
|
|
||||||
|
addEventListener(eventName: string, listener: Listener) {
|
||||||
|
const listeners =
|
||||||
|
this._listenersByType[eventName] ||
|
||||||
|
(this._listenersByType[eventName] = [])
|
||||||
|
|
||||||
|
listeners.push(listener)
|
||||||
|
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
removeEventListener(eventName: string, listener: Listener) {
|
||||||
|
const listeners = this._listenersByType[eventName]
|
||||||
|
if (listeners) {
|
||||||
|
const newListeners = without(listeners, listener)
|
||||||
|
if (newListeners.length === 0) {
|
||||||
|
delete this._listenersByType[eventName]
|
||||||
|
} else {
|
||||||
|
this._listenersByType[eventName] = newListeners
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
emit(eventName: string, payload: unknown) {
|
||||||
|
const listeners = this.getListenersFor(eventName)
|
||||||
|
if (listeners) {
|
||||||
|
forEach(listeners, (listener) => {
|
||||||
|
listener(payload)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getListenersFor(eventName: string) {
|
||||||
|
return this._listenersByType[eventName]
|
||||||
|
}
|
||||||
|
|
||||||
|
hasListenersFor(eventName: string) {
|
||||||
|
return this.getListenersFor(eventName) ? true : false
|
||||||
|
}
|
||||||
|
}
|
133
packages/dataverse/src/utils/PathBasedReducer.ts
Normal file
133
packages/dataverse/src/utils/PathBasedReducer.ts
Normal file
|
@ -0,0 +1,133 @@
|
||||||
|
export type PathBasedReducer<S, ReturnType> = {
|
||||||
|
<
|
||||||
|
A0 extends keyof S,
|
||||||
|
A1 extends keyof S[A0],
|
||||||
|
A2 extends keyof S[A0][A1],
|
||||||
|
A3 extends keyof S[A0][A1][A2],
|
||||||
|
A4 extends keyof S[A0][A1][A2][A3],
|
||||||
|
A5 extends keyof S[A0][A1][A2][A3][A4],
|
||||||
|
A6 extends keyof S[A0][A1][A2][A3][A4][A5],
|
||||||
|
A7 extends keyof S[A0][A1][A2][A3][A4][A5][A6],
|
||||||
|
A8 extends keyof S[A0][A1][A2][A3][A4][A5][A6][A7],
|
||||||
|
A9 extends keyof S[A0][A1][A2][A3][A4][A5][A6][A7][A8],
|
||||||
|
A10 extends keyof S[A0][A1][A2][A3][A4][A5][A6][A7][A8][A9],
|
||||||
|
>(
|
||||||
|
addr: [A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10],
|
||||||
|
reducer: (
|
||||||
|
d: S[A0][A1][A2][A3][A4][A5][A6][A7][A8][A9][A10],
|
||||||
|
) => S[A0][A1][A2][A3][A4][A5][A6][A7][A8][A9][A10],
|
||||||
|
): ReturnType
|
||||||
|
|
||||||
|
<
|
||||||
|
A0 extends keyof S,
|
||||||
|
A1 extends keyof S[A0],
|
||||||
|
A2 extends keyof S[A0][A1],
|
||||||
|
A3 extends keyof S[A0][A1][A2],
|
||||||
|
A4 extends keyof S[A0][A1][A2][A3],
|
||||||
|
A5 extends keyof S[A0][A1][A2][A3][A4],
|
||||||
|
A6 extends keyof S[A0][A1][A2][A3][A4][A5],
|
||||||
|
A7 extends keyof S[A0][A1][A2][A3][A4][A5][A6],
|
||||||
|
A8 extends keyof S[A0][A1][A2][A3][A4][A5][A6][A7],
|
||||||
|
A9 extends keyof S[A0][A1][A2][A3][A4][A5][A6][A7][A8],
|
||||||
|
>(
|
||||||
|
addr: [A0, A1, A2, A3, A4, A5, A6, A7, A8, A9],
|
||||||
|
reducer: (
|
||||||
|
d: S[A0][A1][A2][A3][A4][A5][A6][A7][A8][A9],
|
||||||
|
) => S[A0][A1][A2][A3][A4][A5][A6][A7][A8][A9],
|
||||||
|
): ReturnType
|
||||||
|
|
||||||
|
<
|
||||||
|
A0 extends keyof S,
|
||||||
|
A1 extends keyof S[A0],
|
||||||
|
A2 extends keyof S[A0][A1],
|
||||||
|
A3 extends keyof S[A0][A1][A2],
|
||||||
|
A4 extends keyof S[A0][A1][A2][A3],
|
||||||
|
A5 extends keyof S[A0][A1][A2][A3][A4],
|
||||||
|
A6 extends keyof S[A0][A1][A2][A3][A4][A5],
|
||||||
|
A7 extends keyof S[A0][A1][A2][A3][A4][A5][A6],
|
||||||
|
A8 extends keyof S[A0][A1][A2][A3][A4][A5][A6][A7],
|
||||||
|
>(
|
||||||
|
addr: [A0, A1, A2, A3, A4, A5, A6, A7, A8],
|
||||||
|
reducer: (
|
||||||
|
d: S[A0][A1][A2][A3][A4][A5][A6][A7][A8],
|
||||||
|
) => S[A0][A1][A2][A3][A4][A5][A6][A7][A8],
|
||||||
|
): ReturnType
|
||||||
|
|
||||||
|
<
|
||||||
|
A0 extends keyof S,
|
||||||
|
A1 extends keyof S[A0],
|
||||||
|
A2 extends keyof S[A0][A1],
|
||||||
|
A3 extends keyof S[A0][A1][A2],
|
||||||
|
A4 extends keyof S[A0][A1][A2][A3],
|
||||||
|
A5 extends keyof S[A0][A1][A2][A3][A4],
|
||||||
|
A6 extends keyof S[A0][A1][A2][A3][A4][A5],
|
||||||
|
A7 extends keyof S[A0][A1][A2][A3][A4][A5][A6],
|
||||||
|
>(
|
||||||
|
addr: [A0, A1, A2, A3, A4, A5, A6, A7],
|
||||||
|
reducer: (
|
||||||
|
d: S[A0][A1][A2][A3][A4][A5][A6][A7],
|
||||||
|
) => S[A0][A1][A2][A3][A4][A5][A6][A7],
|
||||||
|
): ReturnType
|
||||||
|
|
||||||
|
<
|
||||||
|
A0 extends keyof S,
|
||||||
|
A1 extends keyof S[A0],
|
||||||
|
A2 extends keyof S[A0][A1],
|
||||||
|
A3 extends keyof S[A0][A1][A2],
|
||||||
|
A4 extends keyof S[A0][A1][A2][A3],
|
||||||
|
A5 extends keyof S[A0][A1][A2][A3][A4],
|
||||||
|
A6 extends keyof S[A0][A1][A2][A3][A4][A5],
|
||||||
|
>(
|
||||||
|
addr: [A0, A1, A2, A3, A4, A5, A6],
|
||||||
|
reducer: (
|
||||||
|
d: S[A0][A1][A2][A3][A4][A5][A6],
|
||||||
|
) => S[A0][A1][A2][A3][A4][A5][A6],
|
||||||
|
): ReturnType
|
||||||
|
|
||||||
|
<
|
||||||
|
A0 extends keyof S,
|
||||||
|
A1 extends keyof S[A0],
|
||||||
|
A2 extends keyof S[A0][A1],
|
||||||
|
A3 extends keyof S[A0][A1][A2],
|
||||||
|
A4 extends keyof S[A0][A1][A2][A3],
|
||||||
|
A5 extends keyof S[A0][A1][A2][A3][A4],
|
||||||
|
>(
|
||||||
|
addr: [A0, A1, A2, A3, A4, A5],
|
||||||
|
reducer: (d: S[A0][A1][A2][A3][A4][A5]) => S[A0][A1][A2][A3][A4][A5],
|
||||||
|
): ReturnType
|
||||||
|
|
||||||
|
<
|
||||||
|
A0 extends keyof S,
|
||||||
|
A1 extends keyof S[A0],
|
||||||
|
A2 extends keyof S[A0][A1],
|
||||||
|
A3 extends keyof S[A0][A1][A2],
|
||||||
|
A4 extends keyof S[A0][A1][A2][A3],
|
||||||
|
>(
|
||||||
|
addr: [A0, A1, A2, A3, A4],
|
||||||
|
reducer: (d: S[A0][A1][A2][A3][A4]) => S[A0][A1][A2][A3][A4],
|
||||||
|
): ReturnType
|
||||||
|
|
||||||
|
<
|
||||||
|
A0 extends keyof S,
|
||||||
|
A1 extends keyof S[A0],
|
||||||
|
A2 extends keyof S[A0][A1],
|
||||||
|
A3 extends keyof S[A0][A1][A2],
|
||||||
|
>(
|
||||||
|
addr: [A0, A1, A2, A3],
|
||||||
|
reducer: (d: S[A0][A1][A2][A3]) => S[A0][A1][A2][A3],
|
||||||
|
): ReturnType
|
||||||
|
|
||||||
|
<A0 extends keyof S, A1 extends keyof S[A0], A2 extends keyof S[A0][A1]>(
|
||||||
|
addr: [A0, A1, A2],
|
||||||
|
reducer: (d: S[A0][A1][A2]) => S[A0][A1][A2],
|
||||||
|
): ReturnType
|
||||||
|
|
||||||
|
<A0 extends keyof S, A1 extends keyof S[A0]>(
|
||||||
|
addr: [A0, A1],
|
||||||
|
reducer: (d: S[A0][A1]) => S[A0][A1],
|
||||||
|
): ReturnType
|
||||||
|
|
||||||
|
<A0 extends keyof S>(addr: [A0], reducer: (d: S[A0]) => S[A0]): ReturnType
|
||||||
|
|
||||||
|
(addr: undefined[], reducer: (d: S) => S): ReturnType
|
||||||
|
}
|
33
packages/dataverse/src/utils/Stack.ts
Normal file
33
packages/dataverse/src/utils/Stack.ts
Normal file
|
@ -0,0 +1,33 @@
|
||||||
|
interface Node<Data> {
|
||||||
|
next: undefined | Node<Data>
|
||||||
|
data: Data
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Just a simple LinkedList
|
||||||
|
*/
|
||||||
|
export default class Stack<Data> {
|
||||||
|
_head: undefined | Node<Data>
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this._head = undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
peek() {
|
||||||
|
return this._head && this._head.data
|
||||||
|
}
|
||||||
|
|
||||||
|
pop() {
|
||||||
|
const head = this._head
|
||||||
|
if (!head) {
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
this._head = head.next
|
||||||
|
return head.data
|
||||||
|
}
|
||||||
|
|
||||||
|
push(data: Data) {
|
||||||
|
const node = {next: this._head, data}
|
||||||
|
this._head = node
|
||||||
|
}
|
||||||
|
}
|
91
packages/dataverse/src/utils/Tappable.ts
Normal file
91
packages/dataverse/src/utils/Tappable.ts
Normal file
|
@ -0,0 +1,91 @@
|
||||||
|
type Untap = () => void
|
||||||
|
type UntapFromSource = () => void
|
||||||
|
|
||||||
|
interface IProps<V> {
|
||||||
|
tapToSource: (cb: (payload: V) => void) => UntapFromSource
|
||||||
|
}
|
||||||
|
|
||||||
|
type Listener<V> = ((v: V) => void) | (() => void)
|
||||||
|
|
||||||
|
export default class Tappable<V> {
|
||||||
|
private _props: IProps<V>
|
||||||
|
private _tappers: Map<number, {bivarianceHack(v: V): void}['bivarianceHack']>
|
||||||
|
private _untapFromSource: null | UntapFromSource
|
||||||
|
private _lastTapperId: number
|
||||||
|
private _untapFromSourceTimeout: null | NodeJS.Timer = null
|
||||||
|
|
||||||
|
constructor(props: IProps<V>) {
|
||||||
|
this._lastTapperId = 0
|
||||||
|
this._untapFromSource = null
|
||||||
|
this._props = props
|
||||||
|
this._tappers = new Map()
|
||||||
|
}
|
||||||
|
|
||||||
|
private _check() {
|
||||||
|
if (this._untapFromSource) {
|
||||||
|
if (this._tappers.size === 0) {
|
||||||
|
this._scheduleToUntapFromSource()
|
||||||
|
/*
|
||||||
|
* this._untapFromSource()
|
||||||
|
* this._untapFromSource = null
|
||||||
|
*/
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (this._tappers.size !== 0) {
|
||||||
|
this._untapFromSource = this._props.tapToSource(this._cb)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private _scheduleToUntapFromSource() {
|
||||||
|
if (this._untapFromSourceTimeout !== null) return
|
||||||
|
this._untapFromSourceTimeout = setTimeout(() => {
|
||||||
|
this._untapFromSourceTimeout = null
|
||||||
|
if (this._tappers.size === 0) {
|
||||||
|
this._untapFromSource!()
|
||||||
|
|
||||||
|
this._untapFromSource = null
|
||||||
|
}
|
||||||
|
}, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
private _cb: any = (arg: any): void => {
|
||||||
|
this._tappers.forEach((cb) => {
|
||||||
|
cb(arg)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
tap(cb: Listener<V>): Untap {
|
||||||
|
const tapperId = this._lastTapperId++
|
||||||
|
this._tappers.set(tapperId, cb)
|
||||||
|
this._check()
|
||||||
|
return () => {
|
||||||
|
this._removeTapperById(tapperId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* tapImmediate(cb: Listener<V>): Untap {
|
||||||
|
* const ret = this.tap(cb)
|
||||||
|
* return ret
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
|
||||||
|
private _removeTapperById(id: number) {
|
||||||
|
this._tappers.delete(id)
|
||||||
|
this._check()
|
||||||
|
}
|
||||||
|
|
||||||
|
// /**
|
||||||
|
// * @deprecated
|
||||||
|
// */
|
||||||
|
// map<T>(transform: {bivarianceHack(v: V): T}['bivarianceHack']): Tappable<T> {
|
||||||
|
// return new Tappable({
|
||||||
|
// tapToSource: (cb: (v: T) => void) => {
|
||||||
|
// return this.tap((v: $IntentionalAny) => {
|
||||||
|
// return cb(transform(v))
|
||||||
|
// })
|
||||||
|
// },
|
||||||
|
// })
|
||||||
|
// }
|
||||||
|
}
|
12
packages/dataverse/src/utils/typeTestUtils.ts
Normal file
12
packages/dataverse/src/utils/typeTestUtils.ts
Normal file
|
@ -0,0 +1,12 @@
|
||||||
|
import type {$IntentionalAny} from '../types'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Useful in type tests, such as: const a: SomeType = _any
|
||||||
|
*/
|
||||||
|
export const _any: $IntentionalAny = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Useful in typeTests. If you want to ensure that value v follows type V,
|
||||||
|
* just write `expectType<V>(v)`
|
||||||
|
*/
|
||||||
|
export const expectType = <T extends unknown>(v: T): T => v
|
42
packages/dataverse/src/utils/updateDeep.ts
Normal file
42
packages/dataverse/src/utils/updateDeep.ts
Normal file
|
@ -0,0 +1,42 @@
|
||||||
|
import type {$FixMe, $IntentionalAny} from '../types'
|
||||||
|
|
||||||
|
export default function updateDeep<S>(
|
||||||
|
state: S,
|
||||||
|
path: (string | number | undefined)[],
|
||||||
|
reducer: (...args: $IntentionalAny[]) => $IntentionalAny,
|
||||||
|
): S {
|
||||||
|
if (path.length === 0) return reducer(state)
|
||||||
|
return hoop(state, path as $IntentionalAny, reducer)
|
||||||
|
}
|
||||||
|
|
||||||
|
const hoop = (
|
||||||
|
s: $FixMe,
|
||||||
|
path: (string | number)[],
|
||||||
|
reducer: $FixMe,
|
||||||
|
): $FixMe => {
|
||||||
|
if (path.length === 0) {
|
||||||
|
return reducer(s)
|
||||||
|
}
|
||||||
|
if (Array.isArray(s)) {
|
||||||
|
let [index, ...restOfPath] = path
|
||||||
|
index = parseInt(String(index), 10)
|
||||||
|
if (isNaN(index)) index = 0
|
||||||
|
const oldVal = s[index]
|
||||||
|
const newVal = hoop(oldVal, restOfPath, reducer)
|
||||||
|
if (oldVal === newVal) return s
|
||||||
|
const newS = [...s]
|
||||||
|
newS.splice(index, 1, newVal)
|
||||||
|
return newS
|
||||||
|
} else if (typeof s === 'object' && s !== null) {
|
||||||
|
const [key, ...restOfPath] = path
|
||||||
|
const oldVal = s[key]
|
||||||
|
const newVal = hoop(oldVal, restOfPath, reducer)
|
||||||
|
if (oldVal === newVal) return s
|
||||||
|
const newS = {...s, [key]: newVal}
|
||||||
|
return newS
|
||||||
|
} else {
|
||||||
|
const [key, ...restOfPath] = path
|
||||||
|
|
||||||
|
return {[key]: hoop(undefined, restOfPath, reducer)}
|
||||||
|
}
|
||||||
|
}
|
12
packages/dataverse/tsconfig.json
Normal file
12
packages/dataverse/tsconfig.json
Normal file
|
@ -0,0 +1,12 @@
|
||||||
|
{
|
||||||
|
"extends": "../../tsconfig.base.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"outDir": "dist",
|
||||||
|
"lib": ["ESNext", "DOM"],
|
||||||
|
"rootDir": "src",
|
||||||
|
"types": ["jest", "node"],
|
||||||
|
"emitDeclarationOnly": false,
|
||||||
|
"composite": true
|
||||||
|
},
|
||||||
|
"include": ["./src/**/*"]
|
||||||
|
}
|
1
packages/dataverse2/.babelrc.js
Normal file
1
packages/dataverse2/.babelrc.js
Normal file
|
@ -0,0 +1 @@
|
||||||
|
module.exports = {}
|
1
packages/dataverse2/.gitignore
vendored
Normal file
1
packages/dataverse2/.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
||||||
|
/dist
|
203
packages/dataverse2/LICENSE
Normal file
203
packages/dataverse2/LICENSE
Normal file
|
@ -0,0 +1,203 @@
|
||||||
|
|
||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
|
|
27
packages/dataverse2/package.json
Normal file
27
packages/dataverse2/package.json
Normal file
|
@ -0,0 +1,27 @@
|
||||||
|
{
|
||||||
|
"name": "@theatre/dataverse2",
|
||||||
|
"version": "1.0.0-dev",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"author": {
|
||||||
|
"name": "Aria Minaei",
|
||||||
|
"email": "aria@theatrejs.com",
|
||||||
|
"url": "https://github.com/AriaMinaei"
|
||||||
|
},
|
||||||
|
"source": "src/index.ts",
|
||||||
|
"main": "dist/index.js",
|
||||||
|
"types": "dist/index.d.ts",
|
||||||
|
"scripts": {
|
||||||
|
"typecheck": "yarn run _declarations:emit",
|
||||||
|
"_declarations:emit": "tsc --build ./tsconfig.json"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/jest": "^26.0.23",
|
||||||
|
"@types/lodash-es": "^4.17.4",
|
||||||
|
"@types/node": "^15.6.2",
|
||||||
|
"@types/react": "^17.0.9",
|
||||||
|
"typescript": "^4.3.2"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"lodash-es": "^4.17.21"
|
||||||
|
}
|
||||||
|
}
|
216
packages/dataverse2/src/Atom.ts
Normal file
216
packages/dataverse2/src/Atom.ts
Normal file
|
@ -0,0 +1,216 @@
|
||||||
|
import get from 'lodash-es/get'
|
||||||
|
import isPlainObject from 'lodash-es/isPlainObject'
|
||||||
|
import last from 'lodash-es/last'
|
||||||
|
import DerivationFromSource from './derivations/DerivationFromSource'
|
||||||
|
import type {IDerivation} from './derivations/IDerivation'
|
||||||
|
import {isDerivation} from './derivations/IDerivation'
|
||||||
|
import type {Pointer, PointerType} from './pointer'
|
||||||
|
import pointer, {getPointerMeta} from './pointer'
|
||||||
|
import type {$FixMe, $IntentionalAny} from './types'
|
||||||
|
import type {PathBasedReducer} from './utils/PathBasedReducer'
|
||||||
|
import updateDeep from './utils/updateDeep'
|
||||||
|
|
||||||
|
type Listener = (newVal: unknown) => void
|
||||||
|
|
||||||
|
enum ValueTypes {
|
||||||
|
Dict,
|
||||||
|
Array,
|
||||||
|
Other,
|
||||||
|
}
|
||||||
|
|
||||||
|
const getTypeOfValue = (v: unknown): ValueTypes => {
|
||||||
|
if (Array.isArray(v)) return ValueTypes.Array
|
||||||
|
if (isPlainObject(v)) return ValueTypes.Dict
|
||||||
|
return ValueTypes.Other
|
||||||
|
}
|
||||||
|
|
||||||
|
const getKeyOfValue = (
|
||||||
|
v: unknown,
|
||||||
|
key: string | number,
|
||||||
|
vType: ValueTypes = getTypeOfValue(v),
|
||||||
|
): unknown => {
|
||||||
|
if (vType === ValueTypes.Dict && typeof key === 'string') {
|
||||||
|
return (v as $IntentionalAny)[key]
|
||||||
|
} else if (vType === ValueTypes.Array && isValidArrayIndex(key)) {
|
||||||
|
return (v as $IntentionalAny)[key]
|
||||||
|
} else {
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const isValidArrayIndex = (key: string | number): boolean => {
|
||||||
|
const inNumber = typeof key === 'number' ? key : parseInt(key, 10)
|
||||||
|
return (
|
||||||
|
!isNaN(inNumber) &&
|
||||||
|
inNumber >= 0 &&
|
||||||
|
inNumber < Infinity &&
|
||||||
|
(inNumber | 0) === inNumber
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
class Scope {
|
||||||
|
children: Map<string | number, Scope> = new Map()
|
||||||
|
identityChangeListeners: Set<Listener> = new Set()
|
||||||
|
constructor(
|
||||||
|
readonly _parent: undefined | Scope,
|
||||||
|
readonly _path: (string | number)[],
|
||||||
|
) {}
|
||||||
|
|
||||||
|
addIdentityChangeListener(cb: Listener) {
|
||||||
|
this.identityChangeListeners.add(cb)
|
||||||
|
}
|
||||||
|
|
||||||
|
removeIdentityChangeListener(cb: Listener) {
|
||||||
|
this.identityChangeListeners.delete(cb)
|
||||||
|
this._checkForGC()
|
||||||
|
}
|
||||||
|
|
||||||
|
removeChild(key: string | number) {
|
||||||
|
this.children.delete(key)
|
||||||
|
this._checkForGC()
|
||||||
|
}
|
||||||
|
|
||||||
|
getChild(key: string | number) {
|
||||||
|
return this.children.get(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
getOrCreateChild(key: string | number) {
|
||||||
|
let child = this.children.get(key)
|
||||||
|
if (!child) {
|
||||||
|
child = child = new Scope(this, this._path.concat([key]))
|
||||||
|
this.children.set(key, child)
|
||||||
|
}
|
||||||
|
return child
|
||||||
|
}
|
||||||
|
|
||||||
|
_checkForGC() {
|
||||||
|
if (this.identityChangeListeners.size > 0) return
|
||||||
|
if (this.children.size > 0) return
|
||||||
|
|
||||||
|
if (this._parent) {
|
||||||
|
this._parent.removeChild(last(this._path) as string | number)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default class Atom<State extends {}> {
|
||||||
|
private _currentState: State
|
||||||
|
private readonly _rootScope: Scope
|
||||||
|
readonly pointer: Pointer<State>
|
||||||
|
|
||||||
|
constructor(initialState: State) {
|
||||||
|
this._currentState = initialState
|
||||||
|
this._rootScope = new Scope(undefined, [])
|
||||||
|
this.pointer = pointer({root: this as $FixMe, path: []})
|
||||||
|
}
|
||||||
|
|
||||||
|
setState(newState: State) {
|
||||||
|
const oldState = this._currentState
|
||||||
|
this._currentState = newState
|
||||||
|
|
||||||
|
this._checkUpdates(this._rootScope, oldState, newState)
|
||||||
|
}
|
||||||
|
|
||||||
|
getState() {
|
||||||
|
return this._currentState
|
||||||
|
}
|
||||||
|
|
||||||
|
getIn(path: (string | number)[]): unknown {
|
||||||
|
return path.length === 0 ? this.getState() : get(this.getState(), path)
|
||||||
|
}
|
||||||
|
|
||||||
|
reduceState: PathBasedReducer<State, State> = (
|
||||||
|
path: $IntentionalAny[],
|
||||||
|
reducer: $IntentionalAny,
|
||||||
|
) => {
|
||||||
|
const newState = updateDeep(this.getState(), path, reducer)
|
||||||
|
this.setState(newState)
|
||||||
|
return newState
|
||||||
|
}
|
||||||
|
|
||||||
|
setIn(path: $FixMe[], val: $FixMe) {
|
||||||
|
return this.reduceState(path, () => val)
|
||||||
|
}
|
||||||
|
|
||||||
|
private _checkUpdates(scope: Scope, oldState: unknown, newState: unknown) {
|
||||||
|
if (oldState === newState) return
|
||||||
|
scope.identityChangeListeners.forEach((cb) => cb(newState))
|
||||||
|
|
||||||
|
if (scope.children.size === 0) return
|
||||||
|
const oldValueType = getTypeOfValue(oldState)
|
||||||
|
const newValueType = getTypeOfValue(newState)
|
||||||
|
|
||||||
|
if (oldValueType === ValueTypes.Other && oldValueType === newValueType)
|
||||||
|
return
|
||||||
|
|
||||||
|
scope.children.forEach((childScope, childKey) => {
|
||||||
|
const oldChildVal = getKeyOfValue(oldState, childKey, oldValueType)
|
||||||
|
const newChildVal = getKeyOfValue(newState, childKey, newValueType)
|
||||||
|
this._checkUpdates(childScope, oldChildVal, newChildVal)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
private _getOrCreateScopeForPath(path: (string | number)[]): Scope {
|
||||||
|
let curScope = this._rootScope
|
||||||
|
for (const pathEl of path) {
|
||||||
|
curScope = curScope.getOrCreateChild(pathEl)
|
||||||
|
}
|
||||||
|
return curScope
|
||||||
|
}
|
||||||
|
|
||||||
|
onPathValueChange(path: (string | number)[], cb: (v: unknown) => void) {
|
||||||
|
const scope = this._getOrCreateScopeForPath(path)
|
||||||
|
scope.identityChangeListeners.add(cb)
|
||||||
|
const untap = () => {
|
||||||
|
scope.identityChangeListeners.delete(cb)
|
||||||
|
}
|
||||||
|
return untap
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const identityDerivationWeakMap = new WeakMap<{}, IDerivation<unknown>>()
|
||||||
|
|
||||||
|
export const valueDerivation = <P extends PointerType<$IntentionalAny>>(
|
||||||
|
pointer: P,
|
||||||
|
): IDerivation<P extends PointerType<infer T> ? T : void> => {
|
||||||
|
const meta = getPointerMeta(pointer)
|
||||||
|
|
||||||
|
let derivation = identityDerivationWeakMap.get(meta)
|
||||||
|
if (!derivation) {
|
||||||
|
const root = meta.root
|
||||||
|
if (!(root instanceof Atom)) {
|
||||||
|
throw new Error(
|
||||||
|
`Cannot run valueDerivation on a pointer whose root is not an Atom`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
const {path} = meta
|
||||||
|
derivation = new DerivationFromSource<$IntentionalAny>(
|
||||||
|
(listener) => root.onPathValueChange(path, listener),
|
||||||
|
() => root.getIn(path),
|
||||||
|
)
|
||||||
|
identityDerivationWeakMap.set(meta, derivation)
|
||||||
|
}
|
||||||
|
return derivation as $IntentionalAny
|
||||||
|
}
|
||||||
|
|
||||||
|
export const val = <P>(
|
||||||
|
pointerOrDerivationOrPlainValue: P,
|
||||||
|
): P extends PointerType<infer T>
|
||||||
|
? T
|
||||||
|
: P extends IDerivation<infer T>
|
||||||
|
? T
|
||||||
|
: unknown => {
|
||||||
|
if (isPointer(pointerOrDerivationOrPlainValue)) {
|
||||||
|
return valueDerivation(
|
||||||
|
pointerOrDerivationOrPlainValue,
|
||||||
|
).getValue() as $IntentionalAny
|
||||||
|
} else if (isDerivation(pointerOrDerivationOrPlainValue)) {
|
||||||
|
return pointerOrDerivationOrPlainValue.getValue() as $IntentionalAny
|
||||||
|
} else {
|
||||||
|
return pointerOrDerivationOrPlainValue as $IntentionalAny
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const isPointer = (p: $IntentionalAny): p is Pointer<unknown> => {
|
||||||
|
return p && p.$pointerMeta ? true : false
|
||||||
|
}
|
33
packages/dataverse2/src/Box.ts
Normal file
33
packages/dataverse2/src/Box.ts
Normal file
|
@ -0,0 +1,33 @@
|
||||||
|
import DerivationFromSource from './derivations/DerivationFromSource'
|
||||||
|
import type {IDerivation} from './derivations/IDerivation'
|
||||||
|
import Emitter from './utils/Emitter'
|
||||||
|
export interface IBox<V> {
|
||||||
|
set(v: V): void
|
||||||
|
get(): V
|
||||||
|
derivation: IDerivation<V>
|
||||||
|
}
|
||||||
|
|
||||||
|
export default class Box<V> implements IBox<V> {
|
||||||
|
private _publicDerivation: IDerivation<V>
|
||||||
|
private _emitter = new Emitter<V>()
|
||||||
|
|
||||||
|
constructor(protected _value: V) {
|
||||||
|
this._publicDerivation = new DerivationFromSource(
|
||||||
|
(listener) => this._emitter.tappable.tap(listener),
|
||||||
|
this.get.bind(this),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
set(v: V) {
|
||||||
|
this._value = v
|
||||||
|
this._emitter.emit(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
get() {
|
||||||
|
return this._value
|
||||||
|
}
|
||||||
|
|
||||||
|
get derivation() {
|
||||||
|
return this._publicDerivation
|
||||||
|
}
|
||||||
|
}
|
84
packages/dataverse2/src/Ticker.ts
Normal file
84
packages/dataverse2/src/Ticker.ts
Normal file
|
@ -0,0 +1,84 @@
|
||||||
|
type ICallback = (t: number) => void
|
||||||
|
|
||||||
|
export default class Ticker {
|
||||||
|
private _scheduledForThisOrNextTick: Set<ICallback>
|
||||||
|
private _scheduledForNextTick: Set<ICallback>
|
||||||
|
private _timeAtCurrentTick: number
|
||||||
|
private _ticking: boolean = false
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this._scheduledForThisOrNextTick = new Set()
|
||||||
|
this._scheduledForNextTick = new Set()
|
||||||
|
this._timeAtCurrentTick = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers for fn to be called either on this tick or the next tick.
|
||||||
|
*
|
||||||
|
* If registerSideEffect() is called while Ticker.tick() is running, the
|
||||||
|
* side effect _will_ be called within the running tick. If you don't want this
|
||||||
|
* behavior, you can use registerSideEffectForNextTick().
|
||||||
|
*
|
||||||
|
* Note that fn will be added to a Set(). Which means, if you call registerSideEffect(fn)
|
||||||
|
* with the same fn twice in a single tick, it'll only run once.
|
||||||
|
*/
|
||||||
|
onThisOrNextTick(fn: ICallback) {
|
||||||
|
this._scheduledForThisOrNextTick.add(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers a side effect to be called on the next tick.
|
||||||
|
*
|
||||||
|
* @see Ticker:onThisOrNextTick()
|
||||||
|
*/
|
||||||
|
onNextTick(fn: ICallback) {
|
||||||
|
this._scheduledForNextTick.add(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
offThisOrNextTick(fn: ICallback) {
|
||||||
|
this._scheduledForThisOrNextTick.delete(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
offNextTick(fn: ICallback) {
|
||||||
|
this._scheduledForNextTick.delete(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
get time() {
|
||||||
|
if (this._ticking) {
|
||||||
|
return this._timeAtCurrentTick
|
||||||
|
} else return performance.now()
|
||||||
|
}
|
||||||
|
|
||||||
|
tick(t: number = performance.now()) {
|
||||||
|
this._ticking = true
|
||||||
|
this._timeAtCurrentTick = t
|
||||||
|
this._scheduledForNextTick.forEach((v) =>
|
||||||
|
this._scheduledForThisOrNextTick.add(v),
|
||||||
|
)
|
||||||
|
this._scheduledForNextTick.clear()
|
||||||
|
this._tick(0)
|
||||||
|
this._ticking = false
|
||||||
|
}
|
||||||
|
|
||||||
|
private _tick(iterationNumber: number): void {
|
||||||
|
const time = this.time
|
||||||
|
|
||||||
|
if (iterationNumber > 10) {
|
||||||
|
console.warn('_tick() recursing for 10 times')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (iterationNumber > 100) {
|
||||||
|
throw new Error(`Maximum recursion limit for _tick()`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const oldSet = this._scheduledForThisOrNextTick
|
||||||
|
this._scheduledForThisOrNextTick = new Set()
|
||||||
|
oldSet.forEach((fn) => {
|
||||||
|
fn(time)
|
||||||
|
})
|
||||||
|
|
||||||
|
if (this._scheduledForThisOrNextTick.size > 0) {
|
||||||
|
return this._tick(iterationNumber + 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
24
packages/dataverse2/src/atom.typeTest.ts
Normal file
24
packages/dataverse2/src/atom.typeTest.ts
Normal file
|
@ -0,0 +1,24 @@
|
||||||
|
import Atom, {val} from './Atom'
|
||||||
|
import {expectType, _any} from './utils/typeTestUtils'
|
||||||
|
;() => {
|
||||||
|
const p = new Atom<{foo: string; bar: number; optional?: boolean}>(_any)
|
||||||
|
.pointer
|
||||||
|
expectType<string>(val(p.foo))
|
||||||
|
// @ts-expect-error TypeTest
|
||||||
|
expectType<number>(val(p.foo))
|
||||||
|
|
||||||
|
expectType<number>(val(p.bar))
|
||||||
|
// @ts-expect-error TypeTest
|
||||||
|
expectType<string>(val(p.bar))
|
||||||
|
|
||||||
|
// @ts-expect-error TypeTest
|
||||||
|
expectType<{}>(val(p.nonExistent))
|
||||||
|
|
||||||
|
expectType<undefined | boolean>(val(p.optional))
|
||||||
|
// @ts-expect-error TypeTest
|
||||||
|
expectType<boolean>(val(p.optional))
|
||||||
|
// @ts-expect-error TypeTest
|
||||||
|
expectType<undefined>(val(p.optional))
|
||||||
|
// @ts-expect-error TypeTest
|
||||||
|
expectType<undefined | string>(val(p.optional))
|
||||||
|
}
|
199
packages/dataverse2/src/derivations/AbstractDerivation.ts
Normal file
199
packages/dataverse2/src/derivations/AbstractDerivation.ts
Normal file
|
@ -0,0 +1,199 @@
|
||||||
|
import type {$IntentionalAny} from '../types'
|
||||||
|
import type Tappable from '../utils/Tappable'
|
||||||
|
import DerivationEmitter from './DerivationEmitter'
|
||||||
|
import flatMap from './flatMap'
|
||||||
|
import type {GraphNode, IDerivation} from './IDerivation'
|
||||||
|
import map from './map'
|
||||||
|
import {
|
||||||
|
reportResolutionEnd,
|
||||||
|
reportResolutionStart,
|
||||||
|
} from './prism/discoveryMechanism'
|
||||||
|
|
||||||
|
export default abstract class AbstractDerivation<V> implements IDerivation<V> {
|
||||||
|
readonly isDerivation: true = true
|
||||||
|
private _didMarkDependentsAsStale: boolean = false
|
||||||
|
private _isHot: boolean = false
|
||||||
|
|
||||||
|
private _isFresh: boolean = false
|
||||||
|
protected _lastValue: undefined | V = undefined
|
||||||
|
|
||||||
|
protected _dependents: Set<GraphNode> = new Set()
|
||||||
|
protected _dependencies: Set<IDerivation<$IntentionalAny>> = new Set()
|
||||||
|
/**
|
||||||
|
* _height is the maximum height of all dependents, plus one.
|
||||||
|
*
|
||||||
|
* -1 means it's not yet calculated
|
||||||
|
* 0 is reserved only for listeners
|
||||||
|
*/
|
||||||
|
private _height: number = -1
|
||||||
|
|
||||||
|
private _graphNode: GraphNode
|
||||||
|
|
||||||
|
protected abstract _recalculate(): V
|
||||||
|
protected abstract _reactToDependencyBecomingStale(
|
||||||
|
which: IDerivation<unknown>,
|
||||||
|
): void
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
const self = this
|
||||||
|
this._graphNode = {
|
||||||
|
get height() {
|
||||||
|
return self._height
|
||||||
|
},
|
||||||
|
recalculate() {
|
||||||
|
// @todo
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
get isHot(): boolean {
|
||||||
|
return this._isHot
|
||||||
|
}
|
||||||
|
|
||||||
|
get height() {
|
||||||
|
return this._height
|
||||||
|
}
|
||||||
|
|
||||||
|
protected _addDependency(d: IDerivation<$IntentionalAny>) {
|
||||||
|
if (this._dependencies.has(d)) return
|
||||||
|
this._dependencies.add(d)
|
||||||
|
if (this._isHot) d.addDependent(this._graphNode)
|
||||||
|
}
|
||||||
|
|
||||||
|
protected _removeDependency(d: IDerivation<$IntentionalAny>) {
|
||||||
|
if (!this._dependencies.has(d)) return
|
||||||
|
this._dependencies.delete(d)
|
||||||
|
if (this._isHot) d.removeDependent(this._graphNode)
|
||||||
|
}
|
||||||
|
|
||||||
|
changes(): Tappable<V> {
|
||||||
|
return new DerivationEmitter(this).tappable()
|
||||||
|
}
|
||||||
|
|
||||||
|
addDependent(d: GraphNode) {
|
||||||
|
const hadDepsBefore = this._dependents.size > 0
|
||||||
|
this._dependents.add(d)
|
||||||
|
|
||||||
|
if (d.height > this._height - 1) {
|
||||||
|
this._setHeight(d.height + 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!hadDepsBefore) {
|
||||||
|
this._reactToNumberOfDependentsChange()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @sealed
|
||||||
|
*/
|
||||||
|
removeDependent(d: GraphNode) {
|
||||||
|
const hadDepsBefore = this._dependents.size > 0
|
||||||
|
this._dependents.delete(d)
|
||||||
|
const hasDepsNow = this._dependents.size > 0
|
||||||
|
if (hadDepsBefore !== hasDepsNow) {
|
||||||
|
this._reactToNumberOfDependentsChange()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
reportDependentHeightChange(d: GraphNode) {
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
if (!this._dependents.has(d)) {
|
||||||
|
throw new Error(
|
||||||
|
`Got a reportDependentHeightChange from a non-dependent.`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this._recalculateHeight()
|
||||||
|
}
|
||||||
|
|
||||||
|
private _recalculateHeight() {
|
||||||
|
let maxHeightOfDependents = -1
|
||||||
|
this._dependents.forEach((d) => {
|
||||||
|
maxHeightOfDependents = Math.max(maxHeightOfDependents, d.height)
|
||||||
|
})
|
||||||
|
const newHeight = maxHeightOfDependents + 1
|
||||||
|
if (this._height !== newHeight) {
|
||||||
|
this._setHeight(newHeight)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private _setHeight(h: number) {
|
||||||
|
this._height = h
|
||||||
|
this._dependencies.forEach((d) => {
|
||||||
|
d.reportDependentHeightChange(this._graphNode)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This is meant to be called by subclasses
|
||||||
|
*
|
||||||
|
* @sealed
|
||||||
|
*/
|
||||||
|
protected _markAsStale(which: IDerivation<$IntentionalAny>) {
|
||||||
|
this._internal_markAsStale(which)
|
||||||
|
}
|
||||||
|
|
||||||
|
private _internal_markAsStale = (which: IDerivation<$IntentionalAny>) => {
|
||||||
|
this._reactToDependencyBecomingStale(which)
|
||||||
|
|
||||||
|
if (this._didMarkDependentsAsStale) return
|
||||||
|
|
||||||
|
this._didMarkDependentsAsStale = true
|
||||||
|
this._isFresh = false
|
||||||
|
|
||||||
|
this._dependents.forEach((dependent) => {
|
||||||
|
dependent.recalculate()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
getValue(): V {
|
||||||
|
reportResolutionStart(this)
|
||||||
|
|
||||||
|
if (!this._isFresh) {
|
||||||
|
const newValue = this._recalculate()
|
||||||
|
this._lastValue = newValue
|
||||||
|
if (this.isHot) {
|
||||||
|
this._isFresh = true
|
||||||
|
this._didMarkDependentsAsStale = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
reportResolutionEnd(this)
|
||||||
|
return this._lastValue!
|
||||||
|
}
|
||||||
|
|
||||||
|
private _reactToNumberOfDependentsChange() {
|
||||||
|
const shouldBecomeHot = this._dependents.size > 0
|
||||||
|
|
||||||
|
if (shouldBecomeHot === this._isHot) return
|
||||||
|
|
||||||
|
this._isHot = shouldBecomeHot
|
||||||
|
this._didMarkDependentsAsStale = false
|
||||||
|
this._isFresh = false
|
||||||
|
if (shouldBecomeHot) {
|
||||||
|
this._dependencies.forEach((d) => {
|
||||||
|
d.addDependent(this._graphNode)
|
||||||
|
})
|
||||||
|
this._keepHot()
|
||||||
|
} else {
|
||||||
|
this._dependencies.forEach((d) => {
|
||||||
|
d.removeDependent(this._graphNode)
|
||||||
|
})
|
||||||
|
this._becomeCold()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected _keepHot() {}
|
||||||
|
|
||||||
|
protected _becomeCold() {}
|
||||||
|
|
||||||
|
map<T>(fn: (v: V) => T): IDerivation<T> {
|
||||||
|
return map(this, fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
flatMap<R>(
|
||||||
|
fn: (v: V) => R,
|
||||||
|
): IDerivation<R extends IDerivation<infer T> ? T : R> {
|
||||||
|
return flatMap(this, fn)
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,36 @@
|
||||||
|
import type {$IntentionalAny} from '../types'
|
||||||
|
import type {IDerivation} from './IDerivation'
|
||||||
|
|
||||||
|
const _any: $IntentionalAny = null
|
||||||
|
|
||||||
|
// map
|
||||||
|
;() => {
|
||||||
|
const a: IDerivation<string> = _any
|
||||||
|
|
||||||
|
// $ExpectType IDerivation<number>
|
||||||
|
// eslint-disable-next-line unused-imports/no-unused-vars-ts
|
||||||
|
a.map((s: string) => 10)
|
||||||
|
|
||||||
|
// @ts-expect-error
|
||||||
|
// eslint-disable-next-line unused-imports/no-unused-vars-ts
|
||||||
|
a.map((s: number) => 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
// flatMap()
|
||||||
|
/* eslint-disable unused-imports/no-unused-vars-ts */
|
||||||
|
;() => {
|
||||||
|
const a: IDerivation<string> = _any
|
||||||
|
|
||||||
|
// okay
|
||||||
|
a.flatMap((s: string) => {})
|
||||||
|
|
||||||
|
// @ts-expect-error TypeTest
|
||||||
|
a.flatMap((s: number) => {})
|
||||||
|
|
||||||
|
// $ExpectType IDerivation<number>
|
||||||
|
a.flatMap((s): IDerivation<number> => _any)
|
||||||
|
|
||||||
|
// $ExpectType IDerivation<number>
|
||||||
|
a.flatMap((s): number => _any)
|
||||||
|
}
|
||||||
|
/* eslint-enable unused-imports/no-unused-vars-ts */
|
17
packages/dataverse2/src/derivations/ConstantDerivation.ts
Normal file
17
packages/dataverse2/src/derivations/ConstantDerivation.ts
Normal file
|
@ -0,0 +1,17 @@
|
||||||
|
import AbstractDerivation from './AbstractDerivation'
|
||||||
|
|
||||||
|
export default class ConstantDerivation<V> extends AbstractDerivation<V> {
|
||||||
|
_v: V
|
||||||
|
|
||||||
|
constructor(v: V) {
|
||||||
|
super()
|
||||||
|
this._v = v
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
_recalculate() {
|
||||||
|
return this._v
|
||||||
|
}
|
||||||
|
|
||||||
|
_reactToDependencyBecomingStale() {}
|
||||||
|
}
|
52
packages/dataverse2/src/derivations/DerivationEmitter.ts
Normal file
52
packages/dataverse2/src/derivations/DerivationEmitter.ts
Normal file
|
@ -0,0 +1,52 @@
|
||||||
|
import Emitter from '../utils/Emitter'
|
||||||
|
import type {default as Tappable} from '../utils/Tappable'
|
||||||
|
import type {GraphNode, IDerivation} from './IDerivation'
|
||||||
|
|
||||||
|
export default class DerivationEmitter<V> {
|
||||||
|
private _emitter: Emitter<V>
|
||||||
|
private _lastValue: undefined | V
|
||||||
|
private _lastValueRecorded: boolean
|
||||||
|
private _hadTappers: boolean
|
||||||
|
private _graphNode: GraphNode
|
||||||
|
|
||||||
|
constructor(private readonly _derivation: IDerivation<V>) {
|
||||||
|
this._emitter = new Emitter()
|
||||||
|
this._graphNode = {
|
||||||
|
height: 0,
|
||||||
|
recalculate: () => {
|
||||||
|
this._emit()
|
||||||
|
},
|
||||||
|
}
|
||||||
|
this._emitter.onNumberOfTappersChange(() => {
|
||||||
|
this._reactToNumberOfTappersChange()
|
||||||
|
})
|
||||||
|
this._hadTappers = false
|
||||||
|
this._lastValueRecorded = false
|
||||||
|
this._lastValue = undefined
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
private _reactToNumberOfTappersChange() {
|
||||||
|
const hasTappers = this._emitter.hasTappers()
|
||||||
|
if (hasTappers !== this._hadTappers) {
|
||||||
|
this._hadTappers = hasTappers
|
||||||
|
if (hasTappers) {
|
||||||
|
this._derivation.addDependent(this._graphNode)
|
||||||
|
} else {
|
||||||
|
this._derivation.removeDependent(this._graphNode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tappable(): Tappable<V> {
|
||||||
|
return this._emitter.tappable
|
||||||
|
}
|
||||||
|
|
||||||
|
private _emit = () => {
|
||||||
|
const newValue = this._derivation.getValue()
|
||||||
|
if (newValue === this._lastValue && this._lastValueRecorded === true) return
|
||||||
|
this._lastValue = newValue
|
||||||
|
this._lastValueRecorded = true
|
||||||
|
this._emitter.emit(newValue)
|
||||||
|
}
|
||||||
|
}
|
53
packages/dataverse2/src/derivations/DerivationFromSource.ts
Normal file
53
packages/dataverse2/src/derivations/DerivationFromSource.ts
Normal file
|
@ -0,0 +1,53 @@
|
||||||
|
import type {VoidFn} from '../types'
|
||||||
|
import AbstractDerivation from './AbstractDerivation'
|
||||||
|
|
||||||
|
const noop = () => {}
|
||||||
|
|
||||||
|
export default class DerivationFromSource<V> extends AbstractDerivation<V> {
|
||||||
|
private _untapFromChanges: () => void
|
||||||
|
private _cachedValue: undefined | V
|
||||||
|
private _hasCachedValue: boolean
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly _tapToSource: (listener: (newValue: V) => void) => VoidFn,
|
||||||
|
private readonly _getValueFromSource: () => V,
|
||||||
|
) {
|
||||||
|
super()
|
||||||
|
this._untapFromChanges = noop
|
||||||
|
this._cachedValue = undefined
|
||||||
|
this._hasCachedValue = false
|
||||||
|
}
|
||||||
|
|
||||||
|
_recalculate() {
|
||||||
|
if (this.isHot) {
|
||||||
|
if (!this._hasCachedValue) {
|
||||||
|
this._cachedValue = this._getValueFromSource()
|
||||||
|
this._hasCachedValue = true
|
||||||
|
}
|
||||||
|
return this._cachedValue as V
|
||||||
|
} else {
|
||||||
|
return this._getValueFromSource()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_keepHot() {
|
||||||
|
this._hasCachedValue = false
|
||||||
|
this._cachedValue = undefined
|
||||||
|
|
||||||
|
this._untapFromChanges = this._tapToSource((newValue) => {
|
||||||
|
this._hasCachedValue = true
|
||||||
|
this._cachedValue = newValue
|
||||||
|
this._markAsStale(this)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
_becomeCold() {
|
||||||
|
this._untapFromChanges()
|
||||||
|
this._untapFromChanges = noop
|
||||||
|
|
||||||
|
this._hasCachedValue = false
|
||||||
|
this._cachedValue = undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
_reactToDependencyBecomingStale() {}
|
||||||
|
}
|
5
packages/dataverse2/src/derivations/Freshener.ts
Normal file
5
packages/dataverse2/src/derivations/Freshener.ts
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
import type {GraphNode} from './IDerivation'
|
||||||
|
|
||||||
|
export default class Freshener {
|
||||||
|
schedulePeak(d: GraphNode) {}
|
||||||
|
}
|
29
packages/dataverse2/src/derivations/IDerivation.ts
Normal file
29
packages/dataverse2/src/derivations/IDerivation.ts
Normal file
|
@ -0,0 +1,29 @@
|
||||||
|
import type Tappable from '../utils/Tappable'
|
||||||
|
|
||||||
|
export type GraphNode = {
|
||||||
|
height: number
|
||||||
|
recalculate(): void
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IDerivation<V> {
|
||||||
|
isDerivation: true
|
||||||
|
isHot: boolean
|
||||||
|
changes(): Tappable<V>
|
||||||
|
|
||||||
|
addDependent(d: GraphNode): void
|
||||||
|
removeDependent(d: GraphNode): void
|
||||||
|
|
||||||
|
reportDependentHeightChange(d: GraphNode): void
|
||||||
|
|
||||||
|
getValue(): V
|
||||||
|
|
||||||
|
map<T>(fn: (v: V) => T): IDerivation<T>
|
||||||
|
|
||||||
|
flatMap<R>(
|
||||||
|
fn: (v: V) => R,
|
||||||
|
): IDerivation<R extends IDerivation<infer T> ? T : R>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isDerivation(d: any): d is IDerivation<unknown> {
|
||||||
|
return d && d.isDerivation && d.isDerivation === true
|
||||||
|
}
|
127
packages/dataverse2/src/derivations/flatMap.ts
Normal file
127
packages/dataverse2/src/derivations/flatMap.ts
Normal file
|
@ -0,0 +1,127 @@
|
||||||
|
import type {$FixMe} from '../types'
|
||||||
|
import AbstractDerivation from './AbstractDerivation'
|
||||||
|
import type {IDerivation} from './IDerivation'
|
||||||
|
|
||||||
|
enum UPDATE_NEEDED_FROM {
|
||||||
|
none = 0,
|
||||||
|
dep = 1,
|
||||||
|
inner = 2,
|
||||||
|
}
|
||||||
|
|
||||||
|
const makeFlatMapDerivationClass = () => {
|
||||||
|
class FlatMapDerivation<V, DepType> extends AbstractDerivation<V> {
|
||||||
|
private _innerDerivation: undefined | null | IDerivation<V>
|
||||||
|
private _staleDependency: UPDATE_NEEDED_FROM
|
||||||
|
|
||||||
|
static displayName = 'flatMap'
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
readonly _depDerivation: IDerivation<DepType>,
|
||||||
|
readonly _fn: (v: DepType) => IDerivation<V> | V,
|
||||||
|
) {
|
||||||
|
super()
|
||||||
|
this._innerDerivation = undefined
|
||||||
|
this._staleDependency = UPDATE_NEEDED_FROM.dep
|
||||||
|
|
||||||
|
this._addDependency(_depDerivation)
|
||||||
|
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
_recalculateHot() {
|
||||||
|
const updateNeededFrom = this._staleDependency
|
||||||
|
this._staleDependency = UPDATE_NEEDED_FROM.none
|
||||||
|
|
||||||
|
if (updateNeededFrom === UPDATE_NEEDED_FROM.inner) {
|
||||||
|
// @ts-ignore
|
||||||
|
return this._innerDerivation.getValue()
|
||||||
|
}
|
||||||
|
|
||||||
|
const possibleInnerDerivation = this._fn(this._depDerivation.getValue())
|
||||||
|
|
||||||
|
if (possibleInnerDerivation instanceof AbstractDerivation) {
|
||||||
|
this._innerDerivation = possibleInnerDerivation
|
||||||
|
this._addDependency(possibleInnerDerivation)
|
||||||
|
return possibleInnerDerivation.getValue()
|
||||||
|
} else {
|
||||||
|
return possibleInnerDerivation
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected _recalculateCold() {
|
||||||
|
const possibleInnerDerivation = this._fn(this._depDerivation.getValue())
|
||||||
|
|
||||||
|
if (possibleInnerDerivation instanceof AbstractDerivation) {
|
||||||
|
return possibleInnerDerivation.getValue()
|
||||||
|
} else {
|
||||||
|
return possibleInnerDerivation
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected _recalculate() {
|
||||||
|
return this.isHot ? this._recalculateHot() : this._recalculateCold()
|
||||||
|
}
|
||||||
|
|
||||||
|
protected _reactToDependencyBecomingStale(
|
||||||
|
msgComingFrom: IDerivation<unknown>,
|
||||||
|
) {
|
||||||
|
const updateNeededFrom =
|
||||||
|
msgComingFrom === this._depDerivation
|
||||||
|
? UPDATE_NEEDED_FROM.dep
|
||||||
|
: UPDATE_NEEDED_FROM.inner
|
||||||
|
|
||||||
|
if (
|
||||||
|
updateNeededFrom === UPDATE_NEEDED_FROM.inner &&
|
||||||
|
msgComingFrom !== this._innerDerivation
|
||||||
|
) {
|
||||||
|
throw Error(
|
||||||
|
`got a _pipostale() from neither the dep nor the inner derivation`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this._staleDependency === UPDATE_NEEDED_FROM.none) {
|
||||||
|
this._staleDependency = updateNeededFrom
|
||||||
|
|
||||||
|
if (updateNeededFrom === UPDATE_NEEDED_FROM.dep) {
|
||||||
|
this._removeInnerDerivation()
|
||||||
|
}
|
||||||
|
} else if (this._staleDependency === UPDATE_NEEDED_FROM.dep) {
|
||||||
|
} else {
|
||||||
|
if (updateNeededFrom === UPDATE_NEEDED_FROM.dep) {
|
||||||
|
this._staleDependency = UPDATE_NEEDED_FROM.dep
|
||||||
|
this._removeInnerDerivation()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private _removeInnerDerivation() {
|
||||||
|
if (this._innerDerivation) {
|
||||||
|
this._removeDependency(this._innerDerivation)
|
||||||
|
this._innerDerivation = undefined
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected _keepHot() {
|
||||||
|
this._staleDependency = UPDATE_NEEDED_FROM.dep
|
||||||
|
this.getValue()
|
||||||
|
}
|
||||||
|
|
||||||
|
protected _becomeCold() {
|
||||||
|
this._staleDependency = UPDATE_NEEDED_FROM.dep
|
||||||
|
this._removeInnerDerivation()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return FlatMapDerivation
|
||||||
|
}
|
||||||
|
|
||||||
|
let cls: ReturnType<typeof makeFlatMapDerivationClass> | undefined = undefined
|
||||||
|
|
||||||
|
export default function flatMap<V, R>(
|
||||||
|
dep: IDerivation<V>,
|
||||||
|
fn: (v: V) => R,
|
||||||
|
): IDerivation<R extends IDerivation<infer T> ? T : R> {
|
||||||
|
if (!cls) {
|
||||||
|
cls = makeFlatMapDerivationClass()
|
||||||
|
}
|
||||||
|
return new cls(dep, fn) as $FixMe
|
||||||
|
}
|
32
packages/dataverse2/src/derivations/iterateAndCountTicks.ts
Normal file
32
packages/dataverse2/src/derivations/iterateAndCountTicks.ts
Normal file
|
@ -0,0 +1,32 @@
|
||||||
|
import {isPointer, valueDerivation} from '../Atom'
|
||||||
|
import type {Pointer} from '../pointer'
|
||||||
|
import type {IDerivation} from './IDerivation'
|
||||||
|
import {isDerivation} from './IDerivation'
|
||||||
|
|
||||||
|
export default function* iterateAndCountTicks<V>(
|
||||||
|
pointerOrDerivation: IDerivation<V> | Pointer<V>,
|
||||||
|
): Generator<{value: V; ticks: number}, void, void> {
|
||||||
|
let d
|
||||||
|
if (isPointer(pointerOrDerivation)) {
|
||||||
|
d = valueDerivation(pointerOrDerivation) as IDerivation<V>
|
||||||
|
} else if (isDerivation(pointerOrDerivation)) {
|
||||||
|
d = pointerOrDerivation
|
||||||
|
} else {
|
||||||
|
throw new Error(`Only pointers and derivations are supported`)
|
||||||
|
}
|
||||||
|
|
||||||
|
let ticksCountedSinceLastYield = 0
|
||||||
|
const untap = d.changes().tap(() => {
|
||||||
|
ticksCountedSinceLastYield++
|
||||||
|
})
|
||||||
|
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
const ticks = ticksCountedSinceLastYield
|
||||||
|
ticksCountedSinceLastYield = 0
|
||||||
|
yield {value: d.getValue(), ticks}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
untap()
|
||||||
|
}
|
||||||
|
}
|
19
packages/dataverse2/src/derivations/iterateOver.test.ts
Normal file
19
packages/dataverse2/src/derivations/iterateOver.test.ts
Normal file
|
@ -0,0 +1,19 @@
|
||||||
|
import Atom from '../Atom'
|
||||||
|
import iterateOver from './iterateOver'
|
||||||
|
|
||||||
|
describe.skip(`iterateOver()`, () => {
|
||||||
|
test('it should work', () => {
|
||||||
|
const a = new Atom({a: 0})
|
||||||
|
let iter = iterateOver(a.pointer.a)
|
||||||
|
expect(iter.next().value).toEqual(0)
|
||||||
|
a.setIn(['a'], 1)
|
||||||
|
a.setIn(['a'], 2)
|
||||||
|
expect(iter.next()).toMatchObject({value: 2, done: false})
|
||||||
|
iter.return()
|
||||||
|
iter = iterateOver(a.pointer.a)
|
||||||
|
expect(iter.next().value).toEqual(2)
|
||||||
|
a.setIn(['a'], 3)
|
||||||
|
expect(iter.next()).toMatchObject({done: false, value: 3})
|
||||||
|
iter.return()
|
||||||
|
})
|
||||||
|
})
|
32
packages/dataverse2/src/derivations/iterateOver.ts
Normal file
32
packages/dataverse2/src/derivations/iterateOver.ts
Normal file
|
@ -0,0 +1,32 @@
|
||||||
|
import {isPointer, valueDerivation} from '../Atom'
|
||||||
|
import type {Pointer} from '../pointer'
|
||||||
|
import Ticker from '../Ticker'
|
||||||
|
import type {IDerivation} from './IDerivation'
|
||||||
|
import {isDerivation} from './IDerivation'
|
||||||
|
|
||||||
|
export default function* iterateOver<V>(
|
||||||
|
pointerOrDerivation: IDerivation<V> | Pointer<V>,
|
||||||
|
): Generator<V, void, void> {
|
||||||
|
let d
|
||||||
|
if (isPointer(pointerOrDerivation)) {
|
||||||
|
d = valueDerivation(pointerOrDerivation) as IDerivation<V>
|
||||||
|
} else if (isDerivation(pointerOrDerivation)) {
|
||||||
|
d = pointerOrDerivation
|
||||||
|
} else {
|
||||||
|
throw new Error(`Only pointers and derivations are supported`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const ticker = new Ticker()
|
||||||
|
|
||||||
|
const untap = d.changes().tap((v) => {})
|
||||||
|
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
ticker.tick()
|
||||||
|
|
||||||
|
yield d.getValue()
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
untap()
|
||||||
|
}
|
||||||
|
}
|
32
packages/dataverse2/src/derivations/map.ts
Normal file
32
packages/dataverse2/src/derivations/map.ts
Normal file
|
@ -0,0 +1,32 @@
|
||||||
|
import AbstractDerivation from './AbstractDerivation'
|
||||||
|
import type {IDerivation} from './IDerivation'
|
||||||
|
|
||||||
|
// Exporting from a function because of the circular dependency with AbstractDerivation
|
||||||
|
const makeMapDerivationClass = () =>
|
||||||
|
class MapDerivation<T, V> extends AbstractDerivation<V> {
|
||||||
|
constructor(
|
||||||
|
private readonly _dep: IDerivation<T>,
|
||||||
|
private readonly _fn: (t: T) => V,
|
||||||
|
) {
|
||||||
|
super()
|
||||||
|
this._addDependency(_dep)
|
||||||
|
}
|
||||||
|
|
||||||
|
_recalculate() {
|
||||||
|
return this._fn(this._dep.getValue())
|
||||||
|
}
|
||||||
|
|
||||||
|
_reactToDependencyBecomingStale() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
let cls: ReturnType<typeof makeMapDerivationClass> | undefined = undefined
|
||||||
|
|
||||||
|
export default function flatMap<V, R>(
|
||||||
|
dep: IDerivation<V>,
|
||||||
|
fn: (v: V) => R,
|
||||||
|
): IDerivation<R> {
|
||||||
|
if (!cls) {
|
||||||
|
cls = makeMapDerivationClass()
|
||||||
|
}
|
||||||
|
return new cls(dep, fn)
|
||||||
|
}
|
|
@ -0,0 +1,50 @@
|
||||||
|
import type {$IntentionalAny} from '../../types'
|
||||||
|
import Stack from '../../utils/Stack'
|
||||||
|
import type {IDerivation} from '../IDerivation'
|
||||||
|
|
||||||
|
const noop = () => {}
|
||||||
|
|
||||||
|
const stack = new Stack<Collector>()
|
||||||
|
const noopCollector: Collector = noop
|
||||||
|
|
||||||
|
type Collector = (d: IDerivation<$IntentionalAny>) => void
|
||||||
|
|
||||||
|
export const collectObservedDependencies = (
|
||||||
|
cb: () => void,
|
||||||
|
collector: Collector,
|
||||||
|
) => {
|
||||||
|
stack.push(collector)
|
||||||
|
cb()
|
||||||
|
stack.pop()
|
||||||
|
}
|
||||||
|
|
||||||
|
export const startIgnoringDependencies = () => {
|
||||||
|
stack.push(noopCollector)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const stopIgnoringDependencies = () => {
|
||||||
|
if (stack.peek() !== noopCollector) {
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('This should never happen')
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
stack.pop()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const reportResolutionStart = (d: IDerivation<$IntentionalAny>) => {
|
||||||
|
const possibleCollector = stack.peek()
|
||||||
|
if (possibleCollector) {
|
||||||
|
possibleCollector(d)
|
||||||
|
}
|
||||||
|
|
||||||
|
stack.push(noopCollector)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const reportResolutionEnd = (_d: IDerivation<$IntentionalAny>) => {
|
||||||
|
stack.pop()
|
||||||
|
}
|
||||||
|
|
||||||
|
export const isCollectingDependencies = () => {
|
||||||
|
return stack.peek() !== noopCollector
|
||||||
|
}
|
225
packages/dataverse2/src/derivations/prism/prism.test.ts
Normal file
225
packages/dataverse2/src/derivations/prism/prism.test.ts
Normal file
|
@ -0,0 +1,225 @@
|
||||||
|
import Atom, {val} from '../../Atom'
|
||||||
|
import Ticker from '../../Ticker'
|
||||||
|
import type {$FixMe, $IntentionalAny} from '../../types'
|
||||||
|
import ConstantDerivation from '../ConstantDerivation'
|
||||||
|
import iterateAndCountTicks from '../iterateAndCountTicks'
|
||||||
|
import prism, {PrismDerivation} from './prism'
|
||||||
|
|
||||||
|
describe.skip('prism', () => {
|
||||||
|
let ticker: Ticker
|
||||||
|
beforeEach(() => {
|
||||||
|
ticker = new Ticker()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should work', () => {
|
||||||
|
const o = new Atom({foo: 'foo'})
|
||||||
|
const d = new PrismDerivation(() => {
|
||||||
|
return val(o.pointer.foo) + 'boo'
|
||||||
|
})
|
||||||
|
expect(d.getValue()).toEqual('fooboo')
|
||||||
|
|
||||||
|
const changes: Array<$FixMe> = []
|
||||||
|
d.changes().tap((c) => {
|
||||||
|
changes.push(c)
|
||||||
|
})
|
||||||
|
|
||||||
|
o.reduceState(['foo'], () => 'foo2')
|
||||||
|
ticker.tick()
|
||||||
|
expect(changes).toMatchObject(['foo2boo'])
|
||||||
|
})
|
||||||
|
it('should only collect immediate dependencies', () => {
|
||||||
|
const aD = new ConstantDerivation(1)
|
||||||
|
const bD = aD.map((v) => v * 2)
|
||||||
|
const cD = prism(() => {
|
||||||
|
return bD.getValue()
|
||||||
|
})
|
||||||
|
expect(cD.getValue()).toEqual(2)
|
||||||
|
expect((cD as $IntentionalAny)._dependencies.size).toEqual(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('prism.ref()', () => {
|
||||||
|
it('should work', () => {
|
||||||
|
const theAtom: Atom<{n: number}> = new Atom({n: 2})
|
||||||
|
|
||||||
|
const isEvenD = prism((): {isEven: boolean} => {
|
||||||
|
const ref = prism.ref<{isEven: boolean} | undefined>('cache', undefined)
|
||||||
|
const currentN = val(theAtom.pointer.n)
|
||||||
|
|
||||||
|
const isEven = currentN % 2 === 0
|
||||||
|
if (ref.current && ref.current.isEven === isEven) {
|
||||||
|
return ref.current
|
||||||
|
} else {
|
||||||
|
ref.current = {isEven}
|
||||||
|
return ref.current
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const iterator = iterateAndCountTicks(isEvenD)
|
||||||
|
|
||||||
|
theAtom.reduceState(['n'], () => 3)
|
||||||
|
|
||||||
|
expect(iterator.next().value).toMatchObject({
|
||||||
|
value: {isEven: false},
|
||||||
|
ticks: 0,
|
||||||
|
})
|
||||||
|
theAtom.reduceState(['n'], () => 5)
|
||||||
|
theAtom.reduceState(['n'], () => 7)
|
||||||
|
expect(iterator.next().value).toMatchObject({
|
||||||
|
value: {isEven: false},
|
||||||
|
ticks: 1,
|
||||||
|
})
|
||||||
|
theAtom.reduceState(['n'], () => 2)
|
||||||
|
theAtom.reduceState(['n'], () => 4)
|
||||||
|
expect(iterator.next().value).toMatchObject({
|
||||||
|
value: {isEven: true},
|
||||||
|
ticks: 1,
|
||||||
|
})
|
||||||
|
expect(iterator.next().value).toMatchObject({
|
||||||
|
value: {isEven: true},
|
||||||
|
ticks: 0,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('prism.effect()', () => {
|
||||||
|
it('should work', async () => {
|
||||||
|
let iteration = 0
|
||||||
|
const sequence: unknown[] = []
|
||||||
|
let deps: unknown[] = []
|
||||||
|
|
||||||
|
const a = new Atom({letter: 'a'})
|
||||||
|
|
||||||
|
const derivation = prism(() => {
|
||||||
|
const n = val(a.pointer.letter)
|
||||||
|
const iterationAtTimeOfCall = iteration
|
||||||
|
sequence.push({derivationCall: iterationAtTimeOfCall})
|
||||||
|
|
||||||
|
prism.effect(
|
||||||
|
'f',
|
||||||
|
() => {
|
||||||
|
sequence.push({effectCall: iterationAtTimeOfCall})
|
||||||
|
return () => {
|
||||||
|
sequence.push({cleanupCall: iterationAtTimeOfCall})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[...deps],
|
||||||
|
)
|
||||||
|
|
||||||
|
return n
|
||||||
|
})
|
||||||
|
|
||||||
|
const untap = derivation.changes().tap((change) => {
|
||||||
|
sequence.push({change})
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(sequence).toMatchObject([{derivationCall: 0}, {effectCall: 0}])
|
||||||
|
sequence.length = 0
|
||||||
|
|
||||||
|
iteration++
|
||||||
|
a.setIn(['letter'], 'b')
|
||||||
|
ticker.tick()
|
||||||
|
expect(sequence).toMatchObject([{derivationCall: 1}, {change: 'b'}])
|
||||||
|
sequence.length = 0
|
||||||
|
|
||||||
|
deps = [1]
|
||||||
|
iteration++
|
||||||
|
a.setIn(['letter'], 'c')
|
||||||
|
ticker.tick()
|
||||||
|
expect(sequence).toMatchObject([
|
||||||
|
{derivationCall: 2},
|
||||||
|
{cleanupCall: 0},
|
||||||
|
{effectCall: 2},
|
||||||
|
{change: 'c'},
|
||||||
|
])
|
||||||
|
sequence.length = 0
|
||||||
|
|
||||||
|
untap()
|
||||||
|
|
||||||
|
// takes a tick before untap takes effect
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 1))
|
||||||
|
expect(sequence).toMatchObject([{cleanupCall: 2}])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('prism.memo()', () => {
|
||||||
|
it('should work', async () => {
|
||||||
|
let iteration = 0
|
||||||
|
const sequence: unknown[] = []
|
||||||
|
let deps: unknown[] = []
|
||||||
|
|
||||||
|
const a = new Atom({letter: 'a'})
|
||||||
|
|
||||||
|
const derivation = prism(() => {
|
||||||
|
const n = val(a.pointer.letter)
|
||||||
|
const iterationAtTimeOfCall = iteration
|
||||||
|
sequence.push({derivationCall: iterationAtTimeOfCall})
|
||||||
|
|
||||||
|
const resultOfMemo = prism.memo(
|
||||||
|
'memo',
|
||||||
|
() => {
|
||||||
|
sequence.push({memoCall: iterationAtTimeOfCall})
|
||||||
|
return iterationAtTimeOfCall
|
||||||
|
},
|
||||||
|
[...deps],
|
||||||
|
)
|
||||||
|
|
||||||
|
sequence.push({resultOfMemo})
|
||||||
|
|
||||||
|
return n
|
||||||
|
})
|
||||||
|
|
||||||
|
const untap = derivation.changes().tap((change) => {
|
||||||
|
sequence.push({change})
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(sequence).toMatchObject([
|
||||||
|
{derivationCall: 0},
|
||||||
|
{memoCall: 0},
|
||||||
|
{resultOfMemo: 0},
|
||||||
|
])
|
||||||
|
sequence.length = 0
|
||||||
|
|
||||||
|
iteration++
|
||||||
|
a.setIn(['letter'], 'b')
|
||||||
|
ticker.tick()
|
||||||
|
expect(sequence).toMatchObject([
|
||||||
|
{derivationCall: 1},
|
||||||
|
{resultOfMemo: 0},
|
||||||
|
{change: 'b'},
|
||||||
|
])
|
||||||
|
sequence.length = 0
|
||||||
|
|
||||||
|
deps = [1]
|
||||||
|
iteration++
|
||||||
|
a.setIn(['letter'], 'c')
|
||||||
|
ticker.tick()
|
||||||
|
expect(sequence).toMatchObject([
|
||||||
|
{derivationCall: 2},
|
||||||
|
{memoCall: 2},
|
||||||
|
{resultOfMemo: 2},
|
||||||
|
{change: 'c'},
|
||||||
|
])
|
||||||
|
sequence.length = 0
|
||||||
|
|
||||||
|
untap()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe(`prism.scope()`, () => {
|
||||||
|
it('should prevent name conflicts', () => {
|
||||||
|
const d = prism(() => {
|
||||||
|
const thisNameWillBeUsedForBothMemos = 'blah'
|
||||||
|
const a = prism.scope('a', () => {
|
||||||
|
return prism.memo(thisNameWillBeUsedForBothMemos, () => 'a', [])
|
||||||
|
})
|
||||||
|
|
||||||
|
const b = prism.scope('b', () => {
|
||||||
|
return prism.memo(thisNameWillBeUsedForBothMemos, () => 'b', [])
|
||||||
|
})
|
||||||
|
|
||||||
|
return {a, b}
|
||||||
|
})
|
||||||
|
expect(d.getValue()).toMatchObject({a: 'a', b: 'b'})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
331
packages/dataverse2/src/derivations/prism/prism.ts
Normal file
331
packages/dataverse2/src/derivations/prism/prism.ts
Normal file
|
@ -0,0 +1,331 @@
|
||||||
|
import Box from '../../Box'
|
||||||
|
import type {$IntentionalAny, VoidFn} from '../../types'
|
||||||
|
import Stack from '../../utils/Stack'
|
||||||
|
import AbstractDerivation from '../AbstractDerivation'
|
||||||
|
import type {IDerivation} from '../IDerivation'
|
||||||
|
import {
|
||||||
|
collectObservedDependencies,
|
||||||
|
startIgnoringDependencies,
|
||||||
|
stopIgnoringDependencies,
|
||||||
|
} from './discoveryMechanism'
|
||||||
|
|
||||||
|
const voidFn = () => {}
|
||||||
|
|
||||||
|
export class PrismDerivation<V> extends AbstractDerivation<V> {
|
||||||
|
protected _cacheOfDendencyValues: Map<IDerivation<unknown>, unknown> =
|
||||||
|
new Map()
|
||||||
|
protected _possiblyStaleDeps = new Set<IDerivation<unknown>>()
|
||||||
|
private _prismScope = new PrismScope()
|
||||||
|
|
||||||
|
constructor(readonly _fn: () => V) {
|
||||||
|
super()
|
||||||
|
}
|
||||||
|
|
||||||
|
_recalculate() {
|
||||||
|
let value: V
|
||||||
|
|
||||||
|
if (this._possiblyStaleDeps.size > 0) {
|
||||||
|
let anActuallyStaleDepWasFound = false
|
||||||
|
startIgnoringDependencies()
|
||||||
|
for (const dep of this._possiblyStaleDeps) {
|
||||||
|
if (this._cacheOfDendencyValues.get(dep) !== dep.getValue()) {
|
||||||
|
anActuallyStaleDepWasFound = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
stopIgnoringDependencies()
|
||||||
|
this._possiblyStaleDeps.clear()
|
||||||
|
if (!anActuallyStaleDepWasFound) {
|
||||||
|
// console.log('ok')
|
||||||
|
|
||||||
|
return this._lastValue!
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const newDeps: Set<IDerivation<unknown>> = new Set()
|
||||||
|
this._cacheOfDendencyValues.clear()
|
||||||
|
collectObservedDependencies(
|
||||||
|
() => {
|
||||||
|
hookScopeStack.push(this._prismScope)
|
||||||
|
try {
|
||||||
|
value = this._fn()
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error)
|
||||||
|
} finally {
|
||||||
|
const topOfTheStack = hookScopeStack.pop()
|
||||||
|
if (topOfTheStack !== this._prismScope) {
|
||||||
|
console.warn(
|
||||||
|
// @todo guide the user to report the bug in an issue
|
||||||
|
`The Prism hook stack has slipped. This is a bug.`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
(observedDep) => {
|
||||||
|
newDeps.add(observedDep)
|
||||||
|
this._addDependency(observedDep)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
this._dependencies.forEach((dep) => {
|
||||||
|
if (!newDeps.has(dep)) {
|
||||||
|
this._removeDependency(dep)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
this._dependencies = newDeps
|
||||||
|
|
||||||
|
startIgnoringDependencies()
|
||||||
|
newDeps.forEach((dep) => {
|
||||||
|
this._cacheOfDendencyValues.set(dep, dep.getValue())
|
||||||
|
})
|
||||||
|
stopIgnoringDependencies()
|
||||||
|
|
||||||
|
return value!
|
||||||
|
}
|
||||||
|
|
||||||
|
_reactToDependencyBecomingStale(msgComingFrom: IDerivation<unknown>) {
|
||||||
|
this._possiblyStaleDeps.add(msgComingFrom)
|
||||||
|
}
|
||||||
|
|
||||||
|
_keepHot() {
|
||||||
|
this._prismScope = new PrismScope()
|
||||||
|
startIgnoringDependencies()
|
||||||
|
this.getValue()
|
||||||
|
stopIgnoringDependencies()
|
||||||
|
}
|
||||||
|
|
||||||
|
_becomeCold() {
|
||||||
|
cleanupScopeStack(this._prismScope)
|
||||||
|
this._prismScope = new PrismScope()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class PrismScope {
|
||||||
|
isPrismScope = true
|
||||||
|
private _subs: Record<string, PrismScope> = {}
|
||||||
|
|
||||||
|
sub(key: string) {
|
||||||
|
if (!this._subs[key]) {
|
||||||
|
this._subs[key] = new PrismScope()
|
||||||
|
}
|
||||||
|
return this._subs[key]
|
||||||
|
}
|
||||||
|
|
||||||
|
get subs() {
|
||||||
|
return this._subs
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function cleanupScopeStack(scope: PrismScope) {
|
||||||
|
for (const [_, sub] of Object.entries(scope.subs)) {
|
||||||
|
cleanupScopeStack(sub)
|
||||||
|
}
|
||||||
|
cleanupEffects(scope)
|
||||||
|
}
|
||||||
|
|
||||||
|
function cleanupEffects(scope: PrismScope) {
|
||||||
|
const effects = effectsWeakMap.get(scope)
|
||||||
|
if (effects) {
|
||||||
|
for (const k of Object.keys(effects)) {
|
||||||
|
const effect = effects[k]
|
||||||
|
safelyRun(effect.cleanup, undefined)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
effectsWeakMap.delete(scope)
|
||||||
|
}
|
||||||
|
|
||||||
|
function safelyRun<T, U>(
|
||||||
|
fn: () => T,
|
||||||
|
returnValueInCaseOfError: U,
|
||||||
|
): {success: boolean; returnValue: T | U} {
|
||||||
|
let returnValue: T | U = returnValueInCaseOfError
|
||||||
|
let success = false
|
||||||
|
try {
|
||||||
|
returnValue = fn()
|
||||||
|
success = true
|
||||||
|
} catch (error) {
|
||||||
|
setTimeout(() => {
|
||||||
|
throw error
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return {success, returnValue}
|
||||||
|
}
|
||||||
|
|
||||||
|
const hookScopeStack = new Stack<PrismScope>()
|
||||||
|
|
||||||
|
const refsWeakMap = new WeakMap<PrismScope, Record<string, IRef<unknown>>>()
|
||||||
|
|
||||||
|
type IRef<T> = {
|
||||||
|
current: T
|
||||||
|
}
|
||||||
|
const effectsWeakMap = new WeakMap<PrismScope, Record<string, IEffect>>()
|
||||||
|
|
||||||
|
type IEffect = {
|
||||||
|
deps: undefined | unknown[]
|
||||||
|
cleanup: VoidFn
|
||||||
|
}
|
||||||
|
|
||||||
|
const memosWeakMap = new WeakMap<PrismScope, Record<string, IMemo>>()
|
||||||
|
|
||||||
|
type IMemo = {
|
||||||
|
deps: undefined | unknown[]
|
||||||
|
cachedValue: unknown
|
||||||
|
}
|
||||||
|
|
||||||
|
function ref<T>(key: string, initialValue: T): IRef<T> {
|
||||||
|
const scope = hookScopeStack.peek()
|
||||||
|
if (!scope) {
|
||||||
|
throw new Error(`prism.ref() is called outside of a prism() call.`)
|
||||||
|
}
|
||||||
|
let refs = refsWeakMap.get(scope)
|
||||||
|
if (!refs) {
|
||||||
|
refs = {}
|
||||||
|
refsWeakMap.set(scope, refs)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (refs[key]) {
|
||||||
|
return refs[key] as $IntentionalAny as IRef<T>
|
||||||
|
} else {
|
||||||
|
const ref: IRef<T> = {
|
||||||
|
current: initialValue,
|
||||||
|
}
|
||||||
|
refs[key] = ref
|
||||||
|
return ref
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function effect(key: string, cb: () => () => void, deps?: unknown[]): void {
|
||||||
|
const scope = hookScopeStack.peek()
|
||||||
|
if (!scope) {
|
||||||
|
throw new Error(`prism.effect() is called outside of a prism() call.`)
|
||||||
|
}
|
||||||
|
let effects = effectsWeakMap.get(scope)
|
||||||
|
|
||||||
|
if (!effects) {
|
||||||
|
effects = {}
|
||||||
|
effectsWeakMap.set(scope, effects)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!effects[key]) {
|
||||||
|
effects[key] = {
|
||||||
|
cleanup: voidFn,
|
||||||
|
deps: [{}],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const effect = effects[key]
|
||||||
|
if (depsHaveChanged(effect.deps, deps)) {
|
||||||
|
effect.cleanup()
|
||||||
|
|
||||||
|
startIgnoringDependencies()
|
||||||
|
effect.cleanup = safelyRun(cb, voidFn).returnValue
|
||||||
|
stopIgnoringDependencies()
|
||||||
|
effect.deps = deps
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function depsHaveChanged(
|
||||||
|
oldDeps: undefined | unknown[],
|
||||||
|
newDeps: undefined | unknown[],
|
||||||
|
): boolean {
|
||||||
|
if (oldDeps === undefined || newDeps === undefined) {
|
||||||
|
return true
|
||||||
|
} else if (oldDeps.length !== newDeps.length) {
|
||||||
|
return true
|
||||||
|
} else {
|
||||||
|
return oldDeps.some((el, i) => el !== newDeps[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function memo<T>(
|
||||||
|
key: string,
|
||||||
|
fn: () => T,
|
||||||
|
deps: undefined | $IntentionalAny[],
|
||||||
|
): T {
|
||||||
|
const scope = hookScopeStack.peek()
|
||||||
|
if (!scope) {
|
||||||
|
throw new Error(`prism.memo() is called outside of a prism() call.`)
|
||||||
|
}
|
||||||
|
|
||||||
|
let memos = memosWeakMap.get(scope)
|
||||||
|
|
||||||
|
if (!memos) {
|
||||||
|
memos = {}
|
||||||
|
memosWeakMap.set(scope, memos)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!memos[key]) {
|
||||||
|
memos[key] = {
|
||||||
|
cachedValue: null,
|
||||||
|
deps: [{}],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const memo = memos[key]
|
||||||
|
if (depsHaveChanged(memo.deps, deps)) {
|
||||||
|
startIgnoringDependencies()
|
||||||
|
|
||||||
|
memo.cachedValue = safelyRun(fn, undefined).returnValue
|
||||||
|
stopIgnoringDependencies()
|
||||||
|
memo.deps = deps
|
||||||
|
}
|
||||||
|
|
||||||
|
return memo.cachedValue as $IntentionalAny as T
|
||||||
|
}
|
||||||
|
|
||||||
|
function state<T>(key: string, initialValue: T): [T, (val: T) => void] {
|
||||||
|
const {b, setValue} = prism.memo(
|
||||||
|
'state/' + key,
|
||||||
|
() => {
|
||||||
|
const b = new Box<T>(initialValue)
|
||||||
|
const setValue = (val: T) => b.set(val)
|
||||||
|
return {b, setValue}
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
)
|
||||||
|
|
||||||
|
return [b.derivation.getValue(), setValue]
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensurePrism(): void {
|
||||||
|
const scope = hookScopeStack.peek()
|
||||||
|
if (!scope) {
|
||||||
|
throw new Error(`The parent function is called outside of a prism() call.`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function scope<T>(key: string, fn: () => T): T {
|
||||||
|
const parentScope = hookScopeStack.peek()
|
||||||
|
if (!parentScope) {
|
||||||
|
throw new Error(`prism.memo() is called outside of a prism() call.`)
|
||||||
|
}
|
||||||
|
const subScope = parentScope.sub(key)
|
||||||
|
hookScopeStack.push(subScope)
|
||||||
|
const ret = safelyRun(fn, undefined).returnValue
|
||||||
|
hookScopeStack.pop()
|
||||||
|
return ret as $IntentionalAny as T
|
||||||
|
}
|
||||||
|
|
||||||
|
type IPrismFn = {
|
||||||
|
<T>(fn: () => T): IDerivation<T>
|
||||||
|
ref: typeof ref
|
||||||
|
effect: typeof effect
|
||||||
|
memo: typeof memo
|
||||||
|
ensurePrism: typeof ensurePrism
|
||||||
|
state: typeof state
|
||||||
|
scope: typeof scope
|
||||||
|
}
|
||||||
|
|
||||||
|
const prism: IPrismFn = (fn) => {
|
||||||
|
return new PrismDerivation(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
prism.ref = ref
|
||||||
|
prism.effect = effect
|
||||||
|
prism.memo = memo
|
||||||
|
prism.ensurePrism = ensurePrism
|
||||||
|
prism.state = state
|
||||||
|
prism.scope = scope
|
||||||
|
|
||||||
|
export default prism
|
14
packages/dataverse2/src/index.ts
Normal file
14
packages/dataverse2/src/index.ts
Normal file
|
@ -0,0 +1,14 @@
|
||||||
|
export {default as Atom, isPointer, val, valueDerivation} from './Atom'
|
||||||
|
export {default as Box} from './Box'
|
||||||
|
export type {IBox} from './Box'
|
||||||
|
export {default as AbstractDerivation} from './derivations/AbstractDerivation'
|
||||||
|
export {default as ConstantDerivation} from './derivations/ConstantDerivation'
|
||||||
|
export {default as DerivationFromSource} from './derivations/DerivationFromSource'
|
||||||
|
export {isDerivation} from './derivations/IDerivation'
|
||||||
|
export type {IDerivation} from './derivations/IDerivation'
|
||||||
|
export {default as iterateAndCountTicks} from './derivations/iterateAndCountTicks'
|
||||||
|
export {default as iterateOver} from './derivations/iterateOver'
|
||||||
|
export {default as prism} from './derivations/prism/prism'
|
||||||
|
export {default as pointer, getPointerParts} from './pointer'
|
||||||
|
export type {Pointer} from './pointer'
|
||||||
|
export {default as Ticker} from './Ticker'
|
32
packages/dataverse2/src/integration.test.ts
Normal file
32
packages/dataverse2/src/integration.test.ts
Normal file
|
@ -0,0 +1,32 @@
|
||||||
|
import Atom, {val} from './Atom'
|
||||||
|
import prism from './derivations/prism/prism'
|
||||||
|
import Ticker from './Ticker'
|
||||||
|
|
||||||
|
describe.skip(`dataverse2 integration tests`, () => {
|
||||||
|
describe(`identity pointers`, () => {
|
||||||
|
it(`should work`, () => {
|
||||||
|
const data = {foo: 'hi', bar: 0}
|
||||||
|
const a = new Atom(data)
|
||||||
|
const dataP = a.pointer
|
||||||
|
const bar = dataP.bar
|
||||||
|
expect(val(bar)).toEqual(0)
|
||||||
|
|
||||||
|
const d = prism(() => {
|
||||||
|
return val(bar)
|
||||||
|
})
|
||||||
|
expect(d.getValue()).toEqual(0)
|
||||||
|
const ticker = new Ticker()
|
||||||
|
const changes: number[] = []
|
||||||
|
d.changes().tap((c) => {
|
||||||
|
changes.push(c)
|
||||||
|
})
|
||||||
|
a.setState({...data, bar: 1})
|
||||||
|
ticker.tick()
|
||||||
|
expect(changes).toHaveLength(1)
|
||||||
|
expect(changes[0]).toEqual(1)
|
||||||
|
a.setState({...data, bar: 1})
|
||||||
|
ticker.tick()
|
||||||
|
expect(changes).toHaveLength(1)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
98
packages/dataverse2/src/pointer.ts
Normal file
98
packages/dataverse2/src/pointer.ts
Normal file
|
@ -0,0 +1,98 @@
|
||||||
|
import type {$IntentionalAny} from './types'
|
||||||
|
|
||||||
|
type PathToProp = Array<string | number>
|
||||||
|
|
||||||
|
type PointerMeta = {
|
||||||
|
root: {}
|
||||||
|
path: (string | number)[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export type UnindexableTypesForPointer =
|
||||||
|
| number
|
||||||
|
| string
|
||||||
|
| boolean
|
||||||
|
| null
|
||||||
|
| void
|
||||||
|
| undefined
|
||||||
|
| Function // eslint-disable-line @typescript-eslint/ban-types
|
||||||
|
|
||||||
|
export type UnindexablePointer = {
|
||||||
|
[K in $IntentionalAny]: Pointer<undefined>
|
||||||
|
}
|
||||||
|
|
||||||
|
const pointerMetaWeakMap = new WeakMap<{}, PointerMeta>()
|
||||||
|
|
||||||
|
export type PointerType<O> = {
|
||||||
|
$$__pointer_type: O
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Pointer<O> = PointerType<O> &
|
||||||
|
(O extends UnindexableTypesForPointer
|
||||||
|
? UnindexablePointer
|
||||||
|
: unknown extends O
|
||||||
|
? UnindexablePointer
|
||||||
|
: O extends (infer T)[]
|
||||||
|
? Pointer<T>[]
|
||||||
|
: O extends {}
|
||||||
|
? {[K in keyof O]-?: Pointer<O[K]>}
|
||||||
|
: UnindexablePointer)
|
||||||
|
|
||||||
|
const pointerMetaSymbol = Symbol('pointerMeta')
|
||||||
|
|
||||||
|
const cachedSubPointersWeakMap = new WeakMap<
|
||||||
|
{},
|
||||||
|
Record<string | number, Pointer<unknown>>
|
||||||
|
>()
|
||||||
|
|
||||||
|
const handler = {
|
||||||
|
get(obj: {}, prop: string | typeof pointerMetaSymbol): $IntentionalAny {
|
||||||
|
if (prop === pointerMetaSymbol) return pointerMetaWeakMap.get(obj)!
|
||||||
|
|
||||||
|
let subs = cachedSubPointersWeakMap.get(obj)
|
||||||
|
if (!subs) {
|
||||||
|
subs = {}
|
||||||
|
cachedSubPointersWeakMap.set(obj, subs)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (subs[prop]) return subs[prop]
|
||||||
|
|
||||||
|
const meta = pointerMetaWeakMap.get(obj)!
|
||||||
|
|
||||||
|
const subPointer = pointer({root: meta.root, path: [...meta.path, prop]})
|
||||||
|
subs[prop] = subPointer
|
||||||
|
return subPointer
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getPointerMeta = (p: Pointer<$IntentionalAny>): PointerMeta => {
|
||||||
|
const meta: PointerMeta = p[
|
||||||
|
pointerMetaSymbol as unknown as $IntentionalAny
|
||||||
|
] as $IntentionalAny
|
||||||
|
return meta
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getPointerParts = (
|
||||||
|
p: Pointer<$IntentionalAny>,
|
||||||
|
): {root: {}; path: PathToProp} => {
|
||||||
|
const {root, path} = getPointerMeta(p)
|
||||||
|
return {root, path}
|
||||||
|
}
|
||||||
|
|
||||||
|
function pointer<O>({
|
||||||
|
root,
|
||||||
|
path,
|
||||||
|
}: {
|
||||||
|
root: {}
|
||||||
|
path: Array<string | number>
|
||||||
|
}): Pointer<O>
|
||||||
|
function pointer(args: {root: {}; path?: Array<string | number>}) {
|
||||||
|
const meta: PointerMeta = {
|
||||||
|
root: args.root as $IntentionalAny,
|
||||||
|
path: args.path ?? [],
|
||||||
|
}
|
||||||
|
const hiddenObj = {}
|
||||||
|
pointerMetaWeakMap.set(hiddenObj, meta)
|
||||||
|
return new Proxy(hiddenObj, handler) as Pointer<$IntentionalAny>
|
||||||
|
}
|
||||||
|
|
||||||
|
export default pointer
|
1
packages/dataverse2/src/setupTestEnv.ts
Normal file
1
packages/dataverse2/src/setupTestEnv.ts
Normal file
|
@ -0,0 +1 @@
|
||||||
|
export {}
|
6
packages/dataverse2/src/types.ts
Normal file
6
packages/dataverse2/src/types.ts
Normal file
|
@ -0,0 +1,6 @@
|
||||||
|
/** For `any`s that aren't meant to stay `any`*/
|
||||||
|
export type $FixMe = any
|
||||||
|
/** For `any`s that we don't care about */
|
||||||
|
export type $IntentionalAny = any
|
||||||
|
|
||||||
|
export type VoidFn = () => void
|
19
packages/dataverse2/src/utils/Emitter.test.ts
Normal file
19
packages/dataverse2/src/utils/Emitter.test.ts
Normal file
|
@ -0,0 +1,19 @@
|
||||||
|
import Emitter from './Emitter'
|
||||||
|
|
||||||
|
describe.skip('DataVerse2.Emitter', () => {
|
||||||
|
it('should work', () => {
|
||||||
|
const e: Emitter<string> = new Emitter()
|
||||||
|
e.emit('no one will see this')
|
||||||
|
e.emit('nor this')
|
||||||
|
|
||||||
|
const tappedEvents: string[] = []
|
||||||
|
const untap = e.tappable.tap((payload) => {
|
||||||
|
tappedEvents.push(payload)
|
||||||
|
})
|
||||||
|
e.emit('foo')
|
||||||
|
e.emit('bar')
|
||||||
|
untap()
|
||||||
|
e.emit('baz')
|
||||||
|
expect(tappedEvents).toMatchObject(['foo', 'bar'])
|
||||||
|
})
|
||||||
|
})
|
55
packages/dataverse2/src/utils/Emitter.ts
Normal file
55
packages/dataverse2/src/utils/Emitter.ts
Normal file
|
@ -0,0 +1,55 @@
|
||||||
|
import Tappable from './Tappable'
|
||||||
|
|
||||||
|
type Tapper<V> = (v: V) => void
|
||||||
|
type Untap = () => void
|
||||||
|
|
||||||
|
export default class Emitter<V> {
|
||||||
|
private _tappers: Map<any, (v: V) => void>
|
||||||
|
private _lastTapperId: number
|
||||||
|
readonly tappable: Tappable<V>
|
||||||
|
private _onNumberOfTappersChangeListener: undefined | ((n: number) => void)
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this._lastTapperId = 0
|
||||||
|
this._tappers = new Map()
|
||||||
|
this.tappable = new Tappable({
|
||||||
|
tapToSource: (cb: Tapper<V>) => {
|
||||||
|
return this._tap(cb)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
_tap(cb: Tapper<V>): Untap {
|
||||||
|
const tapperId = this._lastTapperId++
|
||||||
|
this._tappers.set(tapperId, cb)
|
||||||
|
this._onNumberOfTappersChangeListener &&
|
||||||
|
this._onNumberOfTappersChangeListener(this._tappers.size)
|
||||||
|
return () => {
|
||||||
|
this._removeTapperById(tapperId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_removeTapperById(id: number) {
|
||||||
|
const oldSize = this._tappers.size
|
||||||
|
this._tappers.delete(id)
|
||||||
|
const newSize = this._tappers.size
|
||||||
|
if (oldSize !== newSize) {
|
||||||
|
this._onNumberOfTappersChangeListener &&
|
||||||
|
this._onNumberOfTappersChangeListener(this._tappers.size)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
emit(payload: V) {
|
||||||
|
this._tappers.forEach((cb) => {
|
||||||
|
cb(payload)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
hasTappers() {
|
||||||
|
return this._tappers.size !== 0
|
||||||
|
}
|
||||||
|
|
||||||
|
onNumberOfTappersChange(cb: (n: number) => void) {
|
||||||
|
this._onNumberOfTappersChangeListener = cb
|
||||||
|
}
|
||||||
|
}
|
56
packages/dataverse2/src/utils/EventEmitter.ts
Normal file
56
packages/dataverse2/src/utils/EventEmitter.ts
Normal file
|
@ -0,0 +1,56 @@
|
||||||
|
import forEach from 'lodash-es/forEach'
|
||||||
|
import without from 'lodash-es/without'
|
||||||
|
import type {$FixMe} from '../types'
|
||||||
|
|
||||||
|
type Listener = (v: $FixMe) => void
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A simple barebones event emitter
|
||||||
|
*/
|
||||||
|
export default class EventEmitter {
|
||||||
|
_listenersByType: {[eventName: string]: Array<Listener>}
|
||||||
|
constructor() {
|
||||||
|
this._listenersByType = {}
|
||||||
|
}
|
||||||
|
|
||||||
|
addEventListener(eventName: string, listener: Listener) {
|
||||||
|
const listeners =
|
||||||
|
this._listenersByType[eventName] ||
|
||||||
|
(this._listenersByType[eventName] = [])
|
||||||
|
|
||||||
|
listeners.push(listener)
|
||||||
|
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
removeEventListener(eventName: string, listener: Listener) {
|
||||||
|
const listeners = this._listenersByType[eventName]
|
||||||
|
if (listeners) {
|
||||||
|
const newListeners = without(listeners, listener)
|
||||||
|
if (newListeners.length === 0) {
|
||||||
|
delete this._listenersByType[eventName]
|
||||||
|
} else {
|
||||||
|
this._listenersByType[eventName] = newListeners
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
emit(eventName: string, payload: unknown) {
|
||||||
|
const listeners = this.getListenersFor(eventName)
|
||||||
|
if (listeners) {
|
||||||
|
forEach(listeners, (listener) => {
|
||||||
|
listener(payload)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getListenersFor(eventName: string) {
|
||||||
|
return this._listenersByType[eventName]
|
||||||
|
}
|
||||||
|
|
||||||
|
hasListenersFor(eventName: string) {
|
||||||
|
return this.getListenersFor(eventName) ? true : false
|
||||||
|
}
|
||||||
|
}
|
133
packages/dataverse2/src/utils/PathBasedReducer.ts
Normal file
133
packages/dataverse2/src/utils/PathBasedReducer.ts
Normal file
|
@ -0,0 +1,133 @@
|
||||||
|
export type PathBasedReducer<S, ReturnType> = {
|
||||||
|
<
|
||||||
|
A0 extends keyof S,
|
||||||
|
A1 extends keyof S[A0],
|
||||||
|
A2 extends keyof S[A0][A1],
|
||||||
|
A3 extends keyof S[A0][A1][A2],
|
||||||
|
A4 extends keyof S[A0][A1][A2][A3],
|
||||||
|
A5 extends keyof S[A0][A1][A2][A3][A4],
|
||||||
|
A6 extends keyof S[A0][A1][A2][A3][A4][A5],
|
||||||
|
A7 extends keyof S[A0][A1][A2][A3][A4][A5][A6],
|
||||||
|
A8 extends keyof S[A0][A1][A2][A3][A4][A5][A6][A7],
|
||||||
|
A9 extends keyof S[A0][A1][A2][A3][A4][A5][A6][A7][A8],
|
||||||
|
A10 extends keyof S[A0][A1][A2][A3][A4][A5][A6][A7][A8][A9],
|
||||||
|
>(
|
||||||
|
addr: [A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10],
|
||||||
|
reducer: (
|
||||||
|
d: S[A0][A1][A2][A3][A4][A5][A6][A7][A8][A9][A10],
|
||||||
|
) => S[A0][A1][A2][A3][A4][A5][A6][A7][A8][A9][A10],
|
||||||
|
): ReturnType
|
||||||
|
|
||||||
|
<
|
||||||
|
A0 extends keyof S,
|
||||||
|
A1 extends keyof S[A0],
|
||||||
|
A2 extends keyof S[A0][A1],
|
||||||
|
A3 extends keyof S[A0][A1][A2],
|
||||||
|
A4 extends keyof S[A0][A1][A2][A3],
|
||||||
|
A5 extends keyof S[A0][A1][A2][A3][A4],
|
||||||
|
A6 extends keyof S[A0][A1][A2][A3][A4][A5],
|
||||||
|
A7 extends keyof S[A0][A1][A2][A3][A4][A5][A6],
|
||||||
|
A8 extends keyof S[A0][A1][A2][A3][A4][A5][A6][A7],
|
||||||
|
A9 extends keyof S[A0][A1][A2][A3][A4][A5][A6][A7][A8],
|
||||||
|
>(
|
||||||
|
addr: [A0, A1, A2, A3, A4, A5, A6, A7, A8, A9],
|
||||||
|
reducer: (
|
||||||
|
d: S[A0][A1][A2][A3][A4][A5][A6][A7][A8][A9],
|
||||||
|
) => S[A0][A1][A2][A3][A4][A5][A6][A7][A8][A9],
|
||||||
|
): ReturnType
|
||||||
|
|
||||||
|
<
|
||||||
|
A0 extends keyof S,
|
||||||
|
A1 extends keyof S[A0],
|
||||||
|
A2 extends keyof S[A0][A1],
|
||||||
|
A3 extends keyof S[A0][A1][A2],
|
||||||
|
A4 extends keyof S[A0][A1][A2][A3],
|
||||||
|
A5 extends keyof S[A0][A1][A2][A3][A4],
|
||||||
|
A6 extends keyof S[A0][A1][A2][A3][A4][A5],
|
||||||
|
A7 extends keyof S[A0][A1][A2][A3][A4][A5][A6],
|
||||||
|
A8 extends keyof S[A0][A1][A2][A3][A4][A5][A6][A7],
|
||||||
|
>(
|
||||||
|
addr: [A0, A1, A2, A3, A4, A5, A6, A7, A8],
|
||||||
|
reducer: (
|
||||||
|
d: S[A0][A1][A2][A3][A4][A5][A6][A7][A8],
|
||||||
|
) => S[A0][A1][A2][A3][A4][A5][A6][A7][A8],
|
||||||
|
): ReturnType
|
||||||
|
|
||||||
|
<
|
||||||
|
A0 extends keyof S,
|
||||||
|
A1 extends keyof S[A0],
|
||||||
|
A2 extends keyof S[A0][A1],
|
||||||
|
A3 extends keyof S[A0][A1][A2],
|
||||||
|
A4 extends keyof S[A0][A1][A2][A3],
|
||||||
|
A5 extends keyof S[A0][A1][A2][A3][A4],
|
||||||
|
A6 extends keyof S[A0][A1][A2][A3][A4][A5],
|
||||||
|
A7 extends keyof S[A0][A1][A2][A3][A4][A5][A6],
|
||||||
|
>(
|
||||||
|
addr: [A0, A1, A2, A3, A4, A5, A6, A7],
|
||||||
|
reducer: (
|
||||||
|
d: S[A0][A1][A2][A3][A4][A5][A6][A7],
|
||||||
|
) => S[A0][A1][A2][A3][A4][A5][A6][A7],
|
||||||
|
): ReturnType
|
||||||
|
|
||||||
|
<
|
||||||
|
A0 extends keyof S,
|
||||||
|
A1 extends keyof S[A0],
|
||||||
|
A2 extends keyof S[A0][A1],
|
||||||
|
A3 extends keyof S[A0][A1][A2],
|
||||||
|
A4 extends keyof S[A0][A1][A2][A3],
|
||||||
|
A5 extends keyof S[A0][A1][A2][A3][A4],
|
||||||
|
A6 extends keyof S[A0][A1][A2][A3][A4][A5],
|
||||||
|
>(
|
||||||
|
addr: [A0, A1, A2, A3, A4, A5, A6],
|
||||||
|
reducer: (
|
||||||
|
d: S[A0][A1][A2][A3][A4][A5][A6],
|
||||||
|
) => S[A0][A1][A2][A3][A4][A5][A6],
|
||||||
|
): ReturnType
|
||||||
|
|
||||||
|
<
|
||||||
|
A0 extends keyof S,
|
||||||
|
A1 extends keyof S[A0],
|
||||||
|
A2 extends keyof S[A0][A1],
|
||||||
|
A3 extends keyof S[A0][A1][A2],
|
||||||
|
A4 extends keyof S[A0][A1][A2][A3],
|
||||||
|
A5 extends keyof S[A0][A1][A2][A3][A4],
|
||||||
|
>(
|
||||||
|
addr: [A0, A1, A2, A3, A4, A5],
|
||||||
|
reducer: (d: S[A0][A1][A2][A3][A4][A5]) => S[A0][A1][A2][A3][A4][A5],
|
||||||
|
): ReturnType
|
||||||
|
|
||||||
|
<
|
||||||
|
A0 extends keyof S,
|
||||||
|
A1 extends keyof S[A0],
|
||||||
|
A2 extends keyof S[A0][A1],
|
||||||
|
A3 extends keyof S[A0][A1][A2],
|
||||||
|
A4 extends keyof S[A0][A1][A2][A3],
|
||||||
|
>(
|
||||||
|
addr: [A0, A1, A2, A3, A4],
|
||||||
|
reducer: (d: S[A0][A1][A2][A3][A4]) => S[A0][A1][A2][A3][A4],
|
||||||
|
): ReturnType
|
||||||
|
|
||||||
|
<
|
||||||
|
A0 extends keyof S,
|
||||||
|
A1 extends keyof S[A0],
|
||||||
|
A2 extends keyof S[A0][A1],
|
||||||
|
A3 extends keyof S[A0][A1][A2],
|
||||||
|
>(
|
||||||
|
addr: [A0, A1, A2, A3],
|
||||||
|
reducer: (d: S[A0][A1][A2][A3]) => S[A0][A1][A2][A3],
|
||||||
|
): ReturnType
|
||||||
|
|
||||||
|
<A0 extends keyof S, A1 extends keyof S[A0], A2 extends keyof S[A0][A1]>(
|
||||||
|
addr: [A0, A1, A2],
|
||||||
|
reducer: (d: S[A0][A1][A2]) => S[A0][A1][A2],
|
||||||
|
): ReturnType
|
||||||
|
|
||||||
|
<A0 extends keyof S, A1 extends keyof S[A0]>(
|
||||||
|
addr: [A0, A1],
|
||||||
|
reducer: (d: S[A0][A1]) => S[A0][A1],
|
||||||
|
): ReturnType
|
||||||
|
|
||||||
|
<A0 extends keyof S>(addr: [A0], reducer: (d: S[A0]) => S[A0]): ReturnType
|
||||||
|
|
||||||
|
(addr: undefined[], reducer: (d: S) => S): ReturnType
|
||||||
|
}
|
33
packages/dataverse2/src/utils/Stack.ts
Normal file
33
packages/dataverse2/src/utils/Stack.ts
Normal file
|
@ -0,0 +1,33 @@
|
||||||
|
interface Node<Data> {
|
||||||
|
next: undefined | Node<Data>
|
||||||
|
data: Data
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Just a simple LinkedList
|
||||||
|
*/
|
||||||
|
export default class Stack<Data> {
|
||||||
|
_head: undefined | Node<Data>
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this._head = undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
peek() {
|
||||||
|
return this._head && this._head.data
|
||||||
|
}
|
||||||
|
|
||||||
|
pop() {
|
||||||
|
const head = this._head
|
||||||
|
if (!head) {
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
this._head = head.next
|
||||||
|
return head.data
|
||||||
|
}
|
||||||
|
|
||||||
|
push(data: Data) {
|
||||||
|
const node = {next: this._head, data}
|
||||||
|
this._head = node
|
||||||
|
}
|
||||||
|
}
|
91
packages/dataverse2/src/utils/Tappable.ts
Normal file
91
packages/dataverse2/src/utils/Tappable.ts
Normal file
|
@ -0,0 +1,91 @@
|
||||||
|
type Untap = () => void
|
||||||
|
type UntapFromSource = () => void
|
||||||
|
|
||||||
|
interface IProps<V> {
|
||||||
|
tapToSource: (cb: (payload: V) => void) => UntapFromSource
|
||||||
|
}
|
||||||
|
|
||||||
|
type Listener<V> = ((v: V) => void) | (() => void)
|
||||||
|
|
||||||
|
export default class Tappable<V> {
|
||||||
|
private _props: IProps<V>
|
||||||
|
private _tappers: Map<number, {bivarianceHack(v: V): void}['bivarianceHack']>
|
||||||
|
private _untapFromSource: null | UntapFromSource
|
||||||
|
private _lastTapperId: number
|
||||||
|
private _untapFromSourceTimeout: null | NodeJS.Timer = null
|
||||||
|
|
||||||
|
constructor(props: IProps<V>) {
|
||||||
|
this._lastTapperId = 0
|
||||||
|
this._untapFromSource = null
|
||||||
|
this._props = props
|
||||||
|
this._tappers = new Map()
|
||||||
|
}
|
||||||
|
|
||||||
|
private _check() {
|
||||||
|
if (this._untapFromSource) {
|
||||||
|
if (this._tappers.size === 0) {
|
||||||
|
this._scheduleToUntapFromSource()
|
||||||
|
/*
|
||||||
|
* this._untapFromSource()
|
||||||
|
* this._untapFromSource = null
|
||||||
|
*/
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (this._tappers.size !== 0) {
|
||||||
|
this._untapFromSource = this._props.tapToSource(this._cb)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private _scheduleToUntapFromSource() {
|
||||||
|
if (this._untapFromSourceTimeout !== null) return
|
||||||
|
this._untapFromSourceTimeout = setTimeout(() => {
|
||||||
|
this._untapFromSourceTimeout = null
|
||||||
|
if (this._tappers.size === 0) {
|
||||||
|
this._untapFromSource!()
|
||||||
|
|
||||||
|
this._untapFromSource = null
|
||||||
|
}
|
||||||
|
}, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
private _cb: any = (arg: any): void => {
|
||||||
|
this._tappers.forEach((cb) => {
|
||||||
|
cb(arg)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
tap(cb: Listener<V>): Untap {
|
||||||
|
const tapperId = this._lastTapperId++
|
||||||
|
this._tappers.set(tapperId, cb)
|
||||||
|
this._check()
|
||||||
|
return () => {
|
||||||
|
this._removeTapperById(tapperId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* tapImmediate(cb: Listener<V>): Untap {
|
||||||
|
* const ret = this.tap(cb)
|
||||||
|
* return ret
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
|
||||||
|
private _removeTapperById(id: number) {
|
||||||
|
this._tappers.delete(id)
|
||||||
|
this._check()
|
||||||
|
}
|
||||||
|
|
||||||
|
// /**
|
||||||
|
// * @deprecated
|
||||||
|
// */
|
||||||
|
// map<T>(transform: {bivarianceHack(v: V): T}['bivarianceHack']): Tappable<T> {
|
||||||
|
// return new Tappable({
|
||||||
|
// tapToSource: (cb: (v: T) => void) => {
|
||||||
|
// return this.tap((v: $IntentionalAny) => {
|
||||||
|
// return cb(transform(v))
|
||||||
|
// })
|
||||||
|
// },
|
||||||
|
// })
|
||||||
|
// }
|
||||||
|
}
|
12
packages/dataverse2/src/utils/typeTestUtils.ts
Normal file
12
packages/dataverse2/src/utils/typeTestUtils.ts
Normal file
|
@ -0,0 +1,12 @@
|
||||||
|
import type {$IntentionalAny} from '../types'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Useful in type tests, such as: const a: SomeType = _any
|
||||||
|
*/
|
||||||
|
export const _any: $IntentionalAny = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Useful in typeTests. If you want to ensure that value v follows type V,
|
||||||
|
* just write `expectType<V>(v)`
|
||||||
|
*/
|
||||||
|
export const expectType = <T extends unknown>(v: T): T => v
|
42
packages/dataverse2/src/utils/updateDeep.ts
Normal file
42
packages/dataverse2/src/utils/updateDeep.ts
Normal file
|
@ -0,0 +1,42 @@
|
||||||
|
import type {$FixMe, $IntentionalAny} from '../types'
|
||||||
|
|
||||||
|
export default function updateDeep<S>(
|
||||||
|
state: S,
|
||||||
|
path: (string | number | undefined)[],
|
||||||
|
reducer: (...args: $IntentionalAny[]) => $IntentionalAny,
|
||||||
|
): S {
|
||||||
|
if (path.length === 0) return reducer(state)
|
||||||
|
return hoop(state, path as $IntentionalAny, reducer)
|
||||||
|
}
|
||||||
|
|
||||||
|
const hoop = (
|
||||||
|
s: $FixMe,
|
||||||
|
path: (string | number)[],
|
||||||
|
reducer: $FixMe,
|
||||||
|
): $FixMe => {
|
||||||
|
if (path.length === 0) {
|
||||||
|
return reducer(s)
|
||||||
|
}
|
||||||
|
if (Array.isArray(s)) {
|
||||||
|
let [index, ...restOfPath] = path
|
||||||
|
index = parseInt(String(index), 10)
|
||||||
|
if (isNaN(index)) index = 0
|
||||||
|
const oldVal = s[index]
|
||||||
|
const newVal = hoop(oldVal, restOfPath, reducer)
|
||||||
|
if (oldVal === newVal) return s
|
||||||
|
const newS = [...s]
|
||||||
|
newS.splice(index, 1, newVal)
|
||||||
|
return newS
|
||||||
|
} else if (typeof s === 'object' && s !== null) {
|
||||||
|
const [key, ...restOfPath] = path
|
||||||
|
const oldVal = s[key]
|
||||||
|
const newVal = hoop(oldVal, restOfPath, reducer)
|
||||||
|
if (oldVal === newVal) return s
|
||||||
|
const newS = {...s, [key]: newVal}
|
||||||
|
return newS
|
||||||
|
} else {
|
||||||
|
const [key, ...restOfPath] = path
|
||||||
|
|
||||||
|
return {[key]: hoop(undefined, restOfPath, reducer)}
|
||||||
|
}
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue