├── .github └── workflows │ └── nodejs.yml ├── .gitignore ├── .mocharc.json ├── .storybook ├── config.js └── webpack.config.js ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── package-lock.json ├── package.json ├── src ├── AutomergeCodeMirror.ts ├── Mutex.ts ├── index.ts ├── react │ └── AutomergeCodeMirrorComponent.tsx ├── types.ts ├── updateAutomergeText.ts └── updateCodeMirrorDocs.ts ├── stories ├── index.stories.tsx └── style.css ├── test ├── AutomergeCodeMirrorTest.ts ├── codeMirrorEnv.ts ├── manymerge │ ├── HubDoc.ts │ └── PeerDoc.ts ├── random.ts ├── react │ ├── AutomergeCodeMirrorComponentTest.tsx │ └── PadComponent.tsx ├── updateAutomergeTextTest.ts └── updateCodeMirrorDocsTest.ts └── tsconfig.json /.github/workflows/nodejs.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: Node.js CI 5 | 6 | on: 7 | push: 8 | branches: [ master ] 9 | pull_request: 10 | branches: [ master ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | strategy: 18 | matrix: 19 | node-version: [12.x, 13.x] 20 | 21 | steps: 22 | - uses: actions/checkout@v2 23 | - name: Use Node.js ${{ matrix.node-version }} 24 | uses: actions/setup-node@v1 25 | with: 26 | node-version: ${{ matrix.node-version }} 27 | - run: npm ci 28 | - run: npm run build --if-present 29 | - run: npm test 30 | env: 31 | CI: true 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dist/ 2 | node_modules/ 3 | yarn.lock 4 | .nyc_output/ 5 | coverage/ 6 | yarn-error.log 7 | .idea/ 8 | -------------------------------------------------------------------------------- /.mocharc.json: -------------------------------------------------------------------------------- 1 | { 2 | "require": ["ts-node/register", "source-map-support/register"], 3 | "extension": ["ts", "tsx"], 4 | "recursive": true 5 | } 6 | -------------------------------------------------------------------------------- /.storybook/config.js: -------------------------------------------------------------------------------- 1 | import { configure } from '@storybook/react' 2 | 3 | // automatically import all files ending in *.stories.js 4 | const req = require.context('../stories', true, /\.stories\.tsx$/) 5 | function loadStories() { 6 | req.keys().forEach(filename => req(filename)) 7 | } 8 | 9 | configure(loadStories, module) 10 | -------------------------------------------------------------------------------- /.storybook/webpack.config.js: -------------------------------------------------------------------------------- 1 | module.exports = ({ config }) => { 2 | config.module.rules.push({ 3 | test: /\.(ts|tsx)$/, 4 | use: [ 5 | { 6 | loader: require.resolve('awesome-typescript-loader'), 7 | }, 8 | ], 9 | }) 10 | config.resolve.extensions.push('.ts', '.tsx') 11 | return config 12 | } 13 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # CHANGE LOG 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](http://keepachangelog.com/) 6 | and this project adheres to [Semantic Versioning](http://semver.org/). 7 | 8 | --- 9 | 10 | ## [Unreleased] 11 | 12 | ### Added 13 | 14 | ### Changed 15 | 16 | ### Deprecated 17 | 18 | ### Removed 19 | 20 | ### Fixed 21 | 22 | ## [6.0.0] 23 | 24 | ### Changed 25 | 26 | - Removed dependency on `Automerge.WatchableDoc` 27 | - Completely changed the public API again :-( 28 | 29 | ## [5.0.2] 30 | 31 | ### Fixed 32 | 33 | - Fix a bug where automerge updates would be applied several times to CodeMirror 34 | 35 | ## [5.0.1] 36 | 37 | ### Changed 38 | 39 | - Internals: Make Automerge.Text<->CodeMirror code more cohesive to improve code readability 40 | 41 | ### Fixed 42 | 43 | - Fix export of `useAutomergeDoc` 44 | 45 | ## [5.0.0] 46 | 47 | ### Added 48 | 49 | - [live demo](https://aslakhellesoy.github.io/automerge-codemirror) 50 | - This repo now has a changelog 51 | 52 | ### Changed 53 | 54 | - Upgrade to Automerge 0.14.0 55 | - New, simplified API, with the main objective to make it harder to use the library incorrectly 56 | 57 | ### Removed 58 | 59 | - The `dist` directory is no longer in git 60 | 61 | ## [4.0.5] 62 | 63 | - changelog didn't exist - look at the diff 64 | 65 | ## [4.0.4] 66 | 67 | - changelog didn't exist - look at the diff 68 | 69 | ## [4.0.3] 70 | 71 | - changelog didn't exist - look at the diff 72 | 73 | ## [4.0.2] 74 | 75 | - changelog didn't exist - look at the diff 76 | 77 | ## [4.0.1] 78 | 79 | - changelog didn't exist - look at the diff 80 | 81 | ## [4.0.0] 82 | 83 | - changelog didn't exist - look at the diff 84 | 85 | ## [3.0.0] 86 | 87 | - changelog didn't exist - look at the diff 88 | 89 | ## [2.0.0] 90 | 91 | - changelog didn't exist - look at the diff 92 | 93 | ## [1.0.1] 94 | 95 | - changelog didn't exist - look at the diff 96 | 97 | ## [1.0.0] 98 | 99 | - First stable release! 100 | 101 | 102 | 103 | [unreleased]: https://github.com/aslakhellesoy/automerge-codemirror/compare/v6.0.0...master 104 | [6.0.0]: https://github.com/aslakhellesoy/automerge-codemirror/compare/v5.0.2...v6.0.0 105 | [5.0.2]: https://github.com/aslakhellesoy/automerge-codemirror/compare/v5.0.1...v5.0.2 106 | [5.0.1]: https://github.com/aslakhellesoy/automerge-codemirror/compare/v5.0.0...v5.0.1 107 | [5.0.0]: https://github.com/aslakhellesoy/automerge-codemirror/compare/v4.0.5...v5.0.0 108 | [4.0.5]: https://github.com/aslakhellesoy/automerge-codemirror/compare/v4.0.4...v4.0.5 109 | [4.0.4]: https://github.com/aslakhellesoy/automerge-codemirror/compare/v4.0.3...v4.0.4 110 | [4.0.3]: https://github.com/aslakhellesoy/automerge-codemirror/compare/v4.0.2...v4.0.3 111 | [4.0.2]: https://github.com/aslakhellesoy/automerge-codemirror/compare/v4.0.1...v4.0.2 112 | [4.0.1]: https://github.com/aslakhellesoy/automerge-codemirror/compare/v4.0.0...v4.0.1 113 | [4.0.0]: https://github.com/aslakhellesoy/automerge-codemirror/compare/v3.0.0...v4.0.0 114 | [3.0.0]: https://github.com/aslakhellesoy/automerge-codemirror/compare/v2.0.0...v3.0.0 115 | [2.0.0]: https://github.com/aslakhellesoy/automerge-codemirror/compare/v1.0.1...v2.0.0 116 | [1.0.1]: https://github.com/aslakhellesoy/automerge-codemirror/compare/v1.0.0...v1.0.1 117 | [1.0.0]: https://github.com/aslakhellesoy/automerge-codemirror/tree/v1.0.0 118 | 119 | 120 | 121 | [aslakhellesoy]: https://github.com/aslakhellesoy 122 | [vincentcapicotto]: https://github.com/vincentcapicotto 123 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | ## Making changes 4 | 5 | - Use TDD 6 | - Update `CHANGELOG.md` when you make a significant change 7 | 8 | ## Release process 9 | 10 | Update links in `CHANGELOG.md` and commit. Then: 11 | 12 | npm version NEW_VERSION 13 | npm publish --access public 14 | git push && git push --tags 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) Aslak Hellesøy 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. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Automerge-CodeMirror 2 | 3 | ![Node.js CI](https://github.com/aslakhellesoy/automerge-codemirror/workflows/Node.js%20CI/badge.svg) 4 | 5 | Automerge-CodeMirror brings collaborative editing to CodeMirror by linking it to 6 | an `Automerge.Text` object. 7 | 8 | You can have as many `Automerge.Text` objects as you want inside a single Automerge document, and link each of them to 9 | a separate CodeMirror instance. This is useful for applications that render many editable text areas (such as a 10 | Trello-like application with multiple cards). 11 | 12 | It ships with a React component, but can also be used without React. 13 | 14 | ## Installation 15 | 16 | npm install automerge-codemirror 17 | 18 | ## Live Demo 19 | 20 | [Check it out here](https://aslakhellesoy.github.io/automerge-codemirror) 21 | 22 | To run it locally: 23 | 24 | yarn storybook 25 | 26 | ## General Usage 27 | 28 | ```typescript 29 | import { connectAutomergeDoc } from 'automerge-codemirror' 30 | 31 | // Create a connect function linked to an Automerge document 32 | const connectCodeMirror = connectAutomergeDoc(watchableDoc) 33 | 34 | // Connect a CodeMirror instance 35 | const getText = (doc) => doc.text 36 | const disconnectCodeMirror = connectCodeMirror(codeMirror, getText) 37 | 38 | // Disconnect the CodeMirror instance 39 | disconnectCodeMirror() 40 | ``` 41 | 42 | ## React Usage 43 | 44 | ```typescript jsx 45 | import { connectAutomergeDoc, AutomergeCodeMirror } from 'automerge-codemirror' 46 | 47 | // Create a connect function linked to an Automerge document 48 | const connectCodeMirror = connectAutomergeDoc(watchableDoc) 49 | 50 | // Connect a CodeMirror instance 51 | const getText = (doc) => doc.text 52 | const acm = ( 53 | CodeMirror(element)} 55 | connectCodeMirror={connectCodeMirror} 56 | getText={getText} 57 | /> 58 | ) 59 | ``` 60 | 61 | ## Synchronisation with other peers 62 | 63 | Automerge-CodeMirror is agnostic of how you choose to synchronize the linked Automerge document 64 | with other peers. Just register a handler with the `WatchableDoc` that does the synchronization. 65 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "automerge-codemirror", 3 | "version": "6.0.0", 4 | "description": "Automerge plugin for CodeMirror", 5 | "main": "dist/src/index.js", 6 | "types": "dist/src/index.d.ts", 7 | "repository": "https://github.com/aslakhellesoy/automerge-codemirror", 8 | "author": "Aslak Hellesøy", 9 | "license": "MIT", 10 | "scripts": { 11 | "nyc": "nyc --reporter=html --reporter=text mocha test/**/*.{ts,tsx}", 12 | "test": "mocha test/**/*.{ts,tsx}", 13 | "build": "tsc", 14 | "prepublishOnly": "npm run build", 15 | "storybook": "start-storybook -p 6006", 16 | "build-storybook": "build-storybook", 17 | "deploy-storybook": "storybook-to-ghpages" 18 | }, 19 | "dependencies": { 20 | "@types/cssstyle": "^2.2.0", 21 | "@types/react": "^16.8.19", 22 | "@types/react-dom": "^16.8.4", 23 | "automerge": "^0.14.0", 24 | "codemirror": "^5.47.0", 25 | "react": "^16.8.6", 26 | "react-dom": "^16.8.6" 27 | }, 28 | "devDependencies": { 29 | "@babel/core": "^7.4.5", 30 | "@cucumber/manymerge": "^2.5.5", 31 | "@storybook/addon-actions": "^5.0.11", 32 | "@storybook/addon-links": "^5.0.11", 33 | "@storybook/addons": "^5.0.11", 34 | "@storybook/react": "^5.0.11", 35 | "@storybook/storybook-deployer": "^2.8.5", 36 | "@testing-library/dom": "^7.4.0", 37 | "@types/codemirror": "^0.0.90", 38 | "@types/jsdom": "^16.2.0", 39 | "@types/mocha": "^7.0.2", 40 | "@types/node": "^13.11.0", 41 | "@types/storybook__react": "^5.2.1", 42 | "awesome-typescript-loader": "^5.2.1", 43 | "babel-loader": "^8.0.6", 44 | "cssstyle": "^2.3.0", 45 | "husky": "^4.2.3", 46 | "jsdom": "^16.2.2", 47 | "mocha": "^7.1.1", 48 | "nyc": "^15.0.1", 49 | "prettier": "^2.0.4", 50 | "pretty-quick": "^2.0.1", 51 | "prop-types": "^15.5.9", 52 | "ts-node": "^8.2.0", 53 | "typescript": "^3.4.4", 54 | "webpack": "^4.32.2", 55 | "webpack-cli": "^3.3.0" 56 | }, 57 | "husky": { 58 | "hooks": { 59 | "pre-commit": "pretty-quick --staged" 60 | } 61 | }, 62 | "prettier": { 63 | "trailingComma": "es5", 64 | "semi": false, 65 | "singleQuote": true, 66 | "printWidth": 120 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/AutomergeCodeMirror.ts: -------------------------------------------------------------------------------- 1 | import CodeMirror from 'codemirror' 2 | import Automerge from 'automerge' 3 | import updateCodeMirrorDocs from './updateCodeMirrorDocs' 4 | import Mutex from './Mutex' 5 | import { Change, GetText } from './types' 6 | import updateAutomergeText from './updateAutomergeText' 7 | 8 | /** 9 | * Connect an Automerge document 10 | * 11 | * @param notify - a callback that gets called when the doc is updated as the result of an editor change 12 | * @return ConnectCodeMirror - a function for connecting an Automerge.Text object in the document to a CodeMirror instance 13 | */ 14 | export default class AutomergeCodeMirror { 15 | private readonly mutex: Mutex = new Mutex() 16 | private readonly codeMirrorByTextId = new Map() 17 | 18 | constructor(private readonly change: Change) {} 19 | 20 | getCodeMirror(textObjectId: Automerge.UUID): CodeMirror.Editor | undefined { 21 | return this.codeMirrorByTextId.get(textObjectId) 22 | } 23 | 24 | /** 25 | * Connects a CodeMirror instance to an Automerge.Text object. 26 | * 27 | * @param doc the doc with the text 28 | * @param codeMirror the editor instance 29 | * @param getText a function that looks up the Automerge.Text object to connect the CodeMirror editor to 30 | */ 31 | connectCodeMirror(doc: D, codeMirror: CodeMirror.Editor, getText: GetText) { 32 | const text = getText(doc) 33 | if (!text) { 34 | throw new Error(`Cannot connect CodeMirror. Did not find text in ${JSON.stringify(doc)}`) 35 | } 36 | // Establish the association between the Automerge.Text objectId and the CodeMirror instance. 37 | // This association is used during the processing of diffs between two Automerge document changes, 38 | // so the right CodeMirror instance can be found for each Automerge.Text change. 39 | const textId = Automerge.getObjectId(text) 40 | 41 | this.codeMirrorByTextId.set(textId, codeMirror) 42 | 43 | codeMirror.setValue(text.toString()) 44 | 45 | const codeMirrorChangeHandler = (editor: CodeMirror.Editor, editorChange: CodeMirror.EditorChange) => { 46 | if (editorChange.origin !== 'automerge') { 47 | this.mutex.lock() 48 | this.change((proxy) => updateAutomergeText(proxy, getText, editor.getDoc(), editorChange)) 49 | this.mutex.release() 50 | } 51 | } 52 | 53 | codeMirror.on('change', codeMirrorChangeHandler) 54 | 55 | return () => { 56 | codeMirror.off('change', codeMirrorChangeHandler) 57 | this.codeMirrorByTextId.delete(textId) 58 | } 59 | } 60 | 61 | updateCodeMirrors(oldDoc: D, newDoc: D): D { 62 | return updateCodeMirrorDocs(oldDoc, newDoc, this.getCodeMirror.bind(this), this.mutex) 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/Mutex.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This mutex ensures mutual exclusion of CodeMirror and Automerge updates. 3 | * This is to prevent incoming Automerge changes being propagated to CodeMirror and back again to Automerge. 4 | */ 5 | export default class Mutex { 6 | private _locked: boolean 7 | 8 | get locked() { 9 | return this._locked 10 | } 11 | 12 | lock() { 13 | if (this._locked) throw new Error(`Already locked`) 14 | this._locked = true 15 | } 16 | 17 | release() { 18 | if (!this._locked) throw new Error(`Not locked`) 19 | this._locked = false 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import AutomergeCodeMirror from './AutomergeCodeMirror' 2 | import AutomergeCodeMirrorComponent from './react/AutomergeCodeMirrorComponent' 3 | 4 | export { AutomergeCodeMirror, AutomergeCodeMirrorComponent } 5 | -------------------------------------------------------------------------------- /src/react/AutomergeCodeMirrorComponent.tsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect } from 'react' 2 | import CodeMirror from 'codemirror' 3 | import { GetText } from '../types' 4 | import AutomergeCodeMirror from '../AutomergeCodeMirror' 5 | 6 | interface IProps { 7 | doc: D 8 | makeCodeMirror: (host: HTMLElement) => CodeMirror.Editor 9 | automergeCodeMirror: AutomergeCodeMirror 10 | getText: GetText 11 | } 12 | 13 | const AutomergeCodeMirrorComponent = (props: IProps) => { 14 | const { doc, makeCodeMirror, automergeCodeMirror, getText } = props 15 | let codeMirrorDiv: HTMLDivElement | null 16 | 17 | useEffect(() => { 18 | const codeMirror = makeCodeMirror(codeMirrorDiv!) 19 | return automergeCodeMirror.connectCodeMirror(doc, codeMirror, getText) 20 | }, []) 21 | 22 | return
(codeMirrorDiv = div)} /> 23 | } 24 | 25 | export default AutomergeCodeMirrorComponent 26 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | import Automerge from 'automerge' 2 | 3 | export type GetText = (doc: D | Automerge.Proxy) => Automerge.Text 4 | export type Change = (changeFn: Automerge.ChangeFn>) => void 5 | -------------------------------------------------------------------------------- /src/updateAutomergeText.ts: -------------------------------------------------------------------------------- 1 | import Automerge from 'automerge' 2 | import CodeMirror from 'codemirror' 3 | import { GetText } from './types' 4 | 5 | /** 6 | * Applies CodeMirror changes to an Automerge.Text. This 7 | * function should be called inside an Automerge.change callback. 8 | * 9 | * @param proxy the proxy of the doc containing the text 10 | * @param getText a function that returns a Text object 11 | * @param codeMirrorDoc the editor doc 12 | * @param editorChange the change 13 | */ 14 | export default function updateAutomergeText( 15 | proxy: Automerge.Proxy, 16 | getText: GetText, 17 | codeMirrorDoc: CodeMirror.Doc, 18 | editorChange: CodeMirror.EditorChange 19 | ): void { 20 | const text = getText(proxy) 21 | if (!text) return 22 | const startPos = codeMirrorDoc.indexFromPos(editorChange.from) 23 | 24 | const removedLines = editorChange.removed || [] 25 | const addedLines = editorChange.text 26 | 27 | const removedLength = removedLines.reduce((sum, remove) => sum + remove.length + 1, 0) - 1 28 | if (removedLength > 0) { 29 | text.deleteAt!(startPos, removedLength) 30 | } 31 | 32 | const addedText = addedLines.join('\n') 33 | if (addedText.length > 0) { 34 | text.insertAt!(startPos, ...addedText.split('')) 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/updateCodeMirrorDocs.ts: -------------------------------------------------------------------------------- 1 | import Automerge from 'automerge' 2 | import Mutex from './Mutex' 3 | 4 | /** 5 | * Applies the diff between two Automerge documents to CodeMirror instances 6 | */ 7 | export default function updateCodeMirrorDocs( 8 | oldDoc: D, 9 | newDoc: D, 10 | getCodeMirror: (textObjectId: Automerge.UUID) => CodeMirror.Editor | undefined, 11 | mutex: Mutex 12 | ): D { 13 | if (mutex.locked || !oldDoc) { 14 | return newDoc 15 | } 16 | const diffs = Automerge.diff(oldDoc, newDoc) 17 | 18 | for (const diff of diffs) { 19 | if (diff.type !== 'text') continue 20 | const codeMirror = getCodeMirror(diff.obj) 21 | if (!codeMirror) continue 22 | const codeMirrorDoc = codeMirror.getDoc() 23 | 24 | switch (diff.action) { 25 | case 'insert': { 26 | const fromPos = codeMirrorDoc.posFromIndex(diff.index!) 27 | codeMirrorDoc.replaceRange(diff.value, fromPos, undefined, 'automerge') 28 | break 29 | } 30 | case 'remove': { 31 | const fromPos = codeMirrorDoc.posFromIndex(diff.index!) 32 | const toPos = codeMirrorDoc.posFromIndex(diff.index! + 1) 33 | codeMirrorDoc.replaceRange('', fromPos, toPos, 'automerge') 34 | break 35 | } 36 | } 37 | } 38 | return newDoc 39 | } 40 | -------------------------------------------------------------------------------- /stories/index.stories.tsx: -------------------------------------------------------------------------------- 1 | import { storiesOf } from '@storybook/react' 2 | import React from 'react' 3 | import 'codemirror/lib/codemirror.css' 4 | import 'codemirror/theme/material.css' 5 | 6 | import './style.css' 7 | import { Pad, PadComponent } from '../test/react/PadComponent' 8 | 9 | import PeerDoc from '../test/manymerge/PeerDoc' 10 | import HubDoc from '../test/manymerge/HubDoc' 11 | import { Message } from '@cucumber/manymerge' 12 | import AutomergeCodeMirror from '../src/AutomergeCodeMirror' 13 | import { Change } from '../src/types' 14 | 15 | storiesOf('Collaboration', module).add('Multiple CodeMirrors linked to a single Automerge doc', () => { 16 | const peerDocById = new Map>() 17 | 18 | const hubDoc = new HubDoc( 19 | (peerId: string, msg: Message) => setTimeout(() => peerDocById.get(peerId)!.applyMessage(msg), 0), 20 | (msg: Message) => 21 | Array.from(peerDocById.values()).forEach((peerDoc) => setTimeout(() => peerDoc.applyMessage(msg), 0)) 22 | ) 23 | 24 | const peerIds = ['Wilma', 'Fred', 'Barney'] 25 | for (const peerId of peerIds) { 26 | peerDocById.set( 27 | peerId, 28 | new PeerDoc((msg) => setTimeout(() => hubDoc.applyMessage(peerId, msg), 0)) 29 | ) 30 | } 31 | 32 | return ( 33 |
34 |

35 | Below are three actors - Wilma, Fred and Barney. They each have a Pad with sheets. Each sheet is connected to a 36 | CodeMirror editor. 37 |

38 |

39 | The source code is at 40 | here. 41 |

42 |
43 | {peerIds.map((peerId) => { 44 | let timer: ReturnType 45 | const peerDoc = peerDocById.get(peerId)! 46 | const change: Change = (changeFn) => { 47 | peerDoc.change(changeFn) 48 | clearTimeout(timer) 49 | timer = setTimeout(() => peerDoc.notify(), 5000) 50 | } 51 | return ( 52 |
53 |

{peerId}

54 | (change)} /> 55 |
56 | ) 57 | })} 58 |
59 |
60 | ) 61 | }) 62 | -------------------------------------------------------------------------------- /stories/style.css: -------------------------------------------------------------------------------- 1 | .CodeMirror { 2 | height: auto; 3 | background: inherit; 4 | } 5 | 6 | .pads { 7 | display: flex; 8 | } 9 | 10 | .pad { 11 | margin: 10px; 12 | border: black solid 1px; 13 | } 14 | 15 | .sheet { 16 | margin: 4px; 17 | border: black solid 1px; 18 | } 19 | -------------------------------------------------------------------------------- /test/AutomergeCodeMirrorTest.ts: -------------------------------------------------------------------------------- 1 | import assert from 'assert' 2 | import './codeMirrorEnv' 3 | import Automerge from 'automerge' 4 | import CodeMirror from 'codemirror' 5 | import AutomergeCodeMirror from '../src/AutomergeCodeMirror' 6 | import { Change } from '../src/types' 7 | 8 | interface TestDoc { 9 | text: Automerge.Text 10 | } 11 | 12 | describe('AutomerCodeMirror', () => { 13 | let doc: Automerge.Doc 14 | let change: Change> = (changeFn) => (doc = Automerge.change(doc, changeFn)) 15 | const getText = (testDoc: TestDoc) => testDoc.text 16 | let host: HTMLElement 17 | let codeMirror: CodeMirror.Editor 18 | 19 | beforeEach(() => { 20 | doc = Automerge.from({ text: new Automerge.Text() }) 21 | host = document.body.appendChild(document.createElement('div')) 22 | codeMirror = CodeMirror(host) 23 | }) 24 | 25 | afterEach(() => { 26 | host.remove() 27 | }) 28 | 29 | describe('Automerge => CodeMirror', () => { 30 | it('handles 2 consecutive Automerge changes', () => { 31 | const automergeCodeMirror = new AutomergeCodeMirror(change) 32 | const disconnectCodeMirror = automergeCodeMirror.connectCodeMirror(doc, codeMirror, getText) 33 | 34 | doc = automergeCodeMirror.updateCodeMirrors( 35 | doc, 36 | Automerge.change(doc, (proxy) => proxy.text.insertAt!(0, 'hello')) 37 | ) 38 | 39 | assert.strictEqual(codeMirror.getValue(), 'hello') 40 | 41 | doc = automergeCodeMirror.updateCodeMirrors( 42 | doc, 43 | Automerge.change(doc, (proxy) => proxy.text.insertAt!(0, 'world')) 44 | ) 45 | 46 | assert.strictEqual(codeMirror.getValue(), 'worldhello') 47 | 48 | disconnectCodeMirror() 49 | }) 50 | 51 | it('ignores Automerge changes after disconnection', () => { 52 | const automergeCodeMirror = new AutomergeCodeMirror(change) 53 | const disconnectCodeMirror = automergeCodeMirror.connectCodeMirror(doc, codeMirror, getText) 54 | 55 | doc = automergeCodeMirror.updateCodeMirrors( 56 | doc, 57 | Automerge.change(doc, (proxy) => proxy.text.insertAt!(0, 'hello')) 58 | ) 59 | 60 | assert.strictEqual(codeMirror.getValue(), 'hello') 61 | disconnectCodeMirror() 62 | 63 | doc = automergeCodeMirror.updateCodeMirrors( 64 | doc, 65 | Automerge.change(doc, (proxy) => proxy.text.insertAt!(0, 'world')) 66 | ) 67 | 68 | assert.strictEqual(codeMirror.getValue(), 'hello') 69 | }) 70 | 71 | it('handles document update before CodeMirror is connected', () => { 72 | const automergeCodeMirror = new AutomergeCodeMirror(change) 73 | 74 | doc = automergeCodeMirror.updateCodeMirrors( 75 | doc, 76 | Automerge.change(doc, (proxy) => { 77 | proxy.text.insertAt!(0, 'World') 78 | }) 79 | ) 80 | 81 | automergeCodeMirror.connectCodeMirror(doc, codeMirror, getText) 82 | 83 | assert.strictEqual(codeMirror.getValue(), 'World') 84 | 85 | doc = automergeCodeMirror.updateCodeMirrors( 86 | doc, 87 | Automerge.change(doc, (proxy) => { 88 | proxy.text.insertAt!(0, 'Hello ') 89 | }) 90 | ) 91 | 92 | assert.strictEqual(codeMirror.getValue(), 'Hello World') 93 | }) 94 | }) 95 | 96 | describe('CodeMirror => Automerge', () => { 97 | it('handles 2 consecutive CodeMirror changes', () => { 98 | const automergeCodeMirror = new AutomergeCodeMirror(change) 99 | automergeCodeMirror.connectCodeMirror(doc, codeMirror, getText) 100 | 101 | codeMirror.replaceRange('hello', codeMirror.posFromIndex(0)) 102 | assert.strictEqual(codeMirror.getValue(), 'hello') 103 | assert.strictEqual(doc.text.toString(), 'hello') 104 | 105 | codeMirror.replaceRange('world', codeMirror.posFromIndex(0)) 106 | assert.strictEqual(codeMirror.getValue(), 'worldhello') 107 | assert.strictEqual(doc.text.toString(), 'worldhello') 108 | }) 109 | }) 110 | }) 111 | -------------------------------------------------------------------------------- /test/codeMirrorEnv.ts: -------------------------------------------------------------------------------- 1 | // Minimal browser-like environment to make CodeMirror load (for tests in Node.js) 2 | import { JSDOM } from 'jsdom' 3 | import { CSSStyleDeclaration } from 'cssstyle' 4 | 5 | const dom = new JSDOM(` 6 | 7 | 8 | `) 9 | // https://discuss.codemirror.net/t/working-in-jsdom-or-node-js-natively/138/5 10 | const createRange = dom.window.document.createRange 11 | 12 | const patchedCreateRange = function () { 13 | // @ts-ignore 14 | const range: Range = createRange.apply(this, arguments) 15 | range.getBoundingClientRect = () => { 16 | const rect: DOMRect = { 17 | height: 0, 18 | width: 0, 19 | bottom: 0, 20 | left: 0, 21 | right: 0, 22 | top: 0, 23 | x: 0, 24 | y: 0, 25 | toJSON(): any { 26 | { 27 | } 28 | }, 29 | } 30 | return rect 31 | } 32 | range.getClientRects = () => { 33 | const rects: DOMRectList = { 34 | item(index: number): DOMRect | null { 35 | return null 36 | }, 37 | length: 0, 38 | } 39 | return rects 40 | } 41 | return range 42 | } 43 | dom.window.document.createRange = patchedCreateRange 44 | 45 | // @ts-ignore 46 | global.getComputedStyle = () => new CSSStyleDeclaration() 47 | // @ts-ignore 48 | global.window = dom.window 49 | // @ts-ignore 50 | global.navigator = dom.window.navigator 51 | // @ts-ignore 52 | global.document = dom.window.document 53 | -------------------------------------------------------------------------------- /test/manymerge/HubDoc.ts: -------------------------------------------------------------------------------- 1 | import { Message, Hub } from '@cucumber/manymerge' 2 | import Automerge from 'automerge' 3 | 4 | export default class HubDoc { 5 | private readonly hub: Hub 6 | private _doc = Automerge.init() 7 | 8 | constructor(sendMsgTo: (peerId: string, msg: Message) => void, broadcastMsg: (msg: Message) => void) { 9 | this.hub = new Hub(sendMsgTo, broadcastMsg) 10 | } 11 | 12 | applyMessage(peerId: string, msg: Message) { 13 | const newDoc = this.hub.applyMessage(peerId, msg, this._doc) 14 | if (newDoc) { 15 | this._doc = newDoc 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /test/manymerge/PeerDoc.ts: -------------------------------------------------------------------------------- 1 | import { Message, Peer } from '@cucumber/manymerge' 2 | import Automerge from 'automerge' 3 | 4 | type Handler = (oldDoc: Automerge.Doc, newDoc: Automerge.Doc) => void 5 | 6 | export default class PeerDoc { 7 | private readonly handlers = new Set>() 8 | private readonly peer: Peer 9 | private _doc = Automerge.init() 10 | 11 | get doc() { 12 | return this._doc 13 | } 14 | 15 | constructor(sendMsg: (msg: Message) => void) { 16 | this.peer = new Peer(sendMsg) 17 | } 18 | 19 | applyMessage(msg: Message) { 20 | const oldDoc = this._doc 21 | const newDoc = this.peer.applyMessage(msg, oldDoc) 22 | if (newDoc) { 23 | this._doc = newDoc 24 | for (const handler of this.handlers) { 25 | handler(oldDoc, newDoc) 26 | } 27 | } 28 | } 29 | 30 | change(changeFn: Automerge.ChangeFn) { 31 | const oldDoc = this._doc 32 | this._doc = Automerge.change(this._doc, changeFn) 33 | for (const handler of this.handlers) { 34 | handler(oldDoc, this._doc) 35 | } 36 | } 37 | 38 | notify() { 39 | this.peer.notify(this._doc) 40 | } 41 | 42 | subscribe(handler: Handler) { 43 | this.handlers.add(handler) 44 | return () => { 45 | this.handlers.delete(handler) 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /test/random.ts: -------------------------------------------------------------------------------- 1 | function randomString(len: number): string { 2 | const chars = 3 | '0123456789\nABCDEF\nGHIJKLM\nNOPQRSTUVWXTZ\nabcde\nfghiklmnop\nqrstuvwxyz' 4 | let result = '' 5 | for (let i = 0; i < len; i++) { 6 | const rnum = randomPositiveInt(chars.length) 7 | result += chars.substring(rnum, rnum + 1) 8 | } 9 | return result 10 | } 11 | 12 | function randomPositiveInt(max: number): number { 13 | return Math.floor(Math.random() * max) + 1 14 | } 15 | 16 | export { randomString, randomPositiveInt } 17 | -------------------------------------------------------------------------------- /test/react/AutomergeCodeMirrorComponentTest.tsx: -------------------------------------------------------------------------------- 1 | import '../codeMirrorEnv' 2 | import { waitFor } from '@testing-library/dom' 3 | import { render, unmountComponentAtNode } from 'react-dom' 4 | import CodeMirror from 'codemirror' 5 | import Automerge from 'automerge' 6 | import React from 'react' 7 | import assert from 'assert' 8 | import AutomergeCodeMirror from '../../src/AutomergeCodeMirror' 9 | import { Pad, PadComponent } from './PadComponent' 10 | import HubDoc from '../../test/manymerge/HubDoc' 11 | import PeerDoc from '../../test/manymerge/PeerDoc' 12 | 13 | describe('', () => { 14 | let host: HTMLElement 15 | let hubDoc: HubDoc 16 | const peerDocs: { [peerId: string]: PeerDoc } = {} 17 | 18 | beforeEach(async () => { 19 | host = document.body.appendChild(document.createElement('div')) 20 | 21 | hubDoc = new HubDoc( 22 | (peerId: string, msg) => { 23 | process.nextTick(() => peerDocs[peerId].applyMessage(msg)) 24 | }, 25 | (msg) => 26 | Object.keys(peerDocs).forEach((peerId) => { 27 | const peerDoc = peerDocs[peerId] 28 | process.nextTick(() => peerDoc.applyMessage(msg)) 29 | }) 30 | ) 31 | 32 | peerDocs['bot'] = new PeerDoc((msg) => { 33 | process.nextTick(() => hubDoc.applyMessage('bot', msg)) 34 | }) 35 | peerDocs['user'] = new PeerDoc((msg) => { 36 | process.nextTick(() => hubDoc.applyMessage('user', msg)) 37 | }) 38 | 39 | const userPeerDoc = peerDocs['user'] 40 | const automergeCodeMirror = new AutomergeCodeMirror>(userPeerDoc.change.bind(userPeerDoc)) 41 | render(, host) 42 | await new Promise((resolve) => setTimeout(resolve, 100)) 43 | }) 44 | 45 | afterEach(() => { 46 | unmountComponentAtNode(host) 47 | host.remove() 48 | }) 49 | 50 | it('updates Automerge doc when CodeMirror doc changes', async () => { 51 | peerDocs['user'].change((proxy) => (proxy.sheets = [new Automerge.Text()])) 52 | const codeMirror: CodeMirror.Editor = await findCodeMirrorEditor(host) 53 | codeMirror.setValue('hello') 54 | assert.strictEqual(peerDocs['user'].doc.sheets[0].toString(), 'hello') 55 | 56 | peerDocs['user'].notify() 57 | await new Promise((resolve) => setTimeout(resolve, 50)) 58 | 59 | assert.strictEqual(peerDocs['bot'].doc.sheets[0].toString(), 'hello') 60 | }) 61 | 62 | it('updates CodeMirror doc when Automerge doc changes', async () => { 63 | peerDocs['bot'].change((proxy) => (proxy.sheets = [new Automerge.Text()])) 64 | peerDocs['bot'].notify() 65 | const codeMirror: CodeMirror.Editor = await findCodeMirrorEditor(host) 66 | assert.strictEqual(codeMirror.getValue(), '') 67 | 68 | peerDocs['bot'].change((proxy) => proxy.sheets[0].insertAt!(0, ...'hello'.split(''))) 69 | peerDocs['bot'].notify() 70 | 71 | await new Promise((resolve) => setTimeout(resolve, 50)) 72 | 73 | assert.strictEqual(codeMirror.getValue(), 'hello') 74 | assert.strictEqual(peerDocs['user'].doc.sheets[0].toString(), 'hello') 75 | }) 76 | 77 | it('syncs CodeMirror doc when Automerge doc changes om 2 peers', async () => { 78 | peerDocs['bot'].change((proxy) => (proxy.sheets = [new Automerge.Text()])) 79 | peerDocs['bot'].notify() 80 | await new Promise((resolve) => setTimeout(resolve, 50)) 81 | assert.strictEqual(peerDocs['user'].doc.sheets[0].toString(), '') 82 | 83 | peerDocs['bot'].change((proxy) => proxy.sheets[0].insertAt!(0, ...'BOT'.split(''))) 84 | peerDocs['user'].change((proxy) => proxy.sheets[0].insertAt!(0, ...'USER'.split(''))) 85 | 86 | peerDocs['bot'].notify() 87 | peerDocs['user'].notify() 88 | 89 | await new Promise((resolve) => setTimeout(resolve, 50)) 90 | assert.strictEqual(peerDocs['bot'].doc.sheets[0].toString(), peerDocs['user'].doc.sheets[0].toString()) 91 | }) 92 | }) 93 | 94 | async function findCodeMirrorEditor(element: HTMLElement): Promise { 95 | return waitFor( 96 | // @ts-ignore 97 | () => element.querySelector('.CodeMirror')!.CodeMirror!, 98 | { container: element } 99 | ) 100 | } 101 | -------------------------------------------------------------------------------- /test/react/PadComponent.tsx: -------------------------------------------------------------------------------- 1 | import Automerge from 'automerge' 2 | import React, { FunctionComponent, useEffect, useState } from 'react' 3 | import CodeMirror from 'codemirror' 4 | import PeerDoc from '../../test/manymerge/PeerDoc' 5 | import AutomergeCodeMirror from '../../src/AutomergeCodeMirror' 6 | import AutomergeCodeMirrorComponent from '../../src/react/AutomergeCodeMirrorComponent' 7 | 8 | interface Pad { 9 | sheets: Automerge.Text[] 10 | } 11 | 12 | interface Props { 13 | peerDoc: PeerDoc 14 | automergeCodeMirror: AutomergeCodeMirror 15 | } 16 | 17 | const PadComponent: FunctionComponent = ({ peerDoc, automergeCodeMirror }) => { 18 | const [doc, setDoc] = useState(peerDoc.doc) 19 | 20 | useEffect(() => { 21 | return peerDoc.subscribe((oldDoc, newDoc) => { 22 | automergeCodeMirror.updateCodeMirrors(oldDoc, newDoc) 23 | setDoc(newDoc) 24 | }) 25 | }, []) 26 | 27 | function createSheet() { 28 | peerDoc.change((proxy) => { 29 | if (proxy.sheets == undefined) proxy.sheets = [] 30 | proxy.sheets.push(new Automerge.Text()) 31 | }) 32 | 33 | peerDoc.notify() 34 | } 35 | 36 | function removeSheet() { 37 | peerDoc.change((proxy) => { 38 | if (proxy.sheets) { 39 | proxy.sheets.shift() 40 | } 41 | }) 42 | 43 | peerDoc.notify() 44 | } 45 | 46 | function makeCodeMirror(element: HTMLElement): CodeMirror.Editor { 47 | return CodeMirror(element, { 48 | viewportMargin: Infinity, 49 | lineWrapping: true, 50 | extraKeys: { 51 | Tab: false, 52 | }, 53 | }) 54 | } 55 | 56 | return ( 57 |
58 | 59 | 60 | {(doc.sheets || []).map((_, i) => { 61 | function getText(doc: Pad | Automerge.Proxy) { 62 | return doc.sheets[i] 63 | } 64 | return ( 65 |
66 | 67 | doc={doc} 68 | makeCodeMirror={makeCodeMirror} 69 | automergeCodeMirror={automergeCodeMirror} 70 | getText={getText} 71 | /> 72 |
73 | ) 74 | })} 75 |
76 | ) 77 | } 78 | 79 | export { PadComponent, Pad } 80 | -------------------------------------------------------------------------------- /test/updateAutomergeTextTest.ts: -------------------------------------------------------------------------------- 1 | import assert from 'assert' 2 | import './codeMirrorEnv' 3 | import Automerge from 'automerge' 4 | import updateAutomergeText from '../src/updateAutomergeText' 5 | import CodeMirror from 'codemirror' 6 | import { randomPositiveInt, randomString } from './random' 7 | 8 | interface TestDoc { 9 | text: Automerge.Text 10 | } 11 | 12 | const getText = (doc: TestDoc): Automerge.Text => doc.text 13 | 14 | describe('updateAutomergeDoc', () => { 15 | let div: HTMLDivElement 16 | beforeEach(() => { 17 | div = document.createElement('div') 18 | document.body.appendChild(div) 19 | }) 20 | 21 | it('adds new text', () => { 22 | let doc: TestDoc = Automerge.change(Automerge.init(), (draft) => (draft.text = new Automerge.Text())) 23 | 24 | const codeMirror = CodeMirror(div) 25 | codeMirror.on('change', (editor, editorChange) => { 26 | doc = Automerge.change(doc, (proxy) => updateAutomergeText(proxy, getText, editor.getDoc(), editorChange)) 27 | }) 28 | 29 | codeMirror.getDoc().replaceRange('HELLO', { line: 0, ch: 0 }) 30 | 31 | assert.deepStrictEqual('HELLO', doc.text.join('')) 32 | }) 33 | 34 | for (let n = 0; n < 10; n++) { 35 | it(`works with random edits (fuzz test ${n})`, () => { 36 | let doc: TestDoc = Automerge.change(Automerge.init(), (draft) => { 37 | draft.text = new Automerge.Text() 38 | }) 39 | 40 | const codeMirror = CodeMirror(div) 41 | codeMirror.on('change', (editor, editorChange) => { 42 | doc = Automerge.change(doc, (proxy) => updateAutomergeText(proxy, getText, editor.getDoc(), editorChange)) 43 | }) 44 | 45 | for (let t = 0; t < 10; t++) { 46 | monkeyType(codeMirror.getDoc()) 47 | } 48 | 49 | assert.deepStrictEqual(doc.text.join(''), codeMirror.getValue()) 50 | }) 51 | } 52 | }) 53 | 54 | function monkeyType(codeMirrorDoc: CodeMirror.Doc) { 55 | const textLength = codeMirrorDoc.getValue().length 56 | const index = Math.floor(Math.random() * textLength) 57 | const from = codeMirrorDoc.posFromIndex(index) 58 | const editLength = randomPositiveInt(10) 59 | if (Math.random() < 0.7) { 60 | // Add text 61 | const text = randomString(editLength) 62 | codeMirrorDoc.replaceRange(text, codeMirrorDoc.posFromIndex(index)) 63 | } else { 64 | const endIndex = Math.max(index + editLength, textLength - index) 65 | const to = codeMirrorDoc.posFromIndex(endIndex) 66 | codeMirrorDoc.replaceRange('', from, to) 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /test/updateCodeMirrorDocsTest.ts: -------------------------------------------------------------------------------- 1 | import assert from 'assert' 2 | import './codeMirrorEnv' 3 | import Automerge from 'automerge' 4 | import updateCodeMirrorDocs from '../src/updateCodeMirrorDocs' 5 | import CodeMirror from 'codemirror' 6 | import { randomPositiveInt, randomString } from './random' 7 | import Mutex from '../src/Mutex' 8 | 9 | interface TestDoc { 10 | text: Automerge.Text 11 | } 12 | 13 | interface TestDocWithManyTexts { 14 | texts: Automerge.Text[] 15 | } 16 | 17 | describe('updateCodeMirrorDocs', () => { 18 | let div: HTMLDivElement 19 | beforeEach(() => { 20 | div = document.createElement('div') 21 | document.body.appendChild(div) 22 | }) 23 | 24 | it('adds new text', () => { 25 | const doc1: TestDoc = Automerge.init() 26 | const doc2: TestDoc = Automerge.change(doc1, (draft) => { 27 | draft.text = new Automerge.Text() 28 | draft.text.insertAt!(0, ...'HELLO'.split('')) 29 | }) 30 | const doc3: TestDoc = Automerge.change(doc2, (draft) => { 31 | draft.text.insertAt!(5, ...'WORLD'.split('')) 32 | }) 33 | 34 | const codeMirror = CodeMirror(div) 35 | const mutex = new Mutex() 36 | 37 | updateCodeMirrorDocs(doc1, doc2, () => codeMirror, mutex) 38 | assert.deepStrictEqual(codeMirror.getValue(), doc2.text.toString()) 39 | 40 | updateCodeMirrorDocs(doc2, doc3, () => codeMirror, mutex) 41 | assert.deepStrictEqual(codeMirror.getValue(), doc3.text.toString()) 42 | }) 43 | 44 | it('handles a removed text node without crashing', () => { 45 | const doc1: TestDocWithManyTexts = Automerge.init() 46 | const doc2: TestDocWithManyTexts = Automerge.change(doc1, (draft) => { 47 | draft.texts = [] 48 | draft.texts.push(new Automerge.Text()) 49 | }) 50 | 51 | const codeMirror = CodeMirror(div) 52 | const mutex = new Mutex() 53 | 54 | updateCodeMirrorDocs(doc1, doc2, () => codeMirror, mutex) 55 | assert.deepStrictEqual(codeMirror.getValue(), doc2.texts[0].join('')) 56 | 57 | const doc3: TestDocWithManyTexts = Automerge.change(doc2, (draft) => { 58 | draft.texts.shift() 59 | }) 60 | 61 | updateCodeMirrorDocs(doc2, doc3, () => codeMirror, mutex) 62 | }) 63 | 64 | for (let n = 0; n < 10; n++) { 65 | it(`works with random edits (fuzz test ${n})`, () => { 66 | let doc: TestDoc = Automerge.change(Automerge.init(), (draft) => (draft.text = new Automerge.Text())) 67 | 68 | const codeMirror = CodeMirror(div) 69 | const mutex = new Mutex() 70 | 71 | for (let t = 0; t < 10; t++) { 72 | const newDoc = monkeyModify(doc) 73 | updateCodeMirrorDocs(doc, newDoc, () => codeMirror, mutex) 74 | doc = newDoc 75 | } 76 | 77 | assert.deepStrictEqual(doc.text.toString(), codeMirror.getValue()) 78 | }) 79 | } 80 | 81 | context('performance tests', () => { 82 | it('is very fast', () => { 83 | const initialDoc = Automerge.from({ text: new Automerge.Text() }) 84 | let doc = initialDoc 85 | for (let i = 0; i < 11; i++) { 86 | doc = Automerge.change(doc, (proxy) => { 87 | if (i % 2 == 0) { 88 | proxy.text.insertAt!(0, ...'hello'.split('')) 89 | } else { 90 | proxy.text.deleteAt!(0, 5) 91 | } 92 | }) 93 | } 94 | 95 | const codeMirror = CodeMirror(div) 96 | const mutex = new Mutex() 97 | 98 | updateCodeMirrorDocs(initialDoc, doc, () => codeMirror, mutex) 99 | assert.deepStrictEqual(codeMirror.getValue(), doc.text.toString()) 100 | }) 101 | }) 102 | }) 103 | 104 | function monkeyModify(doc: TestDoc): TestDoc { 105 | const textLength = doc.text.length 106 | const index = Math.floor(Math.random() * textLength) 107 | const editLength = randomPositiveInt(10) 108 | if (Math.random() < 0.7) { 109 | // Add text 110 | doc = Automerge.change(doc, (editableDoc) => { 111 | editableDoc.text.insertAt!(index, ...randomString(editLength).split('')) 112 | }) 113 | } else { 114 | const endIndex = Math.min(index + editLength, textLength - index) 115 | doc = Automerge.change(doc, (editableDoc) => { 116 | editableDoc.text.deleteAt!(index, endIndex) 117 | }) 118 | } 119 | return doc 120 | } 121 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "dist", 4 | "module": "commonjs", 5 | "target": "es5", 6 | "lib": ["es2018", "dom"], 7 | "sourceMap": true, 8 | "allowJs": false, 9 | "jsx": "react", 10 | "moduleResolution": "node", 11 | "baseUrl": "src", 12 | "forceConsistentCasingInFileNames": true, 13 | "noImplicitReturns": true, 14 | "noImplicitThis": true, 15 | "noImplicitAny": true, 16 | "strictNullChecks": true, 17 | "suppressImplicitAnyIndexErrors": true, 18 | "noUnusedLocals": true, 19 | "declaration": true, 20 | "allowSyntheticDefaultImports": true, 21 | "experimentalDecorators": true, 22 | "emitDecoratorMetadata": true, 23 | "downlevelIteration": true, 24 | "esModuleInterop": true, 25 | "types": ["node", "automerge", "codemirror", "mocha"] 26 | }, 27 | "include": ["src", "test", "stories"], 28 | "exclude": ["node_modules"] 29 | } 30 | --------------------------------------------------------------------------------