@jupyter/ydoc
Version:
Jupyter document structures for collaborative editing using YJS
97 lines • 2.56 kB
JavaScript
/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
import { YDocument } from './ydocument.js';
/**
* Shareable text file.
*/
export class YFile extends YDocument {
/**
* Create a new file
*
* #### Notes
* The document is empty and must be populated
*/
constructor() {
super();
/**
* Document version
*/
this.version = '1.0.0';
/**
* YJS file text.
*/
this.ysource = this.ydoc.getText('source');
/**
* Handle a change to the ymodel.
*/
this._modelObserver = (event) => {
this._changed.emit({ sourceChange: event.changes.delta });
};
this.undoManager.addToScope(this.ysource);
this.ysource.observe(this._modelObserver);
}
/**
* Creates a standalone YFile
*/
static create() {
return new YFile();
}
/**
* File text
*/
get source() {
return this.getSource();
}
set source(v) {
this.setSource(v);
}
/**
* Dispose of the resources.
*/
dispose() {
if (this.isDisposed) {
return;
}
this.ysource.unobserve(this._modelObserver);
super.dispose();
}
/**
* Get the file text.
*
* @returns File text.
*/
getSource() {
return this.ysource.toString();
}
/**
* Set the file text.
*
* @param value New text
*/
setSource(value) {
this.transact(() => {
const ytext = this.ysource;
ytext.delete(0, ytext.length);
ytext.insert(0, value);
});
}
/**
* Replace content from `start' to `end` with `value`.
*
* @param start: The start index of the range to replace (inclusive).
* @param end: The end index of the range to replace (exclusive).
* @param value: New source (optional).
*/
updateSource(start, end, value = '') {
this.transact(() => {
const ysource = this.ysource;
// insert and then delete.
// This ensures that the cursor position is adjusted after the replaced content.
ysource.insert(start, value);
ysource.delete(start + value.length, end - start);
});
}
}
//# sourceMappingURL=yfile.js.map