forked from webaverse/app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchat-manager.js
104 lines (95 loc) · 2.82 KB
/
chat-manager.js
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import {makeId} from './util.js';
import metaversefileApi from 'metaversefile';
const _getEmotion = text => {
let match;
if (match = text.match(/(😃|😊|😁|😄|😆|(?:^|\s)lol(?:$|\s))/)) {
match.emotion = 'joy';
return match;
} else if (match = text.match(/(😉|😜|😂|😍|😎|😏|😇|❤️|💗|💕|💞|💖|👽)/)) {
match.emotion = 'fun';
return match;
} else if (match = text.match(/(😞|😖|😒|😱|😨|😰|😫)/)) {
match.emotion = 'sorrow';
return match;
} else if (match = text.match(/(😠|😡|👿|💥|💢)/)) {
match.emotion = 'angry';
return match;
} else if (match = text.match(/(😐|😲|😶)/)) {
match.emotion = 'neutral';
return match;
} else {
return null;
}
};
class ChatManager extends EventTarget {
constructor() {
super();
// this.messageActions = [];
}
/* getMessageActions() {
return this.messageActions;
} */
addPlayerMessage(player, message = '', {timeout = 3000} = {}) {
const chatId = makeId(5);
const match = _getEmotion(message);
const emotion = match && match.emotion;
const fakeSpeech = match ? (match[1] !== message) : true;
const m = {
type: 'chat',
chatId,
playerName: player.name,
message,
emotion,
fakeSpeech,
};
player.addAction(m);
// this.messageActions.push(m);
this.dispatchEvent(new MessageEvent('messageadd', {
data: {
player,
message: m,
},
}));
const localTimeout = setTimeout(() => {
this.removePlayerMessage(player, m);
}, timeout);
m.cleanup = () => {
clearTimeout(localTimeout);
};
return m;
}
addMessage(message, opts) {
const localPlayer = metaversefileApi.useLocalPlayer();
return this.addPlayerMessage(localPlayer, message, opts);
}
removePlayerMessage(player, m) {
// const index = this.messageActions.indexOf(m);
// if (index !== -1) {
// const m = this.messageActions[index];
m.cleanup();
// this.messageActions.splice(index, 1);
const actionIndex = player.findActionIndex(action => action.chatId === m.chatId);
if (actionIndex !== -1) {
player.removeActionIndex(actionIndex);
} else {
console.warn('remove unknown message action 2', m);
}
this.dispatchEvent(new MessageEvent('messageremove', {
data: {
player,
message: m,
},
}));
/* } else {
console.warn('remove unknown message action 1', m);
} */
}
removeMessage(m) {
const localPlayer = metaversefileApi.useLocalPlayer();
this.removePlayerMessage(localPlayer, m);
}
}
const chatManager = new ChatManager();
export {
chatManager,
};