Pad: Use ES6 class syntax to improve readability

This commit is contained in:
Richard Hansen 2021-11-21 23:55:17 -05:00
parent 38b2ffe899
commit addc019810

View file

@ -35,14 +35,15 @@ exports.cleanText = (txt) => txt.replace(/\r\n/g, '\n')
.replace(/\t/g, ' ')
.replace(/\xa0/g, ' ');
/**
* @param [database] - Database object to access this pad's records (and only this pad's records --
* the shared global Etherpad database object is still used for all other pad accesses, such as
* copying the pad). Defaults to the shared global Etherpad database object. This parameter can
* be used to shard pad storage across multiple database backends, to put each pad in its own
* database table, or to validate imported pad data before it is written to the database.
class Pad {
/**
* @param [database] - Database object to access this pad's records (and only this pad's records;
* the shared global Etherpad database object is still used for all other pad accesses, such
* as copying the pad). Defaults to the shared global Etherpad database object. This parameter
* can be used to shard pad storage across multiple database backends, to put each pad in its
* own database table, or to validate imported pad data before it is written to the database.
*/
const Pad = function (id, database = db) {
constructor(id, database = db) {
this.db = database;
this.atext = Changeset.makeAText('\n');
this.pool = new AttributePool();
@ -51,33 +52,31 @@ const Pad = function (id, database = db) {
this.publicStatus = false;
this.id = id;
this.savedRevisions = [];
};
}
exports.Pad = Pad;
Pad.prototype.apool = function () {
apool() {
return this.pool;
};
}
Pad.prototype.getHeadRevisionNumber = function () {
getHeadRevisionNumber() {
return this.head;
};
}
Pad.prototype.getSavedRevisionsNumber = function () {
getSavedRevisionsNumber() {
return this.savedRevisions.length;
};
}
Pad.prototype.getSavedRevisionsList = function () {
getSavedRevisionsList() {
const savedRev = this.savedRevisions.map((rev) => rev.revNum);
savedRev.sort((a, b) => a - b);
return savedRev;
};
}
Pad.prototype.getPublicStatus = function () {
getPublicStatus() {
return this.publicStatus;
};
}
Pad.prototype.appendRevision = async function (aChangeset, authorId = '') {
async appendRevision(aChangeset, authorId = '') {
const newAText = Changeset.applyToAText(aChangeset, this.atext, this.pool);
if (newAText.text === this.atext.text && newAText.attribs === this.atext.attribs) {
return this.head;
@ -130,10 +129,10 @@ Pad.prototype.appendRevision = async function (aChangeset, authorId = '') {
await Promise.all(p);
return newRev;
};
}
// save all attributes to the database
Pad.prototype.saveToDatabase = async function () {
// save all attributes to the database
async saveToDatabase() {
const dbObject = {};
for (const attr in this) {
@ -148,27 +147,27 @@ Pad.prototype.saveToDatabase = async function () {
}
await this.db.set(`pad:${this.id}`, dbObject);
};
}
// get time of last edit (changeset application)
Pad.prototype.getLastEdit = async function () {
// get time of last edit (changeset application)
async getLastEdit() {
const revNum = this.getHeadRevisionNumber();
return await this.db.getSub(`pad:${this.id}:revs:${revNum}`, ['meta', 'timestamp']);
};
}
Pad.prototype.getRevisionChangeset = async function (revNum) {
async getRevisionChangeset(revNum) {
return await this.db.getSub(`pad:${this.id}:revs:${revNum}`, ['changeset']);
};
}
Pad.prototype.getRevisionAuthor = async function (revNum) {
async getRevisionAuthor(revNum) {
return await this.db.getSub(`pad:${this.id}:revs:${revNum}`, ['meta', 'author']);
};
}
Pad.prototype.getRevisionDate = async function (revNum) {
async getRevisionDate(revNum) {
return await this.db.getSub(`pad:${this.id}:revs:${revNum}`, ['meta', 'timestamp']);
};
}
Pad.prototype.getAllAuthors = function () {
getAllAuthors() {
const authorIds = [];
for (const key in this.pool.numToAttrib) {
@ -178,9 +177,9 @@ Pad.prototype.getAllAuthors = function () {
}
return authorIds;
};
}
Pad.prototype.getInternalRevisionAText = async function (targetRev) {
async getInternalRevisionAText(targetRev) {
const keyRev = this.getKeyRevisionNumber(targetRev);
// find out which changesets are needed
@ -213,13 +212,13 @@ Pad.prototype.getInternalRevisionAText = async function (targetRev) {
}
return atext;
};
}
Pad.prototype.getRevision = async function (revNum) {
async getRevision(revNum) {
return await this.db.get(`pad:${this.id}:revs:${revNum}`);
};
}
Pad.prototype.getAllAuthorColors = async function () {
async getAllAuthorColors() {
const authorIds = this.getAllAuthors();
const returnTable = {};
const colorPalette = authorManager.getColorPalette();
@ -231,9 +230,9 @@ Pad.prototype.getAllAuthorColors = async function () {
})));
return returnTable;
};
}
Pad.prototype.getValidRevisionRange = function (startRev, endRev) {
getValidRevisionRange(startRev, endRev) {
startRev = parseInt(startRev, 10);
const head = this.getHeadRevisionNumber();
endRev = endRev ? parseInt(endRev, 10) : head;
@ -252,31 +251,31 @@ Pad.prototype.getValidRevisionRange = function (startRev, endRev) {
return {startRev, endRev};
}
return null;
};
}
Pad.prototype.getKeyRevisionNumber = function (revNum) {
getKeyRevisionNumber(revNum) {
return Math.floor(revNum / 100) * 100;
};
}
/**
/**
* @returns {string} The pad's text.
*/
Pad.prototype.text = function () {
text() {
return this.atext.text;
};
}
/**
/**
* Splices text into the pad. If the result of the splice does not end with a newline, one will be
* automatically appended.
*
* @param {number} start - Location in pad text to start removing and inserting characters. Must be
* a non-negative integer less than or equal to `this.text().length`.
* @param {number} ndel - Number of characters to remove starting at `start`. Must be a non-negative
* integer less than or equal to `this.text().length - start`.
* @param {number} start - Location in pad text to start removing and inserting characters. Must
* be a non-negative integer less than or equal to `this.text().length`.
* @param {number} ndel - Number of characters to remove starting at `start`. Must be a
* non-negative integer less than or equal to `this.text().length - start`.
* @param {string} ins - New text to insert at `start` (after the `ndel` characters are deleted).
* @param {string} [authorId] - Author ID of the user making the change (if applicable).
*/
Pad.prototype.spliceText = async function (start, ndel, ins, authorId = '') {
async spliceText(start, ndel, ins, authorId = '') {
if (start < 0) throw new RangeError(`start index must be non-negative (is ${start})`);
if (ndel < 0) throw new RangeError(`characters to delete must be non-negative (is ${ndel})`);
const orig = this.text();
@ -291,71 +290,74 @@ Pad.prototype.spliceText = async function (start, ndel, ins, authorId = '') {
if (ndel === 0 && ins.length === 0) return;
const changeset = Changeset.makeSplice(orig, start, ndel, ins);
await this.appendRevision(changeset, authorId);
};
}
/**
/**
* Replaces the pad's text with new text.
*
* @param {string} newText - The pad's new text. If this string does not end with a newline, one
* will be automatically appended.
* @param {string} [authorId] - The author ID of the user that initiated the change, if applicable.
* @param {string} [authorId] - The author ID of the user that initiated the change, if
* applicable.
*/
Pad.prototype.setText = async function (newText, authorId = '') {
async setText(newText, authorId = '') {
await this.spliceText(0, this.text().length, newText, authorId);
};
}
/**
/**
* Appends text to the pad.
*
* @param {string} newText - Text to insert just BEFORE the pad's existing terminating newline.
* @param {string} [authorId] - The author ID of the user that initiated the change, if applicable.
* @param {string} [authorId] - The author ID of the user that initiated the change, if
* applicable.
*/
Pad.prototype.appendText = async function (newText, authorId = '') {
async appendText(newText, authorId = '') {
await this.spliceText(this.text().length - 1, 0, newText, authorId);
};
}
/**
/**
* Adds a chat message to the pad, including saving it to the database.
*
* @param {(ChatMessage|string)} msgOrText - Either a chat message object (recommended) or a string
* containing the raw text of the user's chat message (deprecated).
* @param {?string} [authorId] - The user's author ID. Deprecated; use `msgOrText.authorId` instead.
* @param {(ChatMessage|string)} msgOrText - Either a chat message object (recommended) or a
* string containing the raw text of the user's chat message (deprecated).
* @param {?string} [authorId] - The user's author ID. Deprecated; use `msgOrText.authorId`
* instead.
* @param {?number} [time] - Message timestamp (milliseconds since epoch). Deprecated; use
* `msgOrText.time` instead.
*/
Pad.prototype.appendChatMessage = async function (msgOrText, authorId = null, time = null) {
async appendChatMessage(msgOrText, authorId = null, time = null) {
const msg =
msgOrText instanceof ChatMessage ? msgOrText : new ChatMessage(msgOrText, authorId, time);
this.chatHead++;
await Promise.all([
// Don't save the display name in the database because the user can change it at any time. The
// `displayName` property will be populated with the current value when the message is read from
// the database.
// `displayName` property will be populated with the current value when the message is read
// from the database.
this.db.set(`pad:${this.id}:chat:${this.chatHead}`, {...msg, displayName: undefined}),
this.saveToDatabase(),
]);
};
}
/**
/**
* @param {number} entryNum - ID of the desired chat message.
* @returns {?ChatMessage}
*/
Pad.prototype.getChatMessage = async function (entryNum) {
async getChatMessage(entryNum) {
const entry = await this.db.get(`pad:${this.id}:chat:${entryNum}`);
if (entry == null) return null;
const message = ChatMessage.fromObject(entry);
message.displayName = await authorManager.getAuthorName(message.authorId);
return message;
};
}
/**
/**
* @param {number} start - ID of the first desired chat message.
* @param {number} end - ID of the last desired chat message.
* @returns {ChatMessage[]} Any existing messages with IDs between `start` (inclusive) and `end`
* (inclusive), in order. Note: `start` and `end` form a closed interval, not a half-open
* interval as is typical in code.
*/
Pad.prototype.getChatMessages = async function (start, end) {
async getChatMessages(start, end) {
const entries = await Promise.all(
[...Array(end + 1 - start).keys()].map((i) => this.getChatMessage(start + i)));
@ -369,9 +371,9 @@ Pad.prototype.getChatMessages = async function (start, end) {
}
return pass;
});
};
}
Pad.prototype.init = async function (text, authorId = '') {
async init(text, authorId = '') {
// try to load the pad
const value = await this.db.get(`pad:${this.id}`);
@ -396,9 +398,9 @@ Pad.prototype.init = async function (text, authorId = '') {
await this.appendRevision(firstChangeset, authorId);
}
await hooks.aCallAll('padLoad', {pad: this});
};
}
Pad.prototype.copy = async function (destinationID, force) {
async copy(destinationID, force) {
// Kick everyone from this pad.
// This was commented due to https://github.com/ether/etherpad-lite/issues/3183.
// Do we really need to kick everyone out?
@ -436,7 +438,8 @@ Pad.prototype.copy = async function (destinationID, force) {
return this.srcPad;
},
get destinationID() {
warnDeprecated('padCopy destinationID context property is deprecated; use dstPad.id instead');
warnDeprecated(
'padCopy destinationID context property is deprecated; use dstPad.id instead');
return this.dstPad.id;
},
srcPad: this,
@ -444,9 +447,9 @@ Pad.prototype.copy = async function (destinationID, force) {
});
return {padID: destinationID};
};
}
Pad.prototype.checkIfGroupExistAndReturnIt = async function (destinationID) {
async checkIfGroupExistAndReturnIt(destinationID) {
let destGroupID = false;
if (destinationID.indexOf('$') >= 0) {
@ -459,9 +462,9 @@ Pad.prototype.checkIfGroupExistAndReturnIt = async function (destinationID) {
}
}
return destGroupID;
};
}
Pad.prototype.removePadIfForceIsTrueAndAlreadyExist = async function (destinationID, force) {
async removePadIfForceIsTrueAndAlreadyExist(destinationID, force) {
// if the pad exists, we should abort, unless forced.
const exists = await padManager.doesPadExist(destinationID);
@ -482,15 +485,15 @@ Pad.prototype.removePadIfForceIsTrueAndAlreadyExist = async function (destinatio
const pad = await padManager.getPad(destinationID);
await pad.remove();
}
};
}
Pad.prototype.copyAuthorInfoToDestinationPad = async function (destinationID) {
async copyAuthorInfoToDestinationPad(destinationID) {
// add the new sourcePad to all authors who contributed to the old one
await Promise.all(this.getAllAuthors().map(
(authorID) => authorManager.addPad(authorID, destinationID)));
};
}
Pad.prototype.copyPadWithoutHistory = async function (destinationID, force, authorId = '') {
async copyPadWithoutHistory(destinationID, force, authorId = '') {
// flush the source pad
this.saveToDatabase();
@ -536,7 +539,8 @@ Pad.prototype.copyPadWithoutHistory = async function (destinationID, force, auth
return this.srcPad;
},
get destinationID() {
warnDeprecated('padCopy destinationID context property is deprecated; use dstPad.id instead');
warnDeprecated(
'padCopy destinationID context property is deprecated; use dstPad.id instead');
return this.dstPad.id;
},
srcPad: this,
@ -544,10 +548,9 @@ Pad.prototype.copyPadWithoutHistory = async function (destinationID, force, auth
});
return {padID: destinationID};
};
}
Pad.prototype.remove = async function () {
async remove() {
const padID = this.id;
const p = [];
@ -603,15 +606,15 @@ Pad.prototype.remove = async function () {
pad: this,
}));
await Promise.all(p);
};
}
// set in db
Pad.prototype.setPublicStatus = async function (publicStatus) {
// set in db
async setPublicStatus(publicStatus) {
this.publicStatus = publicStatus;
await this.saveToDatabase();
};
}
Pad.prototype.addSavedRevision = async function (revNum, savedById, label) {
async addSavedRevision(revNum, savedById, label) {
// if this revision is already saved, return silently
for (const i in this.savedRevisions) {
if (this.savedRevisions[i] && this.savedRevisions[i].revNum === revNum) {
@ -630,16 +633,16 @@ Pad.prototype.addSavedRevision = async function (revNum, savedById, label) {
// save this new saved revision
this.savedRevisions.push(savedRevision);
await this.saveToDatabase();
};
}
Pad.prototype.getSavedRevisions = function () {
getSavedRevisions() {
return this.savedRevisions;
};
}
/**
/**
* Asserts that all pad data is consistent. Throws if inconsistent.
*/
Pad.prototype.check = async function () {
async check() {
assert(this.id != null);
assert.equal(typeof this.id, 'string');
@ -741,4 +744,6 @@ Pad.prototype.check = async function () {
}
await hooks.aCallAll('padCheck', {pad: this});
};
}
}
exports.Pad = Pad;