mami/src/mami.js/messages.js

74 lines
1.9 KiB
JavaScript

#include channels.js
#include server.js
Umi.Messages = (function() {
const msgs = new Map;
const onSend = [],
onAdd = [],
onRemove = [],
onClear = [];
return {
OnSend: onSend,
OnAdd: onAdd,
OnRemove: onRemove,
OnClear: onClear,
Send: function(text) {
Umi.Server.sendMessage(text);
for(const i in onSend)
onSend[i](text);
},
Add: function(msg) {
const msgId = msg.getId();
if(!msgs.has(msgId)) {
msgs.set(msgId, msg);
for(const i in onAdd)
onAdd[i](msg);
if(window.CustomEvent)
window.dispatchEvent(new CustomEvent('umi:message_add', {
detail: msg,
}));
}
},
Remove: function(msg) {
const msgId = msg.getId();
if(msgs.has(msgId)) {
msgs.delete(msgId);
for(const i in onRemove)
onRemove[i](msg);
}
},
Clear: function() {
msgs.clear();
for(const i in onClear)
onClear[i]();
},
All: function(channel, excludeNull) {
if(!channel)
return Array.from(msgs.values());
if(!Umi.Channels.Get(channel))
return null;
const filtered = [];
msgs.forEach(function(msg) {
if(msg.getChannel() === channel || (!excludeNull && msg.getChannel() === null))
filtered.push(msg);
});
return filtered.slice(Math.max(filtered.length - 30, 0));
},
Get: function(msgId) {
msgId = msgId.toString();
if(msgs.has(msgId))
return msgs.get(msgId);
return null;
},
};
})();