-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpadEditor.js
More file actions
69 lines (59 loc) · 2.37 KB
/
padEditor.js
File metadata and controls
69 lines (59 loc) · 2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
'use strict';
const Changeset = require('ep_etherpad-lite/static/js/Changeset');
const padMessageHandler = require('ep_etherpad-lite/node/handler/PadMessageHandler');
const authorManager = require('ep_etherpad-lite/node/db/AuthorManager');
const socketio = require('ep_etherpad-lite/node/hooks/express').socketio;
const log4js = require('ep_etherpad-lite/node_modules/log4js');
const logger = log4js.getLogger('ep_ai_chat:editor');
/**
* Broadcast AI author info to all clients on a pad so the AI
* appears in the user/author list with name and color.
*/
const announceAiAuthor = async (padId, authorId) => {
try {
const authorInfo = await authorManager.getAuthor(authorId);
if (!authorInfo || !socketio) return;
socketio.sockets.in(padId).emit('message', {
type: 'COLLABROOM',
data: {
type: 'USER_NEWINFO',
userInfo: {
colorId: authorInfo.colorId,
name: authorInfo.name,
userId: authorId,
},
},
});
} catch (err) {
logger.warn(`Failed to announce AI author: ${err.message}`);
}
};
const applyEdit = async (pad, edit) => {
const currentText = pad.text();
const authorId = edit.authorId || '';
try {
// Build author attributes so inserted text gets colored
const attribs = authorId ? [['author', authorId]] : undefined;
const pool = authorId ? pad.pool : undefined;
let changeset;
if (edit.appendText) {
const insertPos = currentText.length - 1;
changeset = Changeset.makeSplice(currentText, insertPos, 0, edit.appendText, attribs, pool);
} else if (edit.findText && edit.replaceText !== undefined) {
const idx = currentText.indexOf(edit.findText);
if (idx === -1) return {success: false, error: `Text not found: "${edit.findText.substring(0, 100)}"`};
changeset = Changeset.makeSplice(currentText, idx, edit.findText.length, edit.replaceText, attribs, pool);
} else {
return {success: false, error: 'No valid edit operation specified'};
}
await pad.appendRevision(changeset, authorId);
await padMessageHandler.updatePadClients(pad);
// Announce AI as an author so it appears in the user list
if (authorId) await announceAiAuthor(pad.id, authorId);
return {success: true};
} catch (err) {
logger.error(`Edit failed: ${err.message}`);
return {success: false, error: err.message};
}
};
exports.applyEdit = applyEdit;