├── .eslintrc.js ├── .github ├── ISSUE_TEMPLATE │ └── bug_report.md └── workflows │ └── greetings.yml ├── .gitignore ├── .gitlab-ci.yml ├── .prettierrc.json ├── CODE-OF-CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── assets └── pictures │ └── vue-rx.jpg ├── example ├── createObservableMethod.html ├── fromDom.html ├── ref.html ├── subscribeTo.html ├── vStream.html ├── vStream2.html ├── watch.html └── watchAsObservable.html ├── package-lock.json ├── package.json ├── pull_request_template.md ├── rollup.config.js ├── src ├── directives │ └── stream.js ├── index.js ├── methods │ ├── createObservableMethod.js │ ├── fromDomEvent.js │ ├── ref.js │ ├── subscribeTo.js │ ├── watch.js │ └── watchAsObservable.js ├── mixin.js ├── umd-aliases │ ├── operators.js │ └── rxjs.js └── util.js ├── test └── test.js └── types ├── index.d.ts ├── test ├── index.ts └── tsconfig.json ├── tsconfig.json └── typings.json /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | env: { 4 | node: true, 5 | }, 6 | extends: ["plugin:vue/vue3-essential", "eslint:recommended"], 7 | parserOptions: { 8 | ecmaVersion: 2020, 9 | }, 10 | rules: { 11 | "no-console": process.env.NODE_ENV === "production" ? "warn" : "off", 12 | "no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off", 13 | "no-inferrable-types": "off", 14 | "class-name": "off", 15 | "@typescript-eslint/ban-ts-ignore": "off", 16 | "@typescript-eslint/no-var-requires": "off", 17 | "no-var": "off", 18 | "vue/no-ref-as-operand": "off", 19 | }, 20 | overrides: [ 21 | { 22 | files: [ 23 | "**/__tests__/*.{j,t}s?(x)", 24 | "**/tests/unit/**/*.spec.{j,t}s?(x)", 25 | ], 26 | env: { 27 | mocha: true, 28 | }, 29 | }, 30 | ], 31 | }; 32 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/workflows/greetings.yml: -------------------------------------------------------------------------------- 1 | name: Greetings 2 | 3 | on: [pull_request, issues] 4 | 5 | jobs: 6 | greeting: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/first-interaction@v1 10 | with: 11 | repo-token: ${{ secrets.GITHUB_TOKEN }} 12 | issue-message: 'Hi ! Thanks for this issue, i will look at it quickly !'' first issue' 13 | pr-message: 'Hi ! Thanks for your awesome contribution, i will look at it quickly !'' first pr' 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dist 2 | node_modules 3 | coverage 4 | .DS_Store 5 | .idea 6 | .vscode 7 | .nyc_output -------------------------------------------------------------------------------- /.gitlab-ci.yml: -------------------------------------------------------------------------------- 1 | image: node:latest 2 | 3 | stages: 4 | - test 5 | 6 | test: 7 | script: 8 | - npm install 9 | - npm run build 10 | - npm run test 11 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "prettier.singleQuote": true, 3 | "prettier.bracketSpacing": true, 4 | "prettier.enable": true, 5 | "prettier.semi": false, 6 | "prettier.useEditorConfig": true 7 | } 8 | -------------------------------------------------------------------------------- /CODE-OF-CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | contact@boucham-amine.fr. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Vue next rx 2 | 3 | First off, thanks for taking the time to contribute! ❤️ 4 | 5 | All types of contributions are encouraged and valued. See the [Table of Contents](#table-of-contents) for different ways to help and details about how this project handles them. Please make sure to read the relevant section before making your contribution. It will make it a lot easier for us maintainers and smooth out the experience for all involved. The community looks forward to your contributions. 🎉 6 | 7 | > And if you like the project, but just don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about: 8 | > - Star the project 9 | > - Tweet about it 10 | > - Refer this project in your project's readme 11 | > - Mention the project at local meetups and tell your friends/colleagues 12 | 13 | 14 | ## Table of Contents 15 | 16 | - [I Have a Question](#i-have-a-question) 17 | - [I Want To Contribute](#i-want-to-contribute) 18 | - [Reporting Bugs](#reporting-bugs) 19 | - [Suggesting Enhancements](#suggesting-enhancements) 20 | - [Your First Code Contribution](#your-first-code-contribution) 21 | - [Improving The Documentation](#improving-the-documentation) 22 | - [Styleguides](#styleguides) 23 | - [Commit Messages](#commit-messages) 24 | - [Join The Project Team](#join-the-project-team) 25 | 26 | 27 | 28 | ## I Have a Question 29 | 30 | > If you want to ask a question, we assume that you have read the available [Documentation](https://github.com/NOPR9D/vue-next-rx/blob/main/README.md). 31 | 32 | Before you ask a question, it is best to search for existing [Issues](https://github.com/NOPR9D/vue-next-rxissues) that might help you. In case you have found a suitable issue and still need clarification, you can write your question in this issue. It is also advisable to search the internet for answers first. 33 | 34 | If you then still feel the need to ask a question and need clarification, we recommend the following: 35 | 36 | - Open an [Issue](https://github.com/NOPR9D/vue-next-rxissues/new). 37 | - Provide as much context as you can about what you're running into. 38 | - Provide project and platform versions (nodejs, npm, etc), depending on what seems relevant. 39 | 40 | We will then take care of the issue as soon as possible. 41 | 42 | 56 | 57 | ## I Want To Contribute 58 | 59 | > ### Legal Notice 60 | > When contributing to this project, you must agree that you have authored 100% of the content, that you have the necessary rights to the content and that the content you contribute may be provided under the project license. 61 | 62 | ### Reporting Bugs 63 | 64 | 65 | #### Before Submitting a Bug Report 66 | 67 | A good bug report shouldn't leave others needing to chase you up for more information. Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report. Please complete the following steps in advance to help us fix any potential bug as fast as possible. 68 | 69 | - Make sure that you are using the latest version. 70 | - Determine if your bug is really a bug and not an error on your side e.g. using incompatible environment components/versions (Make sure that you have read the [documentation](https://github.com/NOPR9D/vue-next-rx/blob/main/README.md). If you are looking for support, you might want to check [this section](#i-have-a-question)). 71 | - To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error in the [bug tracker](https://github.com/NOPR9D/vue-next-rxissues?q=label%3Abug). 72 | - Also make sure to search the internet (including Stack Overflow) to see if users outside of the GitHub community have discussed the issue. 73 | - Collect information about the bug: 74 | - Stack trace (Traceback) 75 | - OS, Platform and Version (Windows, Linux, macOS, x86, ARM) 76 | - Version of the interpreter, compiler, SDK, runtime environment, package manager, depending on what seems relevant. 77 | - Possibly your input and the output 78 | - Can you reliably reproduce the issue? And can you also reproduce it with older versions? 79 | 80 | 81 | #### How Do I Submit a Good Bug Report? 82 | 83 | > You must never report security related issues, vulnerabilities or bugs to the issue tracker, or elsewhere in public. Instead sensitive bugs must be sent by email to . 84 | 85 | 86 | We use GitHub issues to track bugs and errors. If you run into an issue with the project: 87 | 88 | - Open an [Issue](https://github.com/NOPR9D/vue-next-rxissues/new). (Since we can't be sure at this point whether it is a bug or not, we ask you not to talk about a bug yet and not to label the issue.) 89 | - Explain the behavior you would expect and the actual behavior. 90 | - Please provide as much context as possible and describe the *reproduction steps* that someone else can follow to recreate the issue on their own. This usually includes your code. For good bug reports you should isolate the problem and create a reduced test case. 91 | - Provide the information you collected in the previous section. 92 | 93 | Once it's filed: 94 | 95 | - The project team will label the issue accordingly. 96 | - A team member will try to reproduce the issue with your provided steps. If there are no reproduction steps or no obvious way to reproduce the issue, the team will ask you for those steps and mark the issue as `needs-repro`. Bugs with the `needs-repro` tag will not be addressed until they are reproduced. 97 | - If the team is able to reproduce the issue, it will be marked `needs-fix`, as well as possibly other tags (such as `critical`), and the issue will be left to be [implemented by someone](#your-first-code-contribution). 98 | 99 | 100 | 101 | 102 | ### Suggesting Enhancements 103 | 104 | This section guides you through submitting an enhancement suggestion for Vue next rx, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community to understand your suggestion and find related suggestions. 105 | 106 | 107 | #### Before Submitting an Enhancement 108 | 109 | - Make sure that you are using the latest version. 110 | - Read the [documentation](https://github.com/NOPR9D/vue-next-rx/blob/main/README.md) carefully and find out if the functionality is already covered, maybe by an individual configuration. 111 | - Perform a [search](https://github.com/NOPR9D/vue-next-rxissues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one. 112 | - Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset. If you're just targeting a minority of users, consider writing an add-on/plugin library. 113 | 114 | 115 | #### How Do I Submit a Good Enhancement Suggestion? 116 | 117 | Enhancement suggestions are tracked as [GitHub issues](https://github.com/NOPR9D/vue-next-rxissues). 118 | 119 | - Use a **clear and descriptive title** for the issue to identify the suggestion. 120 | - Provide a **step-by-step description of the suggested enhancement** in as many details as possible. 121 | - **Describe the current behavior** and **explain which behavior you expected to see instead** and why. At this point you can also tell which alternatives do not work for you. 122 | - You may want to **include screenshots and animated GIFs** which help you demonstrate the steps or point out the part which the suggestion is related to. You can use [this tool](https://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux. 123 | - **Explain why this enhancement would be useful** to most Vue next rx users. You may also want to point out the other projects that solved it better and which could serve as inspiration. 124 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2020-present Boucham Amine 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # vue-next-rx 2 | 3 |
4 | 5 |
6 | 7 | ### [RxJS v7](https://github.com/ReactiveX/rxjs) integration for [Vue next]() 8 | 9 |
10 | 11 | ![](https://img.shields.io/github/license/NOPR9D/vue-next-rx) 12 | ![](https://gitlab.com/nopr3d/vue-next-rx/badges/main/pipeline.svg) 13 | 14 |
15 | 16 | > **NOTE** 17 | > 18 | > - vue-next-rx only works with RxJS v6+ by default. If you want to keep using RxJS v5 style code, install `rxjs-compat`. 19 | 20 | --- 21 | 22 | # Installation 23 | 24 | #### NPM + ES2015 or more 25 | 26 | **`rxjs` is required as a peer dependency.** 27 | 28 | ```bash 29 | npm install vue @nopr3d/vue-next-rx rxjs --save 30 | ``` 31 | 32 | ```js 33 | import Vue from "vue"; 34 | import VueNextRx from "@nopr3d/vue-next-rx"; 35 | 36 | Vue.use(VueNextRx); 37 | ``` 38 | 39 |
40 | 41 | When bundling via webpack, `dist/vue-next-rx.esm.js` is used by default. It imports the minimal amount of Rx operators and ensures small bundle sizes. 42 | 43 | To use in a browser environment, use the UMD build `dist/vue-next-rx.js`. When in a browser environment, the UMD build assumes `window.rxjs` to be already present, so make sure to include `vue-next-rx.js` after Vue.js and RxJS. It also installs itself automatically if `window.Vue` is present. 44 | 45 | Example: 46 | 47 | ```html 48 | 49 | 50 | 51 |
52 |
53 | 54 |
55 |
56 | 69 | ``` 70 | 71 |
72 | 73 | --- 74 | 75 | # Usage 76 | 77 |
78 | 79 | # Subscriptions 80 | 81 | ```js 82 | // Expose `Subject` with domStream, use them in subscriptions functions 83 | export default defineComponent({ 84 | name: "Home", 85 | domStreams: ["click$"], 86 | subscriptions() { 87 | return { 88 | count: this.click$.pipe( 89 | map(() => 1), 90 | startWith(0), 91 | scan((total, change) => total + change) 92 | ), 93 | }; 94 | }); 95 | ``` 96 | 97 | ```html 98 |
99 | 100 |
101 | 102 |
{{count}}
103 | 104 | ``` 105 | 106 | ### Or 107 | 108 |
109 | 110 | ```js 111 | // Expose `Subject` with domStream, use them in subscriptions functions 112 | export default defineComponent({ 113 | name: "Home", 114 | domStreams: ["action$"], 115 | subscriptions() { 116 | this.action$.pipe(map(() => "Click Event !")).subscribe(console.log); 117 | // On click will print "Click Event" 118 | }, 119 | }); 120 | ``` 121 | 122 | ## Tips 123 | 124 | You can get the data by simply plucking it from the source stream: 125 | 126 | ```js 127 | const actionData$ = this.action$.pipe(pluck("data")); 128 | ``` 129 | 130 | You can bind Subject by this way 131 | 132 | ```html // Bind with stream directives 133 | 134 | or 135 | 136 | ``` 137 | 138 |
139 | 140 | --- 141 | 142 | # Ref 143 | 144 | ```js 145 | import { ref } from "@nopr3d/vue-next-rx"; 146 | 147 | // use ref like an Rx Subject 148 | export default defineComponent({ 149 | name: "Home", 150 | components: {}, 151 | setup() { 152 | const msg = ref("Message exemple"); 153 | 154 | setTimeout(() => { 155 | msg.value = "New message !"; 156 | }, 2000); 157 | 158 | msg.subscribe((value) => { 159 | console.log(value); // After 2s will print : New message ! 160 | }); 161 | 162 | return { msg }; 163 | }, 164 | }); 165 | ``` 166 | 167 | ```html 168 | 169 | 170 |
{{ msg }}
171 | ``` 172 | 173 | --- 174 | 175 |
176 | 177 | # Watch 178 | 179 | ```js 180 | import { ref, watch } from "@nopr3d/vue-next-rx"; 181 | 182 | export default defineComponent({ 183 | name: "Home", 184 | components: {}, 185 | setup() { 186 | const msg = ref("Message exemple"); 187 | 188 | watch(msg).subscribe((val) => { 189 | console.log(val); // After 2s will print : New message ! 190 | }); 191 | 192 | setTimeout(() => { 193 | msg.value = "New message !"; 194 | }, 2000); 195 | 196 | return { msg }; 197 | }, 198 | }); 199 | ``` 200 | 201 | ```html 202 | 203 | 204 |
{{ msg }}
205 | ``` 206 | 207 | --- 208 | 209 |
210 | 211 | # Other API Methods 212 | 213 |
214 | 215 | ## `$watchAsObservable(expOrFn, [options])` 216 | 217 | This is a prototype method added to instances. You can use it to create an observable from a Data. The emitted value is in the format of `{ newValue, oldValue }`: 218 | 219 | ```js 220 | import { ref } from "@nopr3d/vue-next-rx"; 221 | 222 | export default defineComponent({ 223 | name: "Home", 224 | setup() { 225 | const msg = ref("Old Message"); 226 | setTimeout(() => (msg.value = "New message incomming !"), 1000); 227 | return { msg }; 228 | }, 229 | subscriptions() { 230 | return { 231 | oldMsg: this.$watchAsObservable("msg").pipe(pluck("oldValue")), 232 | }; 233 | }, 234 | }); 235 | ``` 236 | 237 | ```html 238 | 239 | 240 |
{{ msg }}
241 | 242 |
{{oldMsg}}
243 | 244 | ``` 245 | 246 | --- 247 | 248 | ## `$subscribeTo(observable, next, error, complete)` 249 | 250 | This is a prototype method added to instances. You can use it to subscribe to an observable, but let VueNextRx manage the dispose/unsubscribe. 251 | 252 | ```js 253 | import { interval } from "rxjs"; 254 | 255 | const vm = new Vue({ 256 | mounted() { 257 | this.$subscribeTo(interval(1000), function (count) { 258 | console.log(count); 259 | }); 260 | }, 261 | }); 262 | ``` 263 | 264 | ## `$fromDOMEvent(selector, event)` 265 | 266 | This is a prototype method added to instances. Use it to create an observable from DOM events within the instances' element. This is similar to `Rx.Observable.fromEvent`, but usable inside the `subscriptions` function even before the DOM is actually rendered. 267 | 268 | `selector` is for finding descendant nodes under the component root element, if you want to listen to events from root element itself, pass `null` as first argument. 269 | 270 | ```js 271 | import { pluck } from "rxjs/operators"; 272 | 273 | const vm = new Vue({ 274 | subscriptions() { 275 | return { 276 | inputValue: this.$fromDOMEvent("input", "keyup").pipe( 277 | pluck("target", "value") 278 | ), 279 | }; 280 | }, 281 | }); 282 | ``` 283 | 284 | ```html 285 |
286 |
{{inputValue}}
287 | ``` 288 | 289 | --- 290 | 291 | ## `$createObservableMethod(methodName)` 292 | 293 | Convert function calls to observable sequence which emits the call arguments. 294 | 295 | This is a prototype method added to instances. Use it to create a shared hot observable from a function name. The function will be assigned as a vm method. 296 | 297 | ```html 298 | 299 | ``` 300 | 301 | ```js 302 | const vm = new Vue({ 303 | subscriptions() { 304 | return { 305 | // requires `share` operator 306 | formData: this.$createObservableMethod("submitHandler"), 307 | }; 308 | }, 309 | }); 310 | ``` 311 | 312 | You can use the `observableMethods` option to make it more declarative: 313 | 314 | ```js 315 | new Vue({ 316 | observableMethods: { 317 | submitHandler: "submitHandler$", 318 | // or with Array shothand: ['submitHandler'] 319 | }, 320 | }); 321 | ``` 322 | 323 | The above will automatically create two things on the instance: 324 | 325 | 1. A `submitHandler` method which can be bound to in template with `v-on`; 326 | 2. A `submitHandler$` observable which will be the stream emitting calls to `submitHandler`. 327 | 328 | [example](https://github.com/NOPR9D/vue-next-rx/blob/main/example/createObservableMethod.html) 329 | 330 | --- 331 | 332 | ## Example 333 | 334 | See `/examples` for some simple examples. 335 | 336 |
337 | 338 | --- 339 | 340 | ## Test 341 | 342 | Test look goods, feel free to open an issue ! 343 | 344 | ![](https://i.ibb.co/17mtk34/testsPNG.png) 345 | 346 | --- 347 | 348 | ### Contributors 349 | 350 |
351 |
352 | 353 | 354 |
NOPR9D
355 |
356 |
357 | 358 | 359 |
AlvinTCH
360 |
361 |
362 |
363 | 364 | --- 365 | 366 | ## License 367 | 368 | [MIT](http://opensource.org/licenses/MIT) 369 | 370 | --- 371 | -------------------------------------------------------------------------------- /assets/pictures/vue-rx.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mylabz-xyz/vue-next-rx/3a142d633cdf1de02593a0639ea4887afa237234/assets/pictures/vue-rx.jpg -------------------------------------------------------------------------------- /example/createObservableMethod.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 |
{{ count }}
8 | 9 | 10 | 11 | 12 | 13 | 14 |
{{ $data }}
15 |
16 | 43 | -------------------------------------------------------------------------------- /example/fromDom.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 |
8 |
9 |
{{inputValue}}
10 |
11 |
12 | 26 | -------------------------------------------------------------------------------- /example/ref.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 |
8 |
{{ tick }}
9 |
10 |
11 | 32 | -------------------------------------------------------------------------------- /example/subscribeTo.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 |
8 |
9 | -------------------------------------------------------------------------------- /example/vStream.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 |
8 | 9 |
10 |
11 | 24 | -------------------------------------------------------------------------------- /example/vStream2.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 |
8 |
9 | 10 |
11 | 12 |
{{count}}
13 |
14 |
15 | 34 | -------------------------------------------------------------------------------- /example/watch.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 |
8 |
{{ tick }}
9 |
10 |
11 | 31 | -------------------------------------------------------------------------------- /example/watchAsObservable.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 |
8 |
{{ msg }}
9 |
{{oldMsg}}
10 |
11 |
12 | 31 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@nopr3d/vue-next-rx", 3 | "version": "1.0.12", 4 | "description": "RxJs for Vue 3", 5 | "author": "Boucham Amine", 6 | "license": "MIT", 7 | "bugs": { 8 | "url": "https://github.com/NOPR9D/vue-next-rx/issues" 9 | }, 10 | "homepage": "https://github.com/NOPR9D/vue-next-rx#readme", 11 | "main": "dist/vue-next-rx.js", 12 | "module": "dist/vue-next-rx.esm.js", 13 | "sideEffects": false, 14 | "files": [ 15 | "types/*.d.ts" 16 | ], 17 | "typings": "types/index.d.ts", 18 | "scripts": { 19 | "dev": "rollup -c rollup.config.js -w", 20 | "build": "rollup -c rollup.config.js", 21 | "publish": "npm publish --access public", 22 | "lint": "eslint src test example", 23 | "dev:test": "jest --watch", 24 | "test": "jest" 25 | }, 26 | "devDependencies": { 27 | "@rollup/plugin-alias": "^3.1.1", 28 | "@rollup/plugin-buble": "^0.21.3", 29 | "@typescript-eslint/eslint-plugin": "^4.9.1", 30 | "@typescript-eslint/parser": "^4.9.1", 31 | "@vue/eslint-config-typescript": "^7.0.0", 32 | "@vue/test-utils": "^2.0.0-beta.12", 33 | "buble": "^0.20.0", 34 | "eslint": "^7.2.0", 35 | "eslint-plugin-vue": "^7.2.0", 36 | "jest": "^26.6.3", 37 | "mocha": "^8.2.1", 38 | "nyc": "^15.1.0", 39 | "prettier": "^2.2.1", 40 | "rollup": "^2.34.2", 41 | "rxjs": "^7.0.0", 42 | "typescript": "^2.8.2", 43 | "vue": "^3.2.0" 44 | }, 45 | "peerDependencies": { 46 | "rxjs": "^7.0.0", 47 | "vue": "^3.0.0" 48 | }, 49 | "repository": { 50 | "type": "git", 51 | "url": "git+https://github.com/NOPR9D/vue-next-rx.git" 52 | }, 53 | "keywords": [ 54 | "vue", 55 | "vue 3", 56 | "vue3", 57 | "vue next", 58 | "rx", 59 | "rxjs", 60 | "composition-api", 61 | "composition", 62 | "pure", 63 | "hooks", 64 | "store", 65 | "support" 66 | ] 67 | } 68 | -------------------------------------------------------------------------------- /pull_request_template.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Description 4 | 5 | 6 | ## Motivation and Context 7 | 8 | 9 | 10 | ## How Has This Been Tested? 11 | 12 | 13 | 14 | 15 | ## Screenshots (if appropriate): 16 | 17 | ## Types of Changes 18 | 19 | - [ ] Bug fix (non-breaking change that fixes an issue) 20 | - [ ] New feature (non-breaking change that adds functionality) 21 | - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) 22 | 23 | ## Checklist: 24 | 25 | 26 | - [ ] My code follows the code style of this project. 27 | - [ ] My change requires a change to the documentation. 28 | - [ ] I have updated the documentation accordingly. 29 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | const alias = require("@rollup/plugin-alias"); 2 | const buble = require("@rollup/plugin-buble"); 3 | 4 | module.exports = [ 5 | { 6 | input: "src/index.js", 7 | output: { 8 | file: "dist/vue-next-rx.esm.js", 9 | exports: "named", 10 | format: "es", 11 | globals: { 12 | vue: "Vue", 13 | rxjs: "rxjs", 14 | "rxjs/operators": "rxjs/operators", 15 | }, 16 | }, 17 | plugins: [ 18 | buble(), 19 | alias({ 20 | "rxjs/operators": "src/umd-aliases/operators.js", 21 | rxjs: "src/umd-aliases/rxjs.js", 22 | }), 23 | ], 24 | external: ["vue", "rxjs", "rxjs/operators"], 25 | }, 26 | { 27 | input: "src/index.js", 28 | output: { 29 | file: "dist/vue-next-rx.js", 30 | format: "umd", 31 | exports: "named", 32 | name: "VueNextRx", 33 | globals: { 34 | vue: "Vue", 35 | rxjs: "rxjs", 36 | "rxjs/operators": "rxjs.operators", 37 | }, 38 | }, 39 | plugins: [ 40 | buble(), 41 | alias({ 42 | "rxjs/operators": "src/umd-aliases/operators.js", 43 | rxjs: "src/umd-aliases/rxjs.js", 44 | }), 45 | ], 46 | external: ["vue", "rxjs", "rxjs/operators"], 47 | }, 48 | ]; 49 | -------------------------------------------------------------------------------- /src/directives/stream.js: -------------------------------------------------------------------------------- 1 | import { isObserver, warn, getKey } from "../util"; 2 | import { fromEvent } from "rxjs"; 3 | 4 | export default { 5 | // Example ./example/counter_dir.html 6 | mounted(el, binding, vnode) { 7 | let handle = binding.value; 8 | const event = binding.arg; 9 | const streamName = binding.expression; 10 | const modifiers = binding.modifiers; 11 | 12 | if (isObserver(handle)) { 13 | handle = { subject: handle }; 14 | } else if (!handle || !isObserver(handle.subject)) { 15 | warn( 16 | 'Invalid Subject found in directive with key "' + 17 | streamName + 18 | '".' + 19 | streamName + 20 | " should be an instance of Subject or have the " + 21 | "type { subject: Subject, data: any }.", 22 | vnode.context 23 | ); 24 | return; 25 | } 26 | 27 | const modifiersFuncs = { 28 | stop: (e) => e.stopPropagation(), 29 | prevent: (e) => e.preventDefault(), 30 | }; 31 | 32 | var modifiersExists = Object.keys(modifiersFuncs).filter( 33 | (key) => modifiers[key] 34 | ); 35 | 36 | const subject = handle.subject; 37 | const next = (subject.next || subject.onNext).bind(subject); 38 | 39 | if (!modifiers.native && vnode.componentInstance) { 40 | handle.subscription = vnode.componentInstance 41 | .$eventToObservable(event) 42 | .subscribe((e) => { 43 | modifiersExists.forEach((mod) => modifiersFuncs[mod](e)); 44 | next({ 45 | event: e, 46 | data: handle.data, 47 | }); 48 | }); 49 | } else { 50 | const fromEventArgs = handle.options 51 | ? [el, event, handle.options] 52 | : [el, event]; 53 | handle.subscription = fromEvent(...fromEventArgs).subscribe((e) => { 54 | modifiersExists.forEach((mod) => modifiersFuncs[mod](e)); 55 | next({ 56 | event: e, 57 | data: handle.data, 58 | }); 59 | }); 60 | } 61 | 62 | // store handle on element with a unique key for identifying 63 | // multiple v-stream directives on the same node 64 | (el._rxHandles || (el._rxHandles = {}))[getKey(binding)] = handle; 65 | }, 66 | 67 | updated(el, binding) { 68 | const handle = binding.value; 69 | const _handle = el._rxHandles && el._rxHandles[getKey(binding)]; 70 | if (_handle && handle && isObserver(handle.subject)) { 71 | Object.assign(_handle, handle); 72 | } 73 | }, 74 | 75 | unmounted(el, binding) { 76 | const key = getKey(binding); 77 | const handle = el._rxHandles && el._rxHandles[key]; 78 | if (handle) { 79 | if (handle.subscription) { 80 | handle.subscription.unsubscribe(); 81 | } 82 | el._rxHandles[key] = null; 83 | } 84 | }, 85 | }; 86 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import { ref } from "./methods/ref"; 2 | import { watch } from "./methods/watch"; 3 | 4 | import { createObservableMethod } from "./methods/createObservableMethod"; 5 | import { fromDomEvent } from "./methods/fromDomEvent"; 6 | import { subscribeTo } from "./methods/subscribeTo"; 7 | import { watchAsObservable } from "./methods/watchAsObservable"; 8 | 9 | import streamDirective from "./directives/stream"; 10 | 11 | import rxMixin from "./mixin"; 12 | 13 | import { install as _install } from "./util"; 14 | 15 | //TODO: Work also with vue 16 | export default { 17 | install: install, 18 | }; 19 | export let _Vue; 20 | 21 | export function install(Vue) { 22 | _install(Vue); 23 | Vue.mixin(rxMixin); 24 | Vue.directive("stream", streamDirective); 25 | Vue.config.globalProperties.$watchAsObservable = watchAsObservable; 26 | Vue.config.globalProperties.$fromDOMEvent = fromDomEvent; 27 | Vue.config.globalProperties.$subscribeTo = subscribeTo; 28 | Vue.config.globalProperties.$createObservableMethod = createObservableMethod; 29 | Vue.config.optionMergeStrategies.subscriptions = (toVal, fromVal) => { 30 | return fromVal || toVal; 31 | }; 32 | this._Vue = Vue; 33 | } 34 | 35 | // auto install 36 | export { ref, watch }; 37 | -------------------------------------------------------------------------------- /src/methods/createObservableMethod.js: -------------------------------------------------------------------------------- 1 | import { share } from "rxjs/operators"; 2 | import { Observable } from "rxjs"; 3 | import { warn } from "../util"; 4 | 5 | /** 6 | * @name Vue.prototype.$createObservableMethod 7 | * @description Creates an observable from a given function name. 8 | * @param {String} methodName Function name 9 | * @param {Boolean} [passContext] Append the call context at the end of emit data? 10 | * @return {Observable} Hot stream 11 | */ 12 | export function createObservableMethod(methodName, passContext) { 13 | const vm = this; 14 | if (vm[methodName] !== undefined) { 15 | warn( 16 | "Potential bug: " + 17 | `Method ${methodName} already defined on vm and has been overwritten by $createObservableMethod.` + 18 | String(vm[methodName]), 19 | vm 20 | ); 21 | } 22 | 23 | const creator = function (observer) { 24 | vm[methodName] = function () { 25 | const args = Array.from(arguments); 26 | if (passContext) { 27 | args.push(this); 28 | observer.next(args); 29 | } else { 30 | if (args.length <= 1) { 31 | observer.next(args[0]); 32 | } else { 33 | observer.next(args); 34 | } 35 | } 36 | }; 37 | return function () { 38 | delete vm[methodName]; 39 | }; 40 | }; 41 | 42 | // Must be a hot stream otherwise function context may overwrite over and over again 43 | return new Observable(creator).pipe(share()); 44 | } 45 | -------------------------------------------------------------------------------- /src/methods/fromDomEvent.js: -------------------------------------------------------------------------------- 1 | import { Observable, Subscription, NEVER } from "rxjs"; 2 | 3 | export function fromDomEvent(selector, event) { 4 | if (typeof window === "undefined") { 5 | // TODO(benlesh): I'm not sure if this is really what you want here, 6 | // but it's equivalent to what you were doing. You might want EMPTY 7 | return NEVER; 8 | } 9 | 10 | const vm = this; 11 | const doc = document.documentElement; 12 | const obs$ = new Observable((observer) => { 13 | function listener(e) { 14 | if (!vm.$el) return; 15 | if (selector === null && vm.$el === e.target) return observer.next(e); 16 | var els = vm.$el.querySelectorAll(selector); 17 | var el = e.target; 18 | for (var i = 0, len = els.length; i < len; i++) { 19 | if (els[i] === el) return observer.next(e); 20 | } 21 | } 22 | doc.addEventListener(event, listener); 23 | // Returns function which disconnects the $watch expression 24 | return new Subscription(() => { 25 | doc.removeEventListener(event, listener); 26 | }); 27 | }); 28 | 29 | return obs$; 30 | } 31 | -------------------------------------------------------------------------------- /src/methods/ref.js: -------------------------------------------------------------------------------- 1 | import { ref as _ref, watch as _watch, onBeforeUnmount } from "vue"; 2 | import { Subject } from "rxjs"; 3 | 4 | export function ref(value) { 5 | const $ref = _ref(value); 6 | const subject = new Subject(); 7 | $ref.next = subject.next.bind(subject); 8 | $ref.pipe = subject.pipe.bind(subject); 9 | $ref.subscribe = subject.subscribe.bind(subject); 10 | _watch($ref, (newValue) => { 11 | subject.next(newValue); 12 | }); 13 | onBeforeUnmount(() => subject.unsubscribe()); 14 | return $ref; 15 | } 16 | -------------------------------------------------------------------------------- /src/methods/subscribeTo.js: -------------------------------------------------------------------------------- 1 | import { Subscription } from "rxjs"; 2 | 3 | export function subscribeTo(observable, ...subscribeArgs) { 4 | const subscription = observable.subscribe(...subscribeArgs); 5 | (this._subscription || (this._subscription = new Subscription())).add( 6 | subscription 7 | ); 8 | return subscription; 9 | } 10 | -------------------------------------------------------------------------------- /src/methods/watch.js: -------------------------------------------------------------------------------- 1 | import { watch as _watch, onBeforeUnmount } from "vue"; 2 | import { Subject } from "rxjs"; 3 | 4 | export function watch(ref, fn = null) { 5 | const subject = new Subject(); 6 | const $watch = _watch(ref, (val) => { 7 | subject.next(val); 8 | if (fn) fn(val); 9 | }); 10 | $watch.next = subject.next.bind(subject); 11 | $watch.pipe = subject.pipe.bind(subject); 12 | $watch.subscribe = subject.subscribe.bind(subject); 13 | $watch.unsubscribe = subject.unsubscribe.bind(subject); 14 | onBeforeUnmount(() => subject.unsubscribe()); 15 | 16 | return $watch; 17 | } 18 | -------------------------------------------------------------------------------- /src/methods/watchAsObservable.js: -------------------------------------------------------------------------------- 1 | import { Observable, Subscription } from "rxjs"; 2 | 3 | export function watchAsObservable(expOrFn, options) { 4 | const vm = this; 5 | const obs$ = new Observable((observer) => { 6 | let _unwatch; 7 | const watch = () => { 8 | vm.$watch( 9 | expOrFn, 10 | (newValue, oldValue) => { 11 | observer.next({ oldValue: oldValue, newValue: newValue }); 12 | }, 13 | options 14 | ); 15 | }; 16 | 17 | // if $watchAsObservable is called inside the subscriptions function, 18 | // because data hasn't been observed yet, the watcher will not work. 19 | // in that case, wait until created hook to watch. 20 | setTimeout(() => { 21 | watch(); 22 | }, 0); 23 | 24 | // Returns function which disconnects the $watch expression 25 | return new Subscription(() => { 26 | _unwatch && _unwatch(); 27 | }); 28 | }); 29 | 30 | return obs$; 31 | } 32 | -------------------------------------------------------------------------------- /src/mixin.js: -------------------------------------------------------------------------------- 1 | import { uuidv4, warn } from "./util"; 2 | import { Subject, Subscription, isObservable } from "rxjs"; 3 | import { getCurrentInstance } from "vue"; 4 | 5 | export default { 6 | created() { 7 | var vm = this; 8 | const domStreams = vm.$options.domStreams; 9 | 10 | if (domStreams) { 11 | domStreams.forEach((key) => { 12 | vm[key] = new Subject(); 13 | }); 14 | } 15 | 16 | const observableMethods = vm.$options.observableMethods; 17 | if (observableMethods) { 18 | if (Array.isArray(observableMethods)) { 19 | observableMethods.forEach((methodName) => { 20 | vm[methodName + "$"] = vm.$createObservableMethod(methodName); 21 | }); 22 | } else { 23 | Object.keys(observableMethods).forEach((methodName) => { 24 | vm[observableMethods[methodName]] = 25 | vm.$createObservableMethod(methodName); 26 | }); 27 | } 28 | } 29 | 30 | let obs = vm.$options.subscriptions; 31 | if (typeof obs === "function") { 32 | obs = obs.call(vm); 33 | } 34 | if (obs) { 35 | vm.$observables = {}; 36 | vm._subscription = new Subscription(); 37 | Object.keys(obs).forEach((key) => { 38 | vm[key] = undefined; 39 | const ob = (vm.$observables[key] = obs[key]); 40 | if (!isObservable(ob)) { 41 | warn( 42 | 'Invalid Observable found in subscriptions option with key "' + 43 | key + 44 | '".', 45 | vm 46 | ); 47 | return; 48 | } 49 | vm._subscription.add( 50 | obs[key].subscribe( 51 | (value) => { 52 | vm[key] = value; 53 | try { 54 | vm.$forceUpdate(); 55 | } catch (e) { 56 | const currentInst = getCurrentInstance(); 57 | const newKey = uuidv4(); 58 | // try to force new key if force update fails (usually fails when it is created on created hook) 59 | if (currentInst && currentInst.vnode) { 60 | currentInst.vnode.key = newKey; 61 | } else if (vm.$ && vm.$.subTree) { 62 | vm.$.subTree.key = newKey; 63 | } else if (currentInst && currentInst.subTree) { 64 | currentInst.subTree.key = newKey; 65 | } 66 | } 67 | }, 68 | (error) => { 69 | throw error; 70 | } 71 | ) 72 | ); 73 | }); 74 | } 75 | }, 76 | 77 | beforeUnmount() { 78 | if (this._subscription) { 79 | this._subscription.unsubscribe(); 80 | } 81 | }, 82 | }; 83 | -------------------------------------------------------------------------------- /src/umd-aliases/operators.js: -------------------------------------------------------------------------------- 1 | const operators = 2 | typeof require !== "undefined" 3 | ? require("rxjs/operators") 4 | : typeof window !== "undefined" && window.rxjs 5 | ? window.rxjs.operators 6 | : {}; 7 | 8 | const { share } = operators; 9 | 10 | export { share }; 11 | -------------------------------------------------------------------------------- /src/umd-aliases/rxjs.js: -------------------------------------------------------------------------------- 1 | const rxjs = 2 | typeof require !== "undefined" 3 | ? require("rxjs") 4 | : typeof window !== "undefined" 5 | ? window.rxjs 6 | : null; 7 | 8 | if (!rxjs) { 9 | throw new Error(`[vue-rx]: RxJS is not found.`); 10 | } 11 | 12 | const { 13 | Observable, 14 | Subject, 15 | Subscription, 16 | fromEvent, 17 | NEVER, 18 | isObservable, 19 | } = rxjs; 20 | 21 | export { Observable, Subject, Subscription, fromEvent, NEVER, isObservable }; 22 | -------------------------------------------------------------------------------- /src/util.js: -------------------------------------------------------------------------------- 1 | export let Vue; 2 | export let warn = function (error) { 3 | console.log("vue-next-rx : " + error); 4 | }; 5 | 6 | export function install(_Vue) { 7 | Vue = _Vue; 8 | } 9 | 10 | export function isObserver(subject) { 11 | return subject && typeof subject.next === "function"; 12 | } 13 | 14 | export function defineReactive(vm, key, val) { 15 | vm[key] = val; 16 | } 17 | 18 | export function getKey(binding) { 19 | return [binding.arg].concat(Object.keys(binding.modifiers)).join(":"); 20 | } 21 | 22 | export function uuidv4() { 23 | return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) => 24 | ( 25 | c ^ 26 | (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4))) 27 | ).toString(16) 28 | ); 29 | } 30 | -------------------------------------------------------------------------------- /test/test.js: -------------------------------------------------------------------------------- 1 | /* eslint-env jest */ 2 | 3 | "use strict"; 4 | 5 | const { mount, config } = require("@vue/test-utils"); 6 | const VueNextRx = require("../dist/vue-next-rx.js"); 7 | const { Observable } = require("rxjs"); 8 | const { 9 | startWith, 10 | map, 11 | tap, 12 | scan, 13 | merge, 14 | filter, 15 | pluck, 16 | } = require("rxjs/operators"); 17 | 18 | config.global.plugins.push(VueNextRx); 19 | 20 | const defaultTemplate = "
Hello world
"; 21 | const varTemplate = (val) => `
{{${val}}}
`; 22 | 23 | function mock() { 24 | let observer; 25 | const observable = new Observable((_observer) => { 26 | observer = _observer; 27 | }); 28 | return { 29 | ob: observable, 30 | next: (val) => observer.next(val), 31 | }; 32 | } 33 | 34 | function trigger(target, event) { 35 | var e = document.createEvent("HTMLEvents"); 36 | e.initEvent(event, true, true); 37 | target.dispatchEvent(e); 38 | } 39 | 40 | function click(target) { 41 | trigger(target, "click"); 42 | } 43 | 44 | test("Expose observable", () => { 45 | const { ob, next } = mock(); 46 | const component = { 47 | template: defaultTemplate, 48 | subscriptions() { 49 | return { hello: ob.pipe(startWith(0)) }; 50 | }, 51 | }; 52 | const wrapper = mount(component); 53 | 54 | const results = []; 55 | wrapper.componentVM.$observables.hello.subscribe((val) => { 56 | results.push(val); 57 | }); 58 | 59 | next(1); 60 | next(2); 61 | next(3); 62 | expect(results).toEqual([0, 1, 2, 3]); 63 | // Assert the rendered text of the component 64 | expect(wrapper.text()).toContain("Hello world"); 65 | }); 66 | 67 | test("Bind subscriptions to render", (done) => { 68 | const { ob, next } = mock(); 69 | const component = { 70 | template: varTemplate("hello"), 71 | subscriptions() { 72 | return { hello: ob.pipe(startWith("foo")) }; 73 | }, 74 | }; 75 | const wrapper = mount(component); 76 | 77 | expect(wrapper.text()).toBe("foo"); 78 | 79 | next("bar"); 80 | wrapper.componentVM.$nextTick(() => { 81 | expect(wrapper.text()).toBe("bar"); 82 | }); 83 | done(); 84 | }); 85 | 86 | test("subscriptions() has access to component inject", () => { 87 | const { ob } = mock(); 88 | 89 | const component = { 90 | template: varTemplate("hello"), 91 | data() { 92 | return { foo: "FOO" }; 93 | }, 94 | inject: { bar: { default: "BAR" } }, 95 | subscriptions() { 96 | return { 97 | hello: ob.pipe(startWith(this.foo + this.bar)), 98 | }; 99 | }, 100 | }; 101 | 102 | const wrapper = mount(component); 103 | 104 | expect(wrapper.text()).toBe("FOOBAR"); 105 | }); 106 | 107 | test("subscriptions() can throw error properly", (done) => { 108 | const { ob, next } = mock(); 109 | let thrownError; 110 | 111 | const component = { 112 | template: varTemplate("num"), 113 | subscriptions() { 114 | return { 115 | num: ob.pipe( 116 | startWith(1), 117 | map((n) => n.toFixed()), 118 | tap({ 119 | error(err) { 120 | thrownError = err; 121 | }, 122 | }) 123 | ), 124 | }; 125 | }, 126 | }; 127 | 128 | const wrapper = mount(component); 129 | 130 | wrapper.componentVM.$nextTick(() => { 131 | next(null); 132 | 133 | wrapper.componentVM.$nextTick(() => { 134 | expect(thrownError).toBeDefined(); 135 | expect(wrapper.text()).toBe("1"); 136 | done(); 137 | }); 138 | }); 139 | }); 140 | 141 | test("v-stream directive (basic)", (done) => { 142 | const component = { 143 | template: ` 144 |
145 | {{ count }} 146 | 147 |
148 | `, 149 | domStreams: ["click$"], 150 | subscriptions() { 151 | return { 152 | count: this.click$.pipe( 153 | map(() => 1), 154 | startWith(0), 155 | scan((total, change) => total + change) 156 | ), 157 | }; 158 | }, 159 | }; 160 | 161 | const wrapper = mount(component); 162 | 163 | expect(wrapper.element.querySelector("span").textContent).toBe("0"); 164 | click(wrapper.element.querySelector("button")); 165 | wrapper.componentVM.$nextTick(() => { 166 | expect(wrapper.element.querySelector("span").textContent).toBe("1"); 167 | done(); 168 | }); 169 | }); 170 | 171 | test("v-stream directive (with .native modify)", (done) => { 172 | const component = { 173 | template: ` 174 |
175 | {{ count }} 176 | + 177 | - 178 |
179 | `, 180 | components: { 181 | myButton: { 182 | template: "", 183 | }, 184 | }, 185 | domStreams: ["clickNative$", "click$"], 186 | subscriptions() { 187 | return { 188 | count: this.clickNative$.pipe( 189 | merge(this.click$), 190 | filter((e) => e.event.target && e.event.target.id === "btn-native"), 191 | map(() => 1), 192 | startWith(0), 193 | scan((total, change) => total + change) 194 | ), 195 | }; 196 | }, 197 | }; 198 | 199 | const wrapper = mount(component); 200 | 201 | expect(wrapper.element.querySelector("span").textContent).toBe("0"); 202 | click(wrapper.element.querySelector("#btn")); 203 | click(wrapper.element.querySelector("#btn")); 204 | click(wrapper.element.querySelector("#btn-native")); 205 | wrapper.componentVM.$nextTick(() => { 206 | expect(wrapper.element.querySelector("span").textContent).toBe("1"); 207 | done(); 208 | }); 209 | }); 210 | 211 | test("v-stream directive (with .stop, .prevent modify)", (done) => { 212 | const component = { 213 | template: ` 214 |
215 | {{stoped}} {{prevented}} 216 | 217 | 218 |
219 | `, 220 | domStreams: ["clickStop$", "clickPrevent$"], 221 | subscriptions() { 222 | return { 223 | stoped: this.clickStop$.pipe(map((x) => x.event.cancelBubble)), 224 | prevented: this.clickPrevent$.pipe( 225 | map((x) => x.event.defaultPrevented) 226 | ), 227 | }; 228 | }, 229 | }; 230 | 231 | const wrapper = mount(component); 232 | 233 | click(wrapper.element.querySelector("#btn-stop")); 234 | click(wrapper.element.querySelector("#btn-prevent")); 235 | wrapper.componentVM.$nextTick(() => { 236 | expect(wrapper.element.querySelector("span").textContent).toBe("true true"); 237 | done(); 238 | }); 239 | }); 240 | 241 | test("v-stream directive (multiple bindings on same node)", (done) => { 242 | const component = { 243 | template: ` 244 |
245 | {{ count }} 246 | 249 |
250 | `, 251 | domStreams: ["plus$"], 252 | subscriptions() { 253 | return { 254 | count: this.plus$.pipe( 255 | pluck("data"), 256 | startWith(0), 257 | scan((total, change) => total + change) 258 | ), 259 | }; 260 | }, 261 | }; 262 | 263 | const wrapper = mount(component); 264 | 265 | expect(wrapper.element.querySelector("span").textContent).toBe("0"); 266 | click(wrapper.element.querySelector("button")); 267 | wrapper.componentVM.$nextTick(() => { 268 | expect(wrapper.element.querySelector("span").textContent).toBe("1"); 269 | trigger(wrapper.element.querySelector("button"), "keyup"); 270 | wrapper.componentVM.$nextTick(() => { 271 | expect(wrapper.element.querySelector("span").textContent).toBe("0"); 272 | done(); 273 | }); 274 | }); 275 | }); 276 | 277 | test("$fromDOMEvent()", (done) => { 278 | const component = { 279 | template: ` 280 |
281 | {{ count }} 282 | 283 |
284 | `, 285 | subscriptions() { 286 | const click$ = this.$fromDOMEvent("button", "click"); 287 | return { 288 | count: click$.pipe( 289 | map(() => 1), 290 | startWith(0), 291 | scan((total, change) => total + change) 292 | ), 293 | }; 294 | }, 295 | }; 296 | const wrapper = mount(component); 297 | 298 | document.body.appendChild(wrapper.element); 299 | expect(wrapper.element.querySelector("span").textContent).toBe("0"); 300 | click(wrapper.element.querySelector("button")); 301 | wrapper.componentVM.$nextTick(() => { 302 | expect(wrapper.element.querySelector("span").textContent).toBe("1"); 303 | done(); 304 | }); 305 | }); 306 | 307 | test("$subscribeTo()", () => { 308 | const { ob, next } = mock(); 309 | const results = []; 310 | const component = { 311 | template: defaultTemplate, 312 | created() { 313 | this.$subscribeTo(ob, (count) => { 314 | results.push(count); 315 | }); 316 | }, 317 | }; 318 | 319 | const wrapper = mount(component); 320 | 321 | next(1); 322 | expect(results).toEqual([1]); 323 | 324 | wrapper.unmount(); 325 | next(2); 326 | expect(results).toEqual([1]); // should not trigger anymore 327 | }); 328 | 329 | test("$createObservableMethod() with no context", (done) => { 330 | const { ob, next } = mock(); 331 | const results = []; 332 | const component = { 333 | template: defaultTemplate, 334 | created() { 335 | this.$createObservableMethod("add").subscribe(function (param) { 336 | expect(param).toEqual("hola"); 337 | done(); 338 | }); 339 | }, 340 | }; 341 | 342 | const wrapper = mount(component); 343 | 344 | wrapper.componentVM.$nextTick(() => { 345 | wrapper.componentVM.add("hola"); 346 | }); 347 | }); 348 | 349 | test("$createObservableMethod() with multi params & context", (done) => { 350 | const { ob, next } = mock(); 351 | const results = []; 352 | var wrapper = { e: "" }; 353 | const component = { 354 | template: defaultTemplate, 355 | created() { 356 | this.$createObservableMethod("add", true).subscribe(function (param) { 357 | expect(param[0]).toEqual("hola"); 358 | expect(param[1]).toEqual("mundo"); 359 | expect(param[2]).toEqual(wrapper.componentVM); 360 | done(); 361 | }); 362 | }, 363 | }; 364 | 365 | wrapper = mount(component); 366 | 367 | wrapper.componentVM.$nextTick(() => { 368 | wrapper.componentVM.add("hola", "mundo"); 369 | }); 370 | }); 371 | 372 | test("observableMethods mixin", (done) => { 373 | const { ob, next } = mock(); 374 | const results = []; 375 | const component = { 376 | template: defaultTemplate, 377 | observableMethods: ["add"], 378 | created() { 379 | this.add$.subscribe(function (param) { 380 | expect(param[0]).toEqual("Qué"); 381 | expect(param[1]).toEqual("tal"); 382 | done(); 383 | }); 384 | }, 385 | }; 386 | 387 | const wrapper = mount(component); 388 | 389 | wrapper.componentVM.$nextTick(() => { 390 | wrapper.componentVM.add("Qué", "tal"); 391 | }); 392 | }); 393 | 394 | test("observableMethods mixin", (done) => { 395 | const { ob, next } = mock(); 396 | const results = []; 397 | const component = { 398 | template: defaultTemplate, 399 | observableMethods: { add: "plus$" }, 400 | created() { 401 | this.plus$.subscribe(function (param) { 402 | expect(param[0]).toEqual("Qué"); 403 | expect(param[1]).toEqual("tal"); 404 | done(); 405 | }); 406 | }, 407 | }; 408 | 409 | const wrapper = mount(component); 410 | 411 | wrapper.componentVM.$nextTick(() => { 412 | wrapper.componentVM.add("Qué", "tal"); 413 | }); 414 | }); 415 | -------------------------------------------------------------------------------- /types/index.d.ts: -------------------------------------------------------------------------------- 1 | import { Observer, Observable, Unsubscribable } from "rxjs"; 2 | import { 3 | App, 4 | DefineComponent, 5 | Ref as _Ref, 6 | WatchStopHandle as _WatchStopHandle, 7 | } from "vue"; 8 | import { WatchOptions } from "vue/types/options"; 9 | 10 | export type Observables = Record>; 11 | export interface WatchObservable { 12 | newValue: T; 13 | oldValue: T; 14 | } 15 | export type Ref = _Ref & Observer & Observable; 16 | 17 | export type WatchStopHandle = Observer & 18 | Observable & 19 | Unsubscribable & 20 | (() => void); 21 | 22 | export function ref(value: unknown): Ref; 23 | 24 | export function watch(ref: Ref, fn?: (val: any) => any): WatchStopHandle; 25 | 26 | export function watchEffect(fn?: () => any): WatchStopHandle; 27 | 28 | declare module "*.vue" { 29 | const component: DefineComponent<{}, {}, any>; 30 | export default component; 31 | } 32 | import type { Vue } from "vue/types/vue"; 33 | 34 | declare module "vue" { 35 | interface ComponentCustomProperties {} 36 | 37 | interface ComponentCustomOptions { 38 | domStreams?: string[]; 39 | subscriptions?: 40 | | Observables 41 | | ((this: Vue & { [key: string]: Observables | any }) => Observables); 42 | observableMethods?: string[] | Record; 43 | } 44 | interface ComponentCustomProps { 45 | $observables: Observables; 46 | $watchAsObservable( 47 | expr: string, 48 | options?: WatchOptions 49 | ): Observable>; 50 | $watchAsObservable( 51 | fn: (this: this) => T, 52 | options?: WatchOptions 53 | ): Observable>; 54 | $fromDOMEvent(selector: string | null, event: string): Observable; 55 | $createObservableMethod(methodName: string): Observable; 56 | } 57 | } 58 | export function install(app: App): void; 59 | -------------------------------------------------------------------------------- /types/test/index.ts: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mylabz-xyz/vue-next-rx/3a142d633cdf1de02593a0639ea4887afa237234/types/test/index.ts -------------------------------------------------------------------------------- /types/test/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "es5", 5 | "lib": [ 6 | "es6", 7 | "es5", 8 | "dom", 9 | "es2015.promise", 10 | "es2015.core" 11 | ], 12 | "strict": true, 13 | "allowSyntheticDefaultImports": true, 14 | "noEmit": true 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /types/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "CommonJS", 4 | "target": "es6", 5 | "strict": true, 6 | "noEmit": true 7 | }, 8 | "include": ["*.d.ts"], 9 | "exclude": ["node_modules/**"] 10 | } 11 | -------------------------------------------------------------------------------- /types/typings.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vue-rx", 3 | "main": "index.d.ts" 4 | } 5 | --------------------------------------------------------------------------------