From 69c7e9003c24f907e112137040c07fde3cb59afc Mon Sep 17 00:00:00 2001 From: Mateus Lage Date: Sat, 6 Jun 2026 09:58:38 -0300 Subject: [PATCH 1/2] feat(collaborative-vue): Vue.js composables, components & context for json-joy CRDTs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds @jsonjoy.com/collaborative-vue — the Vue 3 counterpart of @jsonjoy.com/collaborative-react, mirroring its surface and names: - context.ts — provide/inject helpers (createNodeCtx, provideModel/provideNode, useCtx{Model,Node}[Strict]) and / - composables.ts — useModelTick/View/Model/ModelTry, useNodeEvents/Effect/ Change/Node/NodeView, usePath/PathView/Obj/Arr/Str - components.ts — / render-prop components via scoped slots Reads return Vue refs/computed; writes use json-joy's existing node verbs (obj.set, str.ins, arr.push, …) — no additions to json-joy core. Node/path composables force-trigger on every matching change so stable node handles still re-notify, matching React's re-render-on-change semantics. Builds entirely on the existing public API. Tested with jest (composables via effectScope, context/components mounted in jsdom). Co-Authored-By: Claude Opus 4.8 (1M context) --- packages/collaborative-vue/LICENSE | 661 ++++++++++++++++++ packages/collaborative-vue/README.md | 134 ++++ packages/collaborative-vue/SECURITY.md | 13 + packages/collaborative-vue/package.json | 67 ++ .../src/__tests__/composables.spec.ts | 142 ++++ .../src/__tests__/context.spec.ts | 93 +++ packages/collaborative-vue/src/components.ts | 46 ++ packages/collaborative-vue/src/composables.ts | 216 ++++++ packages/collaborative-vue/src/context.ts | 83 +++ packages/collaborative-vue/src/index.ts | 5 + packages/collaborative-vue/src/types.ts | 8 + packages/collaborative-vue/src/utils.ts | 15 + .../collaborative-vue/tsconfig.build.json | 18 + packages/collaborative-vue/tsconfig.json | 18 + tsconfig.solution.json | 1 + yarn.lock | 201 +++++- 16 files changed, 1720 insertions(+), 1 deletion(-) create mode 100644 packages/collaborative-vue/LICENSE create mode 100644 packages/collaborative-vue/README.md create mode 100644 packages/collaborative-vue/SECURITY.md create mode 100644 packages/collaborative-vue/package.json create mode 100644 packages/collaborative-vue/src/__tests__/composables.spec.ts create mode 100644 packages/collaborative-vue/src/__tests__/context.spec.ts create mode 100644 packages/collaborative-vue/src/components.ts create mode 100644 packages/collaborative-vue/src/composables.ts create mode 100644 packages/collaborative-vue/src/context.ts create mode 100644 packages/collaborative-vue/src/index.ts create mode 100644 packages/collaborative-vue/src/types.ts create mode 100644 packages/collaborative-vue/src/utils.ts create mode 100644 packages/collaborative-vue/tsconfig.build.json create mode 100644 packages/collaborative-vue/tsconfig.json diff --git a/packages/collaborative-vue/LICENSE b/packages/collaborative-vue/LICENSE new file mode 100644 index 0000000000..0ad25db4bd --- /dev/null +++ b/packages/collaborative-vue/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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. + + + Copyright (C) + + 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 . + +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 +. diff --git a/packages/collaborative-vue/README.md b/packages/collaborative-vue/README.md new file mode 100644 index 0000000000..0360a3bfa7 --- /dev/null +++ b/packages/collaborative-vue/README.md @@ -0,0 +1,134 @@ +# JSON CRDT integrations with Vue.js + +Vue 3 composables, provide/inject context helpers, and render-prop components for +binding Vue UI to [`json-joy`](https://github.com/streamich/json-joy) CRDT models +and nodes. The Vue counterpart of +[`@jsonjoy.com/collaborative-react`](https://github.com/streamich/json-joy/tree/master/packages/collaborative-react) +— same surface, same names, Vue reactivity instead of React state. + +## Installation + +```bash +npm install json-joy @jsonjoy.com/collaborative-vue vue +``` + +## What this package provides + +- **Context helpers** for `Model` and `NodeApi` (Vue `provide`/`inject`) +- **Reactive composables** for model ticks, model views, node views, and path access +- **Typed path composables** for object/array/string nodes +- **Render-prop components** (`UseModel`, `UseNode`) for declarative subscriptions + +Reads are reactive; **writes are plain json-joy verbs** (`obj.set`, `str.ins`, +`arr.push`, …) — the binding adds no write abstraction, so you keep the full, +precise CRDT API (`set` vs `merge`, character-level text ops, etc.). + +## Quick start + +```vue + + + +``` + +## Context API + +A single context carries a `CrdtNodeApi`; the `Model` is derived from +`node.api.model` (so providing a model just provides its root `api`). + +### Provide + +- `provideModel(model)` / `provideNode(node)` — call inside `setup()` +- `` / `` + +### Read + +- `useCtxModel()` / `useCtxNode()` — optional access (`undefined` if none provided) +- `useCtxModelStrict()` / `useCtxNodeStrict()` — strict access (throws `NO_NODE`) + +### Isolated context + +`createNodeCtx()` returns a fresh injection key plus its own `provide*` / `useCtx*` +bindings, when you need a second independent context in the same tree. + +## Composables + +Every composable returns a Vue ref (read `.value`, or use directly in templates). +All accept an explicit `model`/`node`, or fall back to the context node. Node and +path composables take an `event` granularity: `'self'`, `'child'`, or `'subtree'` +(default). Subscriptions are torn down automatically on scope dispose. + +### Model + +- `useModelTick(model?)` → `Ref` — re-renders on every model change +- `useModelView(model?)` → `Ref` — re-renders only when the view identity changes +- `useModel(selector, model?)` → `ComputedRef` — derive a value, recomputed per tick +- `useModelTry(selector, model?)` → `ComputedRef` — safe variant + +### Node + +- `useNodeEvents(event, listener, node?)` → unsubscribe fn (manual lifecycle) +- `useNodeEffect(event, listener, node?)` → `void` — auto-unsubscribes on dispose +- `useNodeChange(event, node?)` → `Ref` +- `useNode(node?, event?)` → `Ref` — re-triggers on every matching change +- `useNodeView(node?, event?)` → `Ref` + +### Path + +- `usePath(path, node?, event?)` → `Ref` +- `usePathView(path, node?, event?)` → `Ref` +- `useObj(path?, node?, event?)` → `Ref` +- `useArr(path?, node?, event?)` → `Ref` +- `useStr(path?, node?, event?)` → `Ref` + +## Components + +### `UseModel` + +Re-renders its default slot on model change; the slot receives the model. + +```vue + +
{{ JSON.stringify(model.api.view(), null, 2) }}
+
+``` + +### `UseNode` + +Re-renders its default slot on the given node event; the slot receives the node. + +```vue + +
{{ JSON.stringify(node.view(), null, 2) }}
+
+``` + +## Notes + +- Reactivity granularity follows json-joy's node events. `'subtree'` re-renders on + any descendant change; narrow it to `'self'`/`'child'` to re-render less. +- `useModelView` only re-renders when the view *identity* changes (json-joy + preserves the view object across structurally-identical updates); node + composables re-render on every matching change event. +- Model-level subscriptions (`useModelTick`/`useModelView`) buffer on a microtask; + node-level subscriptions fire synchronously. +- Transport is your choice: publish local ops via `model.api.onLocalChange` / + `model.api.flush()` and feed remote patches to `model.applyPatch(...)`. + +## License + +Apache-2.0 diff --git a/packages/collaborative-vue/SECURITY.md b/packages/collaborative-vue/SECURITY.md new file mode 100644 index 0000000000..a5497b62af --- /dev/null +++ b/packages/collaborative-vue/SECURITY.md @@ -0,0 +1,13 @@ +# Security Policy + +## Supported Versions + +We release patches for security vulnerabilities. The latest major version +will support security patches. + +## Reporting a Vulnerability + +Please report (suspected) security vulnerabilities to +**[streamich@gmail.com](mailto:streamich@gmail.com)**. We will try to respond +within 48 hours. If the issue is confirmed, we will release a patch as soon +as possible depending on complexity. diff --git a/packages/collaborative-vue/package.json b/packages/collaborative-vue/package.json new file mode 100644 index 0000000000..57c8690a77 --- /dev/null +++ b/packages/collaborative-vue/package.json @@ -0,0 +1,67 @@ +{ + "name": "@jsonjoy.com/collaborative-vue", + "version": "18.27.0", + "description": "JSON CRDT Vue.js composables, components, and context helpers — the Vue counterpart of @jsonjoy.com/collaborative-react.", + "author": { + "name": "streamich", + "url": "https://github.com/streamich" + }, + "license": "Apache-2.0", + "main": "lib/index.js", + "types": "lib/index.d.ts", + "files": [ + "lib/" + ], + "keywords": [ + "collaborative", + "multiplayer", + "binding", + "collaborative-vue", + "composables", + "vue", + "json-crdt", + "json", + "crdt", + "local-first" + ], + "dependencies": { + "json-joy": "workspace:*" + }, + "peerDependencies": { + "tslib": "*", + "vue": "^3.4" + }, + "devDependencies": { + "jest-environment-jsdom": "^30", + "vue": "^3.5.13" + }, + "scripts": { + "clean": "npx rimraf lib typedocs coverage gh-pages yarn-error.log", + "build": "tsc -b tsconfig.build.json", + "jest": "node -r ts-node/register ./node_modules/.bin/jest", + "test": "jest --maxWorkers 7", + "test:ci": "yarn jest --maxWorkers 3 --no-cache", + "typecheck": "tsc -b --noEmit" + }, + "jest": { + "preset": "ts-jest", + "testEnvironment": "node", + "moduleFileExtensions": [ + "ts", + "js", + "tsx" + ], + "transform": { + "^.+\\.tsx?$": "ts-jest" + }, + "transformIgnorePatterns": [ + ".*/node_modules/.*" + ], + "testRegex": ".*/(__tests__|__jest__)/.*(? new Promise((resolve) => setTimeout(resolve)); + +const newModel = () => + Model.create( + s.obj({ + title: s.str('Untitled'), + notes: s.arr([]), + }), + ) as unknown as Model; + +describe('model composables', () => { + test('useModelView mirrors the view and reacts to changes', async () => { + const model = newModel(); + const scope = effectScope(); + let runs = 0; + let view!: ReturnType; + scope.run(() => { + view = useModelView(model); + watchEffect( + () => { + void view.value; + runs++; + }, + {flush: 'sync'}, + ); + }); + expect((view.value as any).title).toBe('Untitled'); + expect(runs).toBe(1); + + model.api.obj([]).set({title: 'Hello'}); + await flush(); + expect((view.value as any).title).toBe('Hello'); + expect(runs).toBe(2); + scope.stop(); + }); + + test('useModelTick increments on every change', async () => { + const model = newModel(); + const scope = effectScope(); + let tick!: ReturnType; + scope.run(() => { + tick = useModelTick(model); + }); + const before = tick.value; + model.api.obj([]).set({title: 'x'}); + await flush(); + expect(tick.value).toBeGreaterThan(before); + scope.stop(); + }); + + test('scope.stop() tears down subscriptions', () => { + const model = newModel(); + const scope = effectScope(); + let runs = 0; + scope.run(() => { + const view = useModelView(model); + watchEffect( + () => { + void view.value; + runs++; + }, + {flush: 'sync'}, + ); + }); + expect(runs).toBe(1); + scope.stop(); + model.api.obj([]).set({title: 'after dispose'}); + expect(runs).toBe(1); + }); +}); + +describe('node & path composables', () => { + test('useStr resolves a string node, reads, and edits it', () => { + const model = newModel(); + const scope = effectScope(); + let runs = 0; + let str!: ReturnType; + scope.run(() => { + str = useStr(['title'], model.api as any); + watchEffect( + () => { + void str.value; + runs++; + }, + {flush: 'sync'}, + ); + }); + expect(str.value?.view()).toBe('Untitled'); + expect(runs).toBe(1); + + // Character-level in-place edit through the node verb (what the proxy can't do). + str.value!.ins(str.value!.view().length, '!'); + expect(str.value?.view()).toBe('Untitled!'); + expect(runs).toBe(2); + scope.stop(); + }); + + test('usePath holds undefined for a missing path and resolves when it appears', () => { + const model = newModel(); + const scope = effectScope(); + let node!: ReturnType; + scope.run(() => { + node = usePath(['missing'], model.api as any); + }); + expect(node.value).toBeUndefined(); + + model.api.obj([]).set({missing: s.str('here')}); + expect(node.value).toBeDefined(); + expect(node.value!.view()).toBe('here'); + scope.stop(); + }); + + test('useNodeView reflects the node view and reacts', () => { + const model = newModel(); + const scope = effectScope(); + let runs = 0; + let view!: ReturnType; + scope.run(() => { + view = useNodeView(model.api as any); + watchEffect( + () => { + void view.value; + runs++; + }, + {flush: 'sync'}, + ); + }); + expect((view.value as any).title).toBe('Untitled'); + expect(runs).toBe(1); + + model.api.obj([]).set({title: 'changed'}); + expect((view.value as any).title).toBe('changed'); + expect(runs).toBe(2); + scope.stop(); + }); +}); diff --git a/packages/collaborative-vue/src/__tests__/context.spec.ts b/packages/collaborative-vue/src/__tests__/context.spec.ts new file mode 100644 index 0000000000..d4429186d1 --- /dev/null +++ b/packages/collaborative-vue/src/__tests__/context.spec.ts @@ -0,0 +1,93 @@ +/** + * @jest-environment jsdom + */ +import {createApp, defineComponent, h, nextTick, type Component} from 'vue'; +import {Model, s} from 'json-joy/lib/json-crdt'; +import {ModelProvider, UseModel, UseNode, useCtxModel, useCtxModelStrict} from '..'; + +const newModel = () => + Model.create(s.obj({title: s.str('Untitled')})) as unknown as Model; + +function mount(component: Component) { + const el = document.createElement('div'); + const app = createApp(component); + app.mount(el); + return {el, app}; +} + +// Model-level changes buffer on a microtask; then Vue flushes its render queue. +// A macrotask tick drains both before we read the DOM. +const flush = async () => { + await new Promise((resolve) => setTimeout(resolve)); + await nextTick(); +}; + +describe('context', () => { + test('ModelProvider supplies the model to descendants', () => { + const model = newModel(); + let resolved: Model | undefined; + const Child = defineComponent({ + setup() { + resolved = useCtxModelStrict(); + return () => h('div'); + }, + }); + const Root = defineComponent({ + setup() { + return () => h(ModelProvider, {model}, () => h(Child)); + }, + }); + const {app} = mount(Root); + expect(resolved).toBe(model); + app.unmount(); + }); + + test('non-strict context returns undefined without a provider', () => { + const app = createApp({render: () => null}); + const result = app.runWithContext(() => useCtxModel()); + expect(result).toBeUndefined(); + }); + + test('strict context throws without a provider', () => { + const app = createApp({render: () => null}); + expect(() => app.runWithContext(() => useCtxModelStrict())).toThrow('NO_NODE'); + }); +}); + +describe('render-prop components', () => { + test('UseModel renders the view and updates on change', async () => { + const model = newModel(); + const Root = defineComponent({ + setup() { + return () => + h(UseModel, {model}, {default: ({model: m}: {model: Model}) => h('span', (m.api.view() as any).title)}); + }, + }); + const {el, app} = mount(Root); + expect(el.textContent).toBe('Untitled'); + + model.api.obj([]).set({title: 'Hello'}); + await flush(); + expect(el.textContent).toBe('Hello'); + app.unmount(); + }); + + test('UseNode renders a node view from context and updates on change', async () => { + const model = newModel(); + const Root = defineComponent({ + setup() { + return () => + h(ModelProvider, {model}, () => + h(UseNode, {event: 'subtree'}, {default: ({node}: {node: any}) => h('span', node.view().title)}), + ); + }, + }); + const {el, app} = mount(Root); + expect(el.textContent).toBe('Untitled'); + + model.api.obj([]).set({title: 'World'}); + await flush(); + expect(el.textContent).toBe('World'); + app.unmount(); + }); +}); diff --git a/packages/collaborative-vue/src/components.ts b/packages/collaborative-vue/src/components.ts new file mode 100644 index 0000000000..559a857b6f --- /dev/null +++ b/packages/collaborative-vue/src/components.ts @@ -0,0 +1,46 @@ +import {defineComponent, type PropType} from 'vue'; +import {useCtxModelStrict} from './context'; +import {useModelTick, useNode} from './composables'; +import type {Model} from 'json-joy/lib/json-crdt'; +import type {CrdtNodeApi} from './types'; + +// Render-prop equivalents using Vue scoped slots — the analog of +// `@jsonjoy.com/collaborative-react`'s `` / ``. The default +// slot receives the live model/node and re-renders on the relevant change. +// +// {{ model.api.view().title }} +// {{ node.view() }} + +/** + * Re-renders its default slot whenever the model changes, passing the model as + * the `model` slot prop. The `model` prop is optional — falls back to context. + */ +export const UseModel = defineComponent({ + name: 'UseModel', + props: {model: {type: Object as PropType>, required: false, default: undefined}}, + setup(props, {slots}) { + const model = props.model ?? useCtxModelStrict(); + // The model handle identity is stable, so depend on the tick to re-render. + const tick = useModelTick(model); + return () => { + void tick.value; + return slots.default?.({model}); + }; + }, +}); + +/** + * Re-renders its default slot on the given node change event, passing the node + * as the `node` slot prop. Both props are optional — `node` falls back to context. + */ +export const UseNode = defineComponent({ + name: 'UseNode', + props: { + node: {type: Object as PropType, required: false, default: undefined}, + event: {type: String as PropType<'self' | 'child' | 'subtree'>, required: false, default: 'subtree'}, + }, + setup(props, {slots}) { + const node = useNode(props.node as CrdtNodeApi, props.event); + return () => slots.default?.({node: node.value}); + }, +}); diff --git a/packages/collaborative-vue/src/composables.ts b/packages/collaborative-vue/src/composables.ts new file mode 100644 index 0000000000..8fac759307 --- /dev/null +++ b/packages/collaborative-vue/src/composables.ts @@ -0,0 +1,216 @@ +import {computed, getCurrentScope, onScopeDispose, shallowRef, triggerRef, type ComputedRef, type ShallowRef} from 'vue'; +import {useCtxModelStrict, useCtxNodeStrict} from './context'; +import type {ArrApi, JsonNodeView, Model, ObjApi, StrApi} from 'json-joy/lib/json-crdt'; +import type {ChangeEvent} from 'json-joy/lib/json-crdt/model/api/events'; +import type {ApiPath} from 'json-joy/lib/json-crdt/model/api/types'; +import type {CrdtNodeApi} from './types'; + +type ChangeKind = 'self' | 'child' | 'subtree'; + +// Register a subscription teardown with the current effect scope (component +// `setup()` or `effectScope()`), if there is one. Outside a scope the caller +// owns cleanup — we skip silently rather than emit Vue's "no active scope" warning. +const autoDispose = (unsubscribe: () => void): void => { + if (getCurrentScope()) onScopeDispose(unsubscribe); +}; + +/** + * A `shallowRef` recomputed on every matching node change. `compute()` runs once + * up front and again after each change event; when its result is identical to + * the previous one (e.g. a stable node handle or a structurally-unchanged view), + * the ref is still *force-triggered* so dependents re-evaluate — matching React, + * where the component re-renders on every subscribed change. Granularity is + * controlled by `event` (`'self'` | `'child'` | `'subtree'`). + */ +const trackedRef = (node: CrdtNodeApi, event: ChangeKind, compute: () => T): Readonly> => { + const ref = shallowRef(compute()); + const unsubscribe = node.onNodeChange(event, () => { + const next = compute(); + if (Object.is(next, ref.value)) triggerRef(ref); + else ref.value = next as ShallowRef['value']; + }); + autoDispose(unsubscribe); + return ref; +}; + +// --------------------------------------------------------------- Model hooks + +/** + * Subscribe to a model's *tick* and return it as a ref. Re-renders on every + * model change, even ones that don't affect the view. + */ +export const useModelTick = >( + model: M = useCtxModelStrict() as M, +): Readonly> => { + const tick = shallowRef(model.tick); + const unsubscribe = model.api.subscribe(() => { + tick.value = model.tick; + }); + autoDispose(unsubscribe); + return tick; +}; + +/** + * Subscribe to a model's view and return it as a ref. Re-renders only when the + * view *identity* changes: json-joy preserves the same view object across + * no-op changes (e.g. `{foo: 'bar'}` → `{foo: 'bar'}`), so the ref does not + * trigger in that case. + */ +export const useModelView = >( + model: M = useCtxModelStrict() as M, +): Readonly>> => { + const api = model.api; + const view = shallowRef(api.getSnapshot()); + const unsubscribe = api.subscribe(() => { + view.value = api.getSnapshot(); + }); + autoDispose(unsubscribe); + return view as Readonly>>; +}; + +/** + * Derive a reactive value from a model with a selector. Recomputes on every + * model tick. + */ +export const useModel = , R = unknown>( + selector: (model: M) => R, + model: M = useCtxModelStrict() as M, +): ComputedRef => { + const tick = useModelTick(model); + return computed(() => { + void tick.value; + return selector(model); + }); +}; + +/** + * Safe variant of {@link useModel}: returns `undefined` when the selector throws + * (e.g. while reading a part of the document that does not exist yet). + */ +export const useModelTry = , R = unknown>( + selector: (model: M) => R, + model: M = useCtxModelStrict() as M, +): ComputedRef => { + const tick = useModelTick(model); + return computed(() => { + void tick.value; + try { + return selector(model); + } catch { + return undefined; + } + }); +}; + +// ---------------------------------------------------------------- Node hooks + +/** + * Subscribe to change events on a node and return the unsubscribe function for + * manual lifecycle control. Prefer {@link useNodeEffect} for automatic cleanup. + * + * @param event `'self'` (the node itself), `'child'` (direct children), or + * `'subtree'` (the node or any descendant). + */ +export const useNodeEvents = ( + event: ChangeKind, + listener: (event: ChangeEvent) => void, + node: N = useCtxNodeStrict() as N, +): (() => void) => node.onNodeChange(event, listener); + +/** Like {@link useNodeEvents}, but unsubscribes automatically on scope dispose. */ +export const useNodeEffect = ( + event: ChangeKind, + listener: (event: ChangeEvent) => void, + node?: N, +): void => { + autoDispose(useNodeEvents(event, listener, node)); +}; + +/** + * Re-renders on the given node change and returns a ref holding the latest + * `ChangeEvent` (or `undefined` before the first change). + */ +export const useNodeChange = ( + event: ChangeKind, + node?: N, +): Readonly> => { + const change = shallowRef(); + useNodeEffect( + event, + (e) => { + change.value = e; + }, + node, + ); + return change; +}; + +/** + * Subscribe to a node and return it as a ref that re-triggers on every matching + * change (the node handle identity is stable, so dependents are force-notified). + */ +export const useNode = ( + node: N = useCtxNodeStrict() as N, + event: ChangeKind = 'subtree', +): Readonly> => trackedRef(node, event, () => node) as Readonly>; + +/** + * Subscribe to a node and return a ref holding its view, recomputed on every + * matching change. + */ +export const useNodeView = ( + node: N = useCtxNodeStrict() as N, + event: ChangeKind = 'subtree', +): Readonly>> => + trackedRef(node, event, () => node.view() as ReturnType); + +// ---------------------------------------------------------------- Path hooks + +const resolvePath = (node: CrdtNodeApi, path: ApiPath): CrdtNodeApi | undefined => { + try { + return node.in(path) as CrdtNodeApi; + } catch { + return undefined; + } +}; + +/** + * Resolve a nested node by path, as a ref that re-triggers on every matching + * change to the parent (or context) node. Holds `undefined` when the path does + * not resolve. + */ +export const usePath = ( + path: ApiPath, + node: N = useCtxNodeStrict() as N, + event: ChangeKind = 'subtree', +): Readonly> => trackedRef(node, event, () => resolvePath(node, path)); + +/** Like {@link usePath}, but holds the resolved node's view instead of the node. */ +export const usePathView = ( + path: ApiPath, + node: N = useCtxNodeStrict() as N, + event: ChangeKind = 'subtree', +): Readonly> => trackedRef(node, event, () => resolvePath(node, path)?.view()); + +/** Typed {@link usePath} returning the node cast to {@link ObjApi}, or `undefined`. */ +export const useObj = ( + path: ApiPath = [], + node: N = useCtxNodeStrict() as N, + event: ChangeKind = 'subtree', +): Readonly | undefined>> => + trackedRef(node, event, () => resolvePath(node, path)?.asObj(true)); + +/** Typed {@link usePath} returning the node cast to {@link ArrApi}, or `undefined`. */ +export const useArr = ( + path: ApiPath = [], + node: N = useCtxNodeStrict() as N, + event: ChangeKind = 'subtree', +): Readonly | undefined>> => + trackedRef(node, event, () => resolvePath(node, path)?.asArr(true)); + +/** Typed {@link usePath} returning the node cast to {@link StrApi}, or `undefined`. */ +export const useStr = ( + path: ApiPath = [], + node: N = useCtxNodeStrict() as N, + event: ChangeKind = 'subtree', +): Readonly> => trackedRef(node, event, () => resolvePath(node, path)?.asStr(true)); diff --git a/packages/collaborative-vue/src/context.ts b/packages/collaborative-vue/src/context.ts new file mode 100644 index 0000000000..2ae46755cf --- /dev/null +++ b/packages/collaborative-vue/src/context.ts @@ -0,0 +1,83 @@ +import {defineComponent, inject, provide, type InjectionKey, type PropType} from 'vue'; +import type {Model} from 'json-joy/lib/json-crdt'; +import type {CrdtNodeApi} from './types'; + +// Vue analog of `@jsonjoy.com/collaborative-react`'s React context. A single +// context carries a `CrdtNodeApi`; the `Model` is derived from `node.api.model` +// (so `provideModel` is just `provideNode(model.api)`). Provide it with the +// `provide*` composables or the `*Provider` components, read it with the +// `useCtx*` composables — exactly mirroring the React surface. + +/** + * Create an isolated node context — a fresh injection key plus the `provide*` / + * `useCtx*` bindings scoped to it. Use this when you need a second, independent + * context in the same component tree (the default export below is one such + * context, shared by the rest of the package). + */ +export const createNodeCtx = (defaultNode?: N) => { + const key: InjectionKey = Symbol('json-joy.node'); + + /** Provide a node to descendants (call inside `setup()`). */ + const provideNode = (node: N): void => provide(key, node); + /** Provide a model (its root `api`) to descendants (call inside `setup()`). */ + const provideModel = (model: Model): void => provide(key, model.api as unknown as N); + + /** Read the context node, or `undefined` if none was provided. */ + const useCtxNode = (): N | undefined => inject(key, defaultNode); + /** Read the context model, or `undefined` if none was provided. */ + const useCtxModel = (): Model | undefined => useCtxNode()?.api.model; + /** Read the context node, throwing `NO_NODE` if none was provided. */ + const useCtxNodeStrict = (): N => { + const node = useCtxNode(); + if (!node) throw new Error('NO_NODE'); + return node; + }; + /** Read the context model, throwing `NO_NODE` if none was provided. */ + const useCtxModelStrict = (): Model => useCtxNodeStrict().api.model; + + /** Provider component: makes `node` available to its default slot. */ + const NodeProvider = defineComponent({ + name: 'NodeProvider', + props: {node: {type: Object as PropType, required: true}}, + setup(props, {slots}) { + provideNode(props.node as N); + return () => slots.default?.(); + }, + }); + + /** Provider component: makes `model` (its root `api`) available to its slot. */ + const ModelProvider = defineComponent({ + name: 'ModelProvider', + props: {model: {type: Object as PropType>, required: true}}, + setup(props, {slots}) { + provideModel(props.model); + return () => slots.default?.(); + }, + }); + + return { + key, + provideNode, + provideModel, + useCtxNode, + useCtxModel, + useCtxNodeStrict, + useCtxModelStrict, + NodeProvider, + ModelProvider, + }; +}; + +const ctx = createNodeCtx(); + +export const { + key, + provideNode, + provideModel, + useCtxNode, + useCtxModel, + useCtxNodeStrict, + useCtxModelStrict, + NodeProvider, + ModelProvider, +} = ctx; diff --git a/packages/collaborative-vue/src/index.ts b/packages/collaborative-vue/src/index.ts new file mode 100644 index 0000000000..ba3e249533 --- /dev/null +++ b/packages/collaborative-vue/src/index.ts @@ -0,0 +1,5 @@ +export type * from './types'; +export * from './utils'; +export * from './context'; +export * from './composables'; +export * from './components'; diff --git a/packages/collaborative-vue/src/types.ts b/packages/collaborative-vue/src/types.ts new file mode 100644 index 0000000000..50afe9d29c --- /dev/null +++ b/packages/collaborative-vue/src/types.ts @@ -0,0 +1,8 @@ +import type {NodeApi} from 'json-joy/lib/json-crdt'; + +/** + * The node API surface the bindings operate on. Mirrors + * `@jsonjoy.com/collaborative-react` — `$` (the path proxy) is omitted because + * it is a navigation helper, not a node, and would otherwise widen the type. + */ +export type CrdtNodeApi = Omit, '$'>; diff --git a/packages/collaborative-vue/src/utils.ts b/packages/collaborative-vue/src/utils.ts new file mode 100644 index 0000000000..e80e8dce14 --- /dev/null +++ b/packages/collaborative-vue/src/utils.ts @@ -0,0 +1,15 @@ +import type {NodeApi} from 'json-joy/lib/json-crdt'; +import type {ApiPath} from 'json-joy/lib/json-crdt/model/api/types'; + +/** + * A way to select a nested node from a root node — either a path (resolved with + * `node.find(path)`) or a function that derives the node from the root. + */ +export type ModelSelector = NodeApi, Selected extends NodeApi = NodeApi> = + | ApiPath + | ((model: Top) => Selected); + +export const selectNode = = NodeApi, Selected extends NodeApi = NodeApi>( + model: Top, + selector: ModelSelector, +): Selected => (typeof selector === 'function' ? selector(model) : (model.find(selector) as unknown as Selected)); diff --git a/packages/collaborative-vue/tsconfig.build.json b/packages/collaborative-vue/tsconfig.build.json new file mode 100644 index 0000000000..3cd3eb66ad --- /dev/null +++ b/packages/collaborative-vue/tsconfig.build.json @@ -0,0 +1,18 @@ +{ + "extends": "./tsconfig", + "compilerOptions": { + "sourceMap": false, + "rootDir": "./src", + "tsBuildInfoFile": "./lib/.tsbuildinfo" + }, + "exclude": [ + "src/demo", + "src/__tests__", + "src/**/__demos__/**/*.*", + "src/**/__tests__/**/*.*", + "src/**/__bench__/**/*.*", + "*.test.ts", + "*.spec.ts" + ], + "references": [{"path": "../json-joy/tsconfig.build.json"}] +} diff --git a/packages/collaborative-vue/tsconfig.json b/packages/collaborative-vue/tsconfig.json new file mode 100644 index 0000000000..1a66fbfd29 --- /dev/null +++ b/packages/collaborative-vue/tsconfig.json @@ -0,0 +1,18 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "rootDir": "./src", + "outDir": "./lib" + }, + "include": ["src"], + "exclude": [ + "src/demo", + "src/__tests__", + "src/**/__demos__/**/*.*", + "src/**/__tests__/**/*.*", + "src/**/__bench__/**/*.*", + "*.test.ts", + "*.spec.ts" + ], + "references": [{"path": "../json-joy"}] +} diff --git a/tsconfig.solution.json b/tsconfig.solution.json index d1666815e6..cde065dce2 100644 --- a/tsconfig.solution.json +++ b/tsconfig.solution.json @@ -20,6 +20,7 @@ { "path": "packages/collaborative-str/tsconfig.build.json" }, { "path": "packages/collaborative-presence/tsconfig.build.json" }, { "path": "packages/collaborative-react/tsconfig.build.json" }, + { "path": "packages/collaborative-vue/tsconfig.build.json" }, { "path": "packages/collaborative-input/tsconfig.build.json" }, { "path": "packages/collaborative-ace/tsconfig.build.json" }, { "path": "packages/collaborative-codemirror/tsconfig.build.json" }, diff --git a/yarn.lock b/yarn.lock index c82f01abf1..b822676560 100644 --- a/yarn.lock +++ b/yarn.lock @@ -143,6 +143,13 @@ __metadata: languageName: node linkType: hard +"@babel/helper-string-parser@npm:^7.29.7": + version: 7.29.7 + resolution: "@babel/helper-string-parser@npm:7.29.7" + checksum: 10c0/194bc0f1716e396d5ffde56ad6119745fb9557662c98611590e5e454906783a4ccb21ce93056b8eb69a4909044834e45d96e50ac695bbe9e3221648fe033c06c + languageName: node + linkType: hard + "@babel/helper-validator-identifier@npm:^7.28.5": version: 7.28.5 resolution: "@babel/helper-validator-identifier@npm:7.28.5" @@ -150,6 +157,13 @@ __metadata: languageName: node linkType: hard +"@babel/helper-validator-identifier@npm:^7.29.7": + version: 7.29.7 + resolution: "@babel/helper-validator-identifier@npm:7.29.7" + checksum: 10c0/4795354e7ae0dcafa72de1cd04ec51252dc1498517170beaf019e03effc5b7bf13c6b21a3949a77e07b8125be7f106ed1131350d8ebd4566ae874094a726d62b + languageName: node + linkType: hard + "@babel/helper-validator-option@npm:^7.27.1": version: 7.27.1 resolution: "@babel/helper-validator-option@npm:7.27.1" @@ -178,6 +192,17 @@ __metadata: languageName: node linkType: hard +"@babel/parser@npm:^7.29.3": + version: 7.29.7 + resolution: "@babel/parser@npm:7.29.7" + dependencies: + "@babel/types": "npm:^7.29.7" + bin: + parser: ./bin/babel-parser.js + checksum: 10c0/65133038f80b54a714d6027cb77cee3f9a6b5c4c6842ce674301e13947cbcbfa8055e63acaf1b84c085d34226a14425b2c2b97b829e0e226d2e8f1299942a51d + languageName: node + linkType: hard + "@babel/plugin-syntax-async-generators@npm:^7.8.4": version: 7.8.4 resolution: "@babel/plugin-syntax-async-generators@npm:7.8.4" @@ -408,6 +433,16 @@ __metadata: languageName: node linkType: hard +"@babel/types@npm:^7.29.7": + version: 7.29.7 + resolution: "@babel/types@npm:7.29.7" + dependencies: + "@babel/helper-string-parser": "npm:^7.29.7" + "@babel/helper-validator-identifier": "npm:^7.29.7" + checksum: 10c0/b6623994c69717fa27294f5fa46d59140338e2d86c6c1c13085c84ef7d53086ee357fbf4fe9abe3dd3da75734dc77c4c0df2f90fb29e667558bb3b3fb705e88f + languageName: node + linkType: hard + "@bcoe/v8-coverage@npm:^0.2.3": version: 0.2.3 resolution: "@bcoe/v8-coverage@npm:0.2.3" @@ -2202,6 +2237,18 @@ __metadata: languageName: unknown linkType: soft +"@jsonjoy.com/collaborative-vue@workspace:packages/collaborative-vue": + version: 0.0.0-use.local + resolution: "@jsonjoy.com/collaborative-vue@workspace:packages/collaborative-vue" + dependencies: + json-joy: "workspace:*" + vue: "npm:^3.5.13" + peerDependencies: + tslib: "*" + vue: ^3.4 + languageName: unknown + linkType: soft + "@jsonjoy.com/fs-core@npm:4.56.10": version: 4.56.10 resolution: "@jsonjoy.com/fs-core@npm:4.56.10" @@ -5211,6 +5258,106 @@ __metadata: languageName: node linkType: hard +"@vue/compiler-core@npm:3.5.35": + version: 3.5.35 + resolution: "@vue/compiler-core@npm:3.5.35" + dependencies: + "@babel/parser": "npm:^7.29.3" + "@vue/shared": "npm:3.5.35" + entities: "npm:^7.0.1" + estree-walker: "npm:^2.0.2" + source-map-js: "npm:^1.2.1" + checksum: 10c0/b269e49636631288c34d81f2e7f596d4f0b407c32d7f70f0fa89eb6757180f4f9bc6c8c9924a7760b9736a72d4489ab6c2cef4d4e710f16239c9296e0fd7b970 + languageName: node + linkType: hard + +"@vue/compiler-dom@npm:3.5.35": + version: 3.5.35 + resolution: "@vue/compiler-dom@npm:3.5.35" + dependencies: + "@vue/compiler-core": "npm:3.5.35" + "@vue/shared": "npm:3.5.35" + checksum: 10c0/491c3f4026824816884e9a6e2d58fd1eaa4686ac5073eb873b2c3241d388f240ea316f3329ed6e84fc8e9e5d548c8780bab566f19f81c1e468355dfb763c2561 + languageName: node + linkType: hard + +"@vue/compiler-sfc@npm:3.5.35": + version: 3.5.35 + resolution: "@vue/compiler-sfc@npm:3.5.35" + dependencies: + "@babel/parser": "npm:^7.29.3" + "@vue/compiler-core": "npm:3.5.35" + "@vue/compiler-dom": "npm:3.5.35" + "@vue/compiler-ssr": "npm:3.5.35" + "@vue/shared": "npm:3.5.35" + estree-walker: "npm:^2.0.2" + magic-string: "npm:^0.30.21" + postcss: "npm:^8.5.15" + source-map-js: "npm:^1.2.1" + checksum: 10c0/18e28d3d4e3cad5715a242aa47553957cb2f0671b56b3398b0e8e394cf041a336fd875a1166dd6ea4b976e019b32985f1fdbe827f4c8b553ac31f64a053664cb + languageName: node + linkType: hard + +"@vue/compiler-ssr@npm:3.5.35": + version: 3.5.35 + resolution: "@vue/compiler-ssr@npm:3.5.35" + dependencies: + "@vue/compiler-dom": "npm:3.5.35" + "@vue/shared": "npm:3.5.35" + checksum: 10c0/b015d0658dff58db362a9d639d7e3b5ad849136de064cbfd3207bd95548e26cc10a5fe7dbbe57cd3148f9ad4ee42a48f518cb3a395c940afcd00043e395d283a + languageName: node + linkType: hard + +"@vue/reactivity@npm:3.5.35": + version: 3.5.35 + resolution: "@vue/reactivity@npm:3.5.35" + dependencies: + "@vue/shared": "npm:3.5.35" + checksum: 10c0/720ac936092316ec6b3f7661ce4526b74e47120cd2ae1da6cc4a9bc380578bf9e5070cade6bec3eecfa5003abba3a3a1d94c430f79fb9943e5fc763625cdf4ab + languageName: node + linkType: hard + +"@vue/runtime-core@npm:3.5.35": + version: 3.5.35 + resolution: "@vue/runtime-core@npm:3.5.35" + dependencies: + "@vue/reactivity": "npm:3.5.35" + "@vue/shared": "npm:3.5.35" + checksum: 10c0/79bc6e2dfa3e7af98bbb66a96c8dfb72afdacb075ead1c9fc76753c1617807139d02f06f5a02562fb9b698567e089d6f8e8ac1aae8108fe2d0a388137507a1c4 + languageName: node + linkType: hard + +"@vue/runtime-dom@npm:3.5.35": + version: 3.5.35 + resolution: "@vue/runtime-dom@npm:3.5.35" + dependencies: + "@vue/reactivity": "npm:3.5.35" + "@vue/runtime-core": "npm:3.5.35" + "@vue/shared": "npm:3.5.35" + csstype: "npm:^3.2.3" + checksum: 10c0/ee144fccf99add8f840a08644196b69e66aed4f9a37840672ebdbdbac3efa50ea8e5e5155a49ad4a8ed9ff07a1ba9e91665b89e3fa71d8a7407396cdce82951d + languageName: node + linkType: hard + +"@vue/server-renderer@npm:3.5.35": + version: 3.5.35 + resolution: "@vue/server-renderer@npm:3.5.35" + dependencies: + "@vue/compiler-ssr": "npm:3.5.35" + "@vue/shared": "npm:3.5.35" + peerDependencies: + vue: 3.5.35 + checksum: 10c0/c9f8dc2c49c14583642b7856d1ce92fe55a84a11a6723c77ebcb81ebea2c6a881c6d663c3db8a5a07b6d31b79bb2695152b3b4cb2d72779bb27813fef9850d41 + languageName: node + linkType: hard + +"@vue/shared@npm:3.5.35": + version: 3.5.35 + resolution: "@vue/shared@npm:3.5.35" + checksum: 10c0/1609ecfdbd7a8fbfd630885d390c9b8908ee05ce827aaa30177c9f8b0340b7a4126a4890d0ef80a721fcce25c9055da5e8120a960b1a9bf8c92b190b7e0c9780 + languageName: node + linkType: hard + "@webassemblyjs/ast@npm:1.14.1, @webassemblyjs/ast@npm:^1.14.1": version: 1.14.1 resolution: "@webassemblyjs/ast@npm:1.14.1" @@ -7092,7 +7239,7 @@ __metadata: languageName: node linkType: hard -"csstype@npm:^3.0.10, csstype@npm:^3.0.2, csstype@npm:^3.1.2, csstype@npm:^3.2.2": +"csstype@npm:^3.0.10, csstype@npm:^3.0.2, csstype@npm:^3.1.2, csstype@npm:^3.2.2, csstype@npm:^3.2.3": version: 3.2.3 resolution: "csstype@npm:3.2.3" checksum: 10c0/cd29c51e70fa822f1cecd8641a1445bed7063697469d35633b516e60fe8c1bde04b08f6c5b6022136bb669b64c63d4173af54864510fbb4ee23281801841a3ce @@ -7580,6 +7727,13 @@ __metadata: languageName: node linkType: hard +"entities@npm:^7.0.1": + version: 7.0.1 + resolution: "entities@npm:7.0.1" + checksum: 10c0/b4fb9937bb47ecb00aaaceb9db9cdd1cc0b0fb649c0e843d05cf5dbbd2e9d2df8f98721d8b1b286445689c72af7b54a7242fc2d63ef7c9739037a8c73363e7ca + languageName: node + linkType: hard + "env-paths@npm:^2.2.0": version: 2.2.1 resolution: "env-paths@npm:2.2.1" @@ -7875,6 +8029,13 @@ __metadata: languageName: node linkType: hard +"estree-walker@npm:^2.0.2": + version: 2.0.2 + resolution: "estree-walker@npm:2.0.2" + checksum: 10c0/53a6c54e2019b8c914dc395890153ffdc2322781acf4bd7d1a32d7aedc1710807bdcd866ac133903d5629ec601fbb50abe8c2e5553c7f5a0afdd9b6af6c945af + languageName: node + linkType: hard + "estree-walker@npm:^3.0.3": version: 3.0.3 resolution: "estree-walker@npm:3.0.3" @@ -11179,6 +11340,15 @@ __metadata: languageName: node linkType: hard +"nanoid@npm:^3.3.12": + version: 3.3.12 + resolution: "nanoid@npm:3.3.12" + bin: + nanoid: bin/nanoid.cjs + checksum: 10c0/ba142b7b39e11e80c16dd74b0365d407880c87c1cf7e1480956981ae940ee36060fa5b6f092cd1e315184dd19244c657bd017d03327bd3c62247d691c5e8edfb + languageName: node + linkType: hard + "napi-macros@npm:^2.2.2": version: 2.2.2 resolution: "napi-macros@npm:2.2.2" @@ -11929,6 +12099,17 @@ __metadata: languageName: node linkType: hard +"postcss@npm:^8.5.15": + version: 8.5.15 + resolution: "postcss@npm:8.5.15" + dependencies: + nanoid: "npm:^3.3.12" + picocolors: "npm:^1.1.1" + source-map-js: "npm:^1.2.1" + checksum: 10c0/7f2e63ae22fbe43aace1bf652bd99da4e90737c64194d49e51ddc9cd0f9e51ff2861a7d734379b494deffa03a880a5c65eec70bc29ee9ebaa7136dde3eee8f31 + languageName: node + linkType: hard + "pretty-error@npm:^4.0.0": version: 4.0.0 resolution: "pretty-error@npm:4.0.0" @@ -15040,6 +15221,24 @@ __metadata: languageName: node linkType: hard +"vue@npm:^3.5.13": + version: 3.5.35 + resolution: "vue@npm:3.5.35" + dependencies: + "@vue/compiler-dom": "npm:3.5.35" + "@vue/compiler-sfc": "npm:3.5.35" + "@vue/runtime-dom": "npm:3.5.35" + "@vue/server-renderer": "npm:3.5.35" + "@vue/shared": "npm:3.5.35" + peerDependencies: + typescript: "*" + peerDependenciesMeta: + typescript: + optional: true + checksum: 10c0/1662c31ce74f408a79590f3eed962f6eb87c8cecad859f01904cfc7866b1223be7ffc837d9fd544a57320e3029e3a4c54d46273285cc8c0b0f83007dc3e2c988 + languageName: node + linkType: hard + "w3c-keyname@npm:^2.2.0, w3c-keyname@npm:^2.2.4": version: 2.2.8 resolution: "w3c-keyname@npm:2.2.8" From ed998ecbe9bd0a6be4d0892b145052b29e40091e Mon Sep 17 00:00:00 2001 From: Mateus Lage Date: Sat, 6 Jun 2026 10:02:06 -0300 Subject: [PATCH 2/2] feat(collaborative-vue): add optional collaborate() proxy on top of composables MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds a high-level `collaborate(model)` that returns a single fine-grained reactive `state` proxy — plain-object reads and `v-model` two-way binding, the Vue-idiomatic ergonomics the low-level composables serve awkwardly. It is sugar over the composables: reactivity uses the same per-node `onNodeChange('self')` subscription, and writes dispatch through json-joy's existing node verbs (ObjApi.set/del, ArrApi.ins/upd/del/merge, VecApi.set). No additions to json-joy core. 5 tests (jest, watchEffect): reads mirror the view; assignment + array methods record ops; fine-grained (sibling edits don't cross-trigger); remote-patch convergence; dispose() teardown. Co-Authored-By: Claude Opus 4.8 (1M context) --- packages/collaborative-vue/README.md | 33 +++ .../src/__tests__/collaborate.spec.ts | 122 ++++++++ packages/collaborative-vue/src/collaborate.ts | 280 ++++++++++++++++++ packages/collaborative-vue/src/index.ts | 1 + 4 files changed, 436 insertions(+) create mode 100644 packages/collaborative-vue/src/__tests__/collaborate.spec.ts create mode 100644 packages/collaborative-vue/src/collaborate.ts diff --git a/packages/collaborative-vue/README.md b/packages/collaborative-vue/README.md index 0360a3bfa7..69aca5795f 100644 --- a/packages/collaborative-vue/README.md +++ b/packages/collaborative-vue/README.md @@ -117,6 +117,39 @@ Re-renders its default slot on the given node event; the slot receives the node. ``` +## High-level `collaborate()` (optional) + +For plain-object ergonomics and `v-model` two-way binding, `collaborate(model)` +returns a single fine-grained reactive `state` proxy you read and mutate directly. +It is **sugar on top of the composables** — the same per-node `onNodeChange('self')` +subscription for reactivity, writes dispatched through the existing node verbs. +Drop down to the composables when you need precise control (in-place text ops, +`merge` vs `set`, explicit event granularity). + +```vue + + + +``` + +- `collaborate(model): { state: T; dispose(): void }` +- `dispose()` runs automatically when called inside a component `setup()`. +- Reads subscribe per node; writes record CRDT ops; remote `applyPatch` re-renders + only the nodes that changed. + ## Notes - Reactivity granularity follows json-joy's node events. `'subtree'` re-renders on diff --git a/packages/collaborative-vue/src/__tests__/collaborate.spec.ts b/packages/collaborative-vue/src/__tests__/collaborate.spec.ts new file mode 100644 index 0000000000..bbfaea4c45 --- /dev/null +++ b/packages/collaborative-vue/src/__tests__/collaborate.spec.ts @@ -0,0 +1,122 @@ +import {nextTick, watchEffect} from 'vue'; +import {Model, s} from 'json-joy/lib/json-crdt'; +import {collaborate} from '..'; + +interface Note { + by: string; + text: string; + at: number; +} +interface Board { + title: string; + notes: Note[]; +} + +const newModel = () => + Model.create( + s.obj({ + title: s.str('Untitled'), + notes: s.arr([]), + }), + ) as unknown as Model; + +describe('collaborate()', () => { + test('reads mirror the document view', () => { + const model = newModel(); + const {state, dispose} = collaborate(model); + expect(state.title).toBe('Untitled'); + expect(state.notes.length).toBe(0); + dispose(); + }); + + test('plain assignment and array methods record CRDT ops', () => { + const model = newModel(); + const {state, dispose} = collaborate(model); + state.title = 'Hello'; + state.notes.push({by: 'a', text: 'first', at: 1}); + state.notes[0].text = 'edited'; + expect(model.view()).toEqual({title: 'Hello', notes: [{by: 'a', text: 'edited', at: 1}]}); + dispose(); + }); + + test('is fine-grained: editing one field does not re-run unrelated effects', () => { + const model = newModel(); + const {state, dispose} = collaborate(model); + + let titleRuns = 0; + let notesRuns = 0; + const stopTitle = watchEffect( + () => { + void state.title; + titleRuns++; + }, + {flush: 'sync'}, + ); + const stopNotes = watchEffect( + () => { + void state.notes.length; + notesRuns++; + }, + {flush: 'sync'}, + ); + expect(titleRuns).toBe(1); + expect(notesRuns).toBe(1); + + state.title = 'Changed'; + expect(titleRuns).toBe(2); + expect(notesRuns).toBe(1); + + state.notes.push({by: 'a', text: 'n', at: 1}); + expect(notesRuns).toBe(2); + expect(titleRuns).toBe(2); + + stopTitle(); + stopNotes(); + dispose(); + }); + + test('applies remote patches and re-renders the affected node', async () => { + const local = newModel(); + local.api.flush(); + const remote = local.fork(); + + const {state, dispose} = collaborate(local); + let titleRuns = 0; + const stop = watchEffect( + () => { + void state.title; + titleRuns++; + }, + {flush: 'sync'}, + ); + expect(titleRuns).toBe(1); + + remote.api.obj([]).set({title: 'From remote'}); + const patch = remote.api.flush(); + local.applyPatch(patch); + await nextTick(); + + expect(state.title).toBe('From remote'); + expect(titleRuns).toBe(2); + + stop(); + dispose(); + }); + + test('dispose() stops reacting to further changes', () => { + const model = newModel(); + const {state, dispose} = collaborate(model); + let runs = 0; + const stop = watchEffect( + () => { + void state.title; + runs++; + }, + {flush: 'sync'}, + ); + dispose(); + model.api.obj([]).set({title: 'after dispose'}); + expect(runs).toBe(1); + stop(); + }); +}); diff --git a/packages/collaborative-vue/src/collaborate.ts b/packages/collaborative-vue/src/collaborate.ts new file mode 100644 index 0000000000..ff5b076f35 --- /dev/null +++ b/packages/collaborative-vue/src/collaborate.ts @@ -0,0 +1,280 @@ +import {getCurrentScope, onScopeDispose, shallowRef, type ShallowRef} from 'vue'; +import {ArrApi, ArrNode, ObjApi, ObjNode, ValNode, VecApi, VecNode} from 'json-joy/lib/json-crdt'; +import type {JsonNode, Model} from 'json-joy/lib/json-crdt'; + +// Optional high-level sugar on top of the composables: a single reactive `state` +// proxy you read/write like a plain object — purpose-built for Vue `v-model` +// two-way binding, which the low-level composables serve awkwardly. It uses the +// same per-node `onNodeChange('self')` subscription the composables use for +// reactivity, and dispatches writes through json-joy's existing node verbs +// (`ObjApi.set`/`del`, `ArrApi.ins`/`upd`/`del`/`merge`, `VecApi.set`). No +// additions to json-joy core. When you need precise control (in-place text ops, +// `merge` vs `set`, explicit event granularity), drop down to the composables. + +type AnyFn = (...args: any[]) => unknown; + +/** + * The minimal node-API surface this binding uses. json-joy's concrete `NodeApi` + * subclasses don't structurally unify (their `.s`/`.$` proxy getters differ), so + * we adapt at one boundary cast to this narrow interface instead of using `any`. + */ +interface CrdtNode { + readonly node: JsonNode; + readonly api: {wrap(node: JsonNode): CrdtNode}; + in(path: string | number, noThrow: true): CrdtNode | undefined; + view(): unknown; + onNodeChange(kind: 'self' | 'child' | 'subtree', listener: () => void): () => void; +} + +export interface CollaborativeDoc { + /** + * A fine-grained reactive view of the CRDT document. Read it in templates + * (including `v-model`) and mutate it with plain assignment / array methods — + * every change records a CRDT operation, and remote changes re-render only the + * parts that changed. + */ + readonly state: T; + /** Tear down all per-node subscriptions. Called automatically when invoked + * inside a Vue effect scope (component `setup`). */ + dispose(): void; +} + +// Resolve through `val`/root register layers to the underlying node. Editing an +// object key fires `onNodeChange('self')` on the OBJ node, not the `val` wrapping +// it, so we track the resolved container — otherwise remote edits to that +// container's keys wouldn't re-render. +function resolve(api: CrdtNode): CrdtNode { + let node = api; + while (node.node instanceof ValNode) node = node.api.wrap(node.node.node()); + return node; +} + +const isContainer = (api: CrdtNode): boolean => { + const node: JsonNode = resolve(api).node; + return node instanceof ObjNode || node instanceof ArrNode || node instanceof VecNode; +}; + +// Write a single property through the concrete node verb, mirroring plain +// object/array assignment semantics. `api` is an already-resolved container. +function writeKey(api: CrdtNode, key: string, value: unknown): void { + const node = api.node; + if (node instanceof ObjNode) { + (api as unknown as ObjApi).set({[key]: value}); + } else if (node instanceof VecNode) { + const index = Number(key); + if (!Number.isNaN(index)) (api as unknown as VecApi).set([[index, value]]); + } else if (node instanceof ArrNode) { + const arr = api as unknown as ArrApi; + const len = arr.length(); + if (key === 'length') { + const next = Number(value); + if (!Number.isNaN(next) && next >= 0 && next < len) arr.del(next, len - next); + return; + } + const index = Number(key); + if (Number.isNaN(index) || index < 0) return; + if (index < len) arr.upd(index, value); + else if (index === len) arr.push(value); + else throw new Error('OUT_OF_BOUNDS'); + } +} + +// Delete a single property through the concrete node verb. `api` is resolved. +function deleteKey(api: CrdtNode, key: string): void { + const node = api.node; + if (node instanceof ObjNode) { + (api as unknown as ObjApi).del([key]); + } else if (node instanceof ArrNode) { + const arr = api as unknown as ArrApi; + const index = Number(key); + if (!Number.isNaN(index) && index >= 0 && index < arr.length()) arr.del(index, 1); + } + // `vec` is fixed-length: deletes are no-ops, matching the read-proxy. +} + +/** + * Bind a json-joy {@link Model} to a single fine-grained Vue reactive object. + * + * The CRDT model stays the source of truth. Reading a node subscribes the + * current Vue effect to it (per-node `onNodeChange('self')`, the same primitive + * the composables use); writing dispatches the matching node verb; applying a + * remote patch (`model.applyPatch(...)`) surfaces through the same signals — + * re-rendering only what changed. Built entirely on json-joy's existing public + * API and on this package's composables. + * + * ```ts + * const {state} = collaborate(model); + * state.title = 'Hello'; // + * state.notes.push({by, text}); + * state.notes[0].text = 'edited'; // deep, in place + * ``` + * + * Transport is out of scope: publish local ops via `model.api.onLocalChange` / + * `model.api.flush()` and feed remote patches to `model.applyPatch(...)`. + */ +export function collaborate(model: Model): CollaborativeDoc { + const unsubs: Array<() => void> = []; + + // One Vue signal per CRDT node, bumped when that node's own value changes. + const signals = new Map>(); + function track(api: CrdtNode): void { + let signal = signals.get(api.node); + if (!signal) { + const created = shallowRef(0); + signals.set(api.node, created); + unsubs.push(api.onNodeChange('self', () => (created.value += 1))); + signal = created; + } + void signal.value; // register dependency with the current Vue effect + } + + // Stable proxy per node (so reads / v-model identities are consistent). + const proxies = new Map(); + function proxyFor(rawApi: CrdtNode): unknown { + const api = resolve(rawApi); + const cached = proxies.get(api.node); + if (cached) return cached; + const isArr = api.node instanceof ArrNode; + + // Materialize the array's elements as a plain array whose entries are the + // child *proxies* (containers) or raw leaf values, so read-only array methods + // (`map`, `at`, iteration, …) stay live and deeply mutable. + const materialize = (): unknown[] => { + const arr = api as unknown as ArrApi; + const length = arr.length(); + const out = new Array(length); + for (let i = 0; i < length; i++) { + const child = api.in(i, true); + out[i] = child && isContainer(child) ? proxyFor(child) : child?.view(); + } + return out; + }; + + // Mutating array methods, expressed via the existing `arr` verbs. + const mutators: Record = isArr + ? (() => { + const arr = api as unknown as ArrApi; + const view = () => api.view() as unknown[]; + return { + push: (...items: unknown[]) => { + if (items.length) arr.push(...items); + return arr.length(); + }, + pop: () => { + const len = arr.length(); + if (!len) return undefined; + const value = view()[len - 1]; + arr.del(len - 1, 1); + return value; + }, + shift: () => { + if (!arr.length()) return undefined; + const value = view()[0]; + arr.del(0, 1); + return value; + }, + unshift: (...items: unknown[]) => { + if (items.length) arr.ins(0, items); + return arr.length(); + }, + splice: (start: number, deleteCount?: number, ...items: unknown[]) => { + const len = arr.length(); + const from = start < 0 ? Math.max(len + start, 0) : Math.min(start, len); + const count = deleteCount === undefined ? len - from : Math.max(0, Math.min(deleteCount, len - from)); + const removed = view().slice(from, from + count); + if (count) arr.del(from, count); + if (items.length) arr.ins(from, items); + return removed; + }, + reverse: () => { + arr.merge(view().slice().reverse()); + return proxy; + }, + sort: (compareFn?: (a: unknown, b: unknown) => number) => { + arr.merge(view().slice().sort(compareFn)); + return proxy; + }, + fill: (value: unknown, start?: number, end?: number) => { + arr.merge(view().slice().fill(value, start, end)); + return proxy; + }, + }; + })() + : {}; + + const proxy: object = new Proxy(isArr ? [] : {}, { + get(_target, key) { + if (typeof key === 'symbol') { + if (isArr) { + track(api); + return (materialize() as unknown as Record)[key]; + } + return undefined; + } + if (isArr) { + if (key === 'length') { + track(api); + return (api as unknown as ArrApi).length(); + } + if (key in mutators) return mutators[key]; + } + const child = api.in(key, true); + if (child && isContainer(child)) { + // Container children keep a stable node identity across their own + // edits, so depend on the child directly — a sibling change to this + // parent must not re-render readers of this child. + track(child); + return proxyFor(child); + } + // Leaf reads (and array read methods / numeric leaf indices): editing a + // scalar replaces its value node and fires `onNodeChange('self')` on THIS + // container, so that's the right dependency. + track(api); + if (isArr) { + const elements = materialize(); + const value = (elements as unknown as Record)[key]; + return typeof value === 'function' ? (value as AnyFn).bind(elements) : value; + } + return (api.view() as Record)[key]; + }, + set(_target, key, value) { + if (typeof key !== 'symbol') writeKey(api, key, value); + return true; + }, + deleteProperty(_target, key) { + if (typeof key !== 'symbol') deleteKey(api, key); + return true; + }, + has(_target, key) { + if (typeof key === 'symbol') return false; + return key in (api.view() as object); + }, + ownKeys() { + return Reflect.ownKeys(api.view() as object); + }, + getOwnPropertyDescriptor(_target, key) { + // For arrays, delegate to the real view array so `length` keeps its + // non-configurable descriptor (required to satisfy the Proxy invariant + // against the array target); numeric indices report as plain enumerable. + if (isArr) return Reflect.getOwnPropertyDescriptor(api.view() as object, key); + if (typeof key === 'symbol') return undefined; + if (key in (api.view() as object)) return {enumerable: true, configurable: true}; + return undefined; + }, + }); + proxies.set(api.node, proxy); + return proxy; + } + + const state = proxyFor(model.api as unknown as CrdtNode) as T; + const dispose = (): void => { + for (const unsub of unsubs) unsub(); + unsubs.length = 0; + signals.clear(); + proxies.clear(); + }; + + if (getCurrentScope()) onScopeDispose(dispose); + + return {state, dispose}; +} diff --git a/packages/collaborative-vue/src/index.ts b/packages/collaborative-vue/src/index.ts index ba3e249533..2eec7dfa19 100644 --- a/packages/collaborative-vue/src/index.ts +++ b/packages/collaborative-vue/src/index.ts @@ -3,3 +3,4 @@ export * from './utils'; export * from './context'; export * from './composables'; export * from './components'; +export {collaborate, type CollaborativeDoc} from './collaborate';