apply and fix ESlint

This commit is contained in:
MathMan05 2024-09-02 15:59:56 -05:00
parent f8b80b65fe
commit 19f08a6408
57 changed files with 8070 additions and 7943 deletions

View file

@ -9,7 +9,7 @@ class Voice {
source;
constructor(wave, freq, volume = 1) {
this.audioCtx = new (window.AudioContext)();
this.info = { wave: wave, freq: freq };
this.info = { wave, freq };
this.playing = false;
this.myArrayBuffer = this.audioCtx.createBuffer(1, this.audioCtx.sampleRate, this.audioCtx.sampleRate);
this.gainNode = this.audioCtx.createGain();
@ -43,7 +43,7 @@ class Voice {
}
}
waveFunction() {
if (typeof this.wave === 'function') {
if (typeof this.wave === "function") {
return this.wave;
}
switch (this.wave) {
@ -92,9 +92,15 @@ class Voice {
case "three": {
const voicy = new Voice("sin", 800);
voicy.play();
setTimeout(_ => { voicy.freq = 1000; }, 50);
setTimeout(_ => { voicy.freq = 1300; }, 100);
setTimeout(_ => { voicy.stop(); }, 150);
setTimeout(_ => {
voicy.freq = 1000;
}, 50);
setTimeout(_ => {
voicy.freq = 1300;
}, 100);
setTimeout(_ => {
voicy.stop();
}, 150);
break;
}
case "zip": {
@ -102,23 +108,37 @@ class Voice {
return Math.sin(((t + 2) ** (Math.cos(t * 4))) * Math.PI * 2 * freq);
}, 700);
voicy.play();
setTimeout(_ => { voicy.stop(); }, 150);
setTimeout(_ => {
voicy.stop();
}, 150);
break;
}
case "square": {
const voicy = new Voice("square", 600, .4);
const voicy = new Voice("square", 600, 0.4);
voicy.play();
setTimeout(_ => { voicy.freq = 800; }, 50);
setTimeout(_ => { voicy.freq = 1000; }, 100);
setTimeout(_ => { voicy.stop(); }, 150);
setTimeout(_ => {
voicy.freq = 800;
}, 50);
setTimeout(_ => {
voicy.freq = 1000;
}, 100);
setTimeout(_ => {
voicy.stop();
}, 150);
break;
}
case "beep": {
const voicy = new Voice("sin", 800);
voicy.play();
setTimeout(_ => { voicy.stop(); }, 50);
setTimeout(_ => { voicy.play(); }, 100);
setTimeout(_ => { voicy.stop(); }, 150);
setTimeout(_ => {
voicy.stop();
}, 50);
setTimeout(_ => {
voicy.play();
}, 100);
setTimeout(_ => {
voicy.stop();
}, 150);
break;
}
}
@ -127,13 +147,13 @@ class Voice {
return ["three", "zip", "square", "beep"];
}
static setNotificationSound(sound) {
let userinfos = getBulkInfo();
const userinfos = getBulkInfo();
userinfos.preferences.notisound = sound;
localStorage.setItem("userinfos", JSON.stringify(userinfos));
}
static getNotificationSound() {
let userinfos = getBulkInfo();
const userinfos = getBulkInfo();
return userinfos.preferences.notisound;
}
}
export { Voice as Voice };
export { Voice };

View file

@ -58,10 +58,14 @@ class Channel {
this.contextmenu.addbutton("Delete channel", function () {
console.log(this);
this.deleteChannel();
}, null, function () { return this.isAdmin(); });
}, null, function () {
return this.isAdmin();
});
this.contextmenu.addbutton("Edit channel", function () {
this.editChannel();
}, null, function () { return this.isAdmin(); });
}, null, function () {
return this.isAdmin();
});
this.contextmenu.addbutton("Make invite", function () {
this.createInvite();
}, null, function () {
@ -148,12 +152,11 @@ class Channel {
}
sortPerms() {
this.permission_overwritesar.sort((a, b) => {
const order = this.guild.roles.findIndex(_ => _.snowflake === a[0]) - this.guild.roles.findIndex(_ => _.snowflake === b[0]);
return order;
return this.guild.roles.findIndex(_ => _.snowflake === a[0]) - this.guild.roles.findIndex(_ => _.snowflake === b[0]);
});
}
setUpInfiniteScroller() {
this.infinite = new InfiniteScroller(async function (id, offset) {
this.infinite = new InfiniteScroller((async (id, offset) => {
const snowflake = id;
if (offset === 1) {
if (this.idToPrev.has(snowflake)) {
@ -176,13 +179,12 @@ class Channel {
console.log("at bottom");
}
}
}.bind(this), async function (id) {
}), (async (id) => {
//await new Promise(_=>{setTimeout(_,Math.random()*10)})
const messgage = this.messages.get(id);
try {
if (messgage) {
const html = messgage.buildhtml();
return html;
return messgage.buildhtml();
}
else {
console.error(id + " not found");
@ -191,18 +193,21 @@ class Channel {
catch (e) {
console.error(e);
}
}.bind(this), async function (id) {
return document.createElement("div");
}), (async (id) => {
const message = this.messages.get(id);
try {
if (message) {
message.deleteDiv();
return true;
}
}
catch (e) {
console.error(e);
}
finally { }
}.bind(this), this.readbottom.bind(this));
return false;
}), this.readbottom.bind(this));
}
constructor(json, owner) {
if (json === -1) {
@ -227,7 +232,6 @@ class Channel {
if (thing.id === "1182819038095799904" || thing.id === "1182820803700625444") {
continue;
}
;
this.permission_overwrites.set(thing.id, new Permissions(thing.allow, thing.deny));
const permission = this.permission_overwrites.get(thing.id);
if (permission) {
@ -268,7 +272,7 @@ class Channel {
if (!this.hasPermission("VIEW_CHANNEL")) {
return false;
}
return this.lastmessageid !== this.lastreadmessageid && this.type !== 4 && !!this.lastmessageid;
return this.lastmessageid !== this.lastreadmessageid && this.type !== 4 && Boolean(this.lastmessageid);
}
hasPermission(name, member = this.guild.member) {
if (member.isAdmin()) {
@ -277,7 +281,7 @@ class Channel {
for (const thing of member.roles) {
const premission = this.permission_overwrites.get(thing.id);
if (premission) {
let perm = premission.getPermission(name);
const perm = premission.getPermission(name);
if (perm) {
return perm === 1;
}
@ -289,7 +293,7 @@ class Channel {
return false;
}
get canMessage() {
if ((0 === this.permission_overwritesar.length) && this.hasPermission("MANAGE_CHANNELS")) {
if ((this.permission_overwritesar.length === 0) && this.hasPermission("MANAGE_CHANNELS")) {
const role = this.guild.roles.find(_ => _.name === "@everyone");
if (role) {
this.addRoleToPerms(role);
@ -298,7 +302,9 @@ class Channel {
return this.hasPermission("SEND_MESSAGES");
}
sortchildren() {
this.children.sort((a, b) => { return a.position - b.position; });
this.children.sort((a, b) => {
return a.position - b.position;
});
}
resolveparent(guild) {
const parentid = this.parent_id?.id;
@ -313,7 +319,7 @@ class Channel {
}
calculateReorder() {
let position = -1;
let build = [];
const build = [];
for (const thing of this.children) {
const thisthing = { id: thing.snowflake, position: undefined, parent_id: undefined };
if (thing.position < position) {
@ -348,8 +354,13 @@ class Channel {
}
div["all"] = this;
div.draggable = admin;
div.addEventListener("dragstart", (e) => { Channel.dragged = [this, div]; e.stopImmediatePropagation(); });
div.addEventListener("dragend", () => { Channel.dragged = []; });
div.addEventListener("dragstart", e => {
Channel.dragged = [this, div];
e.stopImmediatePropagation();
});
div.addEventListener("dragend", () => {
Channel.dragged = [];
});
if (this.type === 4) {
this.sortchildren();
const caps = document.createElement("div");
@ -383,17 +394,19 @@ class Channel {
childrendiv.appendChild(channel.createguildHTML(admin));
}
childrendiv.classList.add("channels");
setTimeout(_ => { childrendiv.style.height = childrendiv.scrollHeight + 'px'; }, 100);
setTimeout(_ => {
childrendiv.style.height = childrendiv.scrollHeight + "px";
}, 100);
decdiv.onclick = function () {
if (childrendiv.style.height !== '0px') {
if (childrendiv.style.height !== "0px") {
decoration.classList.add("hiddencat");
//childrendiv.classList.add("colapsediv");
childrendiv.style.height = '0px';
childrendiv.style.height = "0px";
}
else {
decoration.classList.remove("hiddencat");
//childrendiv.classList.remove("colapsediv")
childrendiv.style.height = childrendiv.scrollHeight + 'px';
childrendiv.style.height = childrendiv.scrollHeight + "px";
}
};
div.appendChild(childrendiv);
@ -479,14 +492,14 @@ class Channel {
}
}
coatDropDiv(div, container = false) {
div.addEventListener("dragenter", (event) => {
div.addEventListener("dragenter", event => {
console.log("enter");
event.preventDefault();
});
div.addEventListener("dragover", (event) => {
div.addEventListener("dragover", event => {
event.preventDefault();
});
div.addEventListener("drop", (event) => {
div.addEventListener("drop", event => {
const that = Channel.dragged[0];
if (!that)
return;
@ -543,8 +556,8 @@ class Channel {
method: "POST",
headers: this.headers,
body: JSON.stringify({
name: name,
type: type,
name,
type,
parent_id: this.snowflake,
permission_overwrites: [],
})
@ -558,22 +571,28 @@ class Channel {
const thistype = this.type;
const full = new Dialog(["hdiv",
["vdiv",
["textbox", "Channel name:", this.name, function () { name = this.value; }],
["mdbox", "Channel topic:", this.topic, function () { topic = this.value; }],
["checkbox", "NSFW Channel", this.nsfw, function () { nsfw = this.checked; }],
["textbox", "Channel name:", this.name, function () {
name = this.value;
}],
["mdbox", "Channel topic:", this.topic, function () {
topic = this.value;
}],
["checkbox", "NSFW Channel", this.nsfw, function () {
nsfw = this.checked;
}],
["button", "", "submit", () => {
fetch(this.info.api + "/channels/" + thisid, {
method: "PATCH",
headers: this.headers,
body: JSON.stringify({
"name": name,
"type": thistype,
"topic": topic,
"bitrate": 64000,
"user_limit": 0,
"nsfw": nsfw,
"flags": 0,
"rate_limit_per_user": 0
name,
type: thistype,
topic,
bitrate: 64000,
user_limit: 0,
nsfw,
flags: 0,
rate_limit_per_user: 0
})
});
console.log(full);
@ -683,7 +702,7 @@ class Channel {
for (let i = 0; i < 15; i++) {
const div = document.createElement("div");
div.classList.add("loadingmessage");
if (Math.random() < .5) {
if (Math.random() < 0.5) {
const pfp = document.createElement("div");
pfp.classList.add("loadingpfp");
const username = document.createElement("div");
@ -704,7 +723,6 @@ class Channel {
if (this.allthewayup) {
return;
}
;
if (this.lastreadmessageid && this.messages.has(this.lastreadmessageid)) {
return;
}
@ -715,7 +733,7 @@ class Channel {
if (response.length !== 100) {
this.allthewayup = true;
}
let prev = undefined;
let prev;
for (const thing of response) {
const message = new Message(thing, this);
if (prev) {
@ -747,7 +765,9 @@ class Channel {
}
await fetch(this.info.api + "/channels/" + this.id + "/messages?limit=100&after=" + id, {
headers: this.headers
}).then((j) => { return j.json(); }).then(response => {
}).then(j => {
return j.json();
}).then(response => {
let previd = id;
for (const i in response) {
let messager;
@ -769,7 +789,6 @@ class Channel {
}
//out.buildmessages();
});
return;
}
topid;
async grabBefore(id) {
@ -778,7 +797,9 @@ class Channel {
}
await fetch(this.info.api + "/channels/" + this.id + "/messages?before=" + id + "&limit=100", {
headers: this.headers
}).then((j) => { return j.json(); }).then((response) => {
}).then(j => {
return j.json();
}).then((response) => {
if (response.length < 100) {
this.allthewayup = true;
if (response.length === 0) {
@ -801,7 +822,7 @@ class Channel {
this.idToPrev.set(previd, messager.id);
previd = messager.id;
this.messageids.set(messager.snowflake, messager);
if (+i === response.length - 1 && response.length < 100) {
if (Number(i) === response.length - 1 && response.length < 100) {
this.topid = previd;
}
if (willbreak) {
@ -809,7 +830,6 @@ class Channel {
}
}
});
return;
}
/**
* Please dont use this, its not implemented.
@ -900,7 +920,7 @@ class Channel {
while (flake && time < flaketime) {
flake = this.idToPrev.get(flake);
if (!flake) {
return undefined;
return;
}
flaketime = Number((BigInt(flake) >> 22n) + 1420070400000n);
}
@ -919,7 +939,6 @@ class Channel {
if (thing.id === "1182819038095799904" || thing.id === "1182820803700625444") {
continue;
}
;
this.permission_overwrites.set(thing.id, new Permissions(thing.allow, thing.deny));
const permisions = this.permission_overwrites.get(thing.id);
if (permisions) {
@ -930,10 +949,10 @@ class Channel {
this.nsfw = json.nsfw;
}
typingstart() {
if (this.typing > new Date().getTime()) {
if (this.typing > Date.now()) {
return;
}
this.typing = new Date().getTime() + 6000;
this.typing = Date.now() + 6000;
fetch(this.info.api + "/channels/" + this.snowflake + "/typing", {
method: "POST",
headers: this.headers
@ -941,11 +960,11 @@ class Channel {
}
get notification() {
let notinumber = this.message_notifications;
if (+notinumber === 3) {
if (Number(notinumber) === 3) {
notinumber = null;
}
notinumber ??= this.guild.message_notifications;
switch (+notinumber) {
switch (Number(notinumber)) {
case 0:
return "all";
case 1:
@ -961,15 +980,14 @@ class Channel {
if (replyingto) {
replyjson =
{
"guild_id": replyingto.guild.id,
"channel_id": replyingto.channel.id,
"message_id": replyingto.id,
guild_id: replyingto.guild.id,
channel_id: replyingto.channel.id,
message_id: replyingto.id,
};
}
;
if (attachments.length === 0) {
const body = {
content: content,
content,
nonce: Math.floor(Math.random() * 1000000000),
message_reference: undefined
};
@ -985,21 +1003,21 @@ class Channel {
else {
const formData = new FormData();
const body = {
content: content,
content,
nonce: Math.floor(Math.random() * 1000000000),
message_reference: undefined
};
if (replyjson) {
body.message_reference = replyjson;
}
formData.append('payload_json', JSON.stringify(body));
formData.append("payload_json", JSON.stringify(body));
for (const i in attachments) {
formData.append("files[" + i + "]", attachments[i]);
}
return await fetch(this.info.api + "/channels/" + this.snowflake + "/messages", {
method: 'POST',
method: "POST",
body: formData,
headers: { "Authorization": this.headers.Authorization }
headers: { Authorization: this.headers.Authorization }
});
}
}
@ -1084,7 +1102,6 @@ class Channel {
if (deep === 3) {
return;
}
;
this.notify(message, deep + 1);
});
}
@ -1115,7 +1132,7 @@ class Channel {
body: JSON.stringify({
allow: permission.allow.toString(),
deny: permission.deny.toString(),
id: id,
id,
type: 0
})
});

View file

@ -5,7 +5,7 @@ class Contextmenu {
div;
static setup() {
Contextmenu.currentmenu = "";
document.addEventListener('click', function (event) {
document.addEventListener("click", event => {
if (Contextmenu.currentmenu == "") {
return;
}
@ -50,8 +50,8 @@ class Contextmenu {
if (Contextmenu.currentmenu != "") {
Contextmenu.currentmenu.remove();
}
div.style.top = y + 'px';
div.style.left = x + 'px';
div.style.top = y + "px";
div.style.left = x + "px";
document.body.appendChild(div);
Contextmenu.keepOnScreen(div);
console.log(div);
@ -59,7 +59,7 @@ class Contextmenu {
return this.div;
}
bindContextmenu(obj, addinfo, other) {
const func = (event) => {
const func = event => {
event.preventDefault();
event.stopImmediatePropagation();
this.makemenu(event.clientX, event.clientY, addinfo, other);
@ -75,12 +75,12 @@ class Contextmenu {
console.log(box, docheight, docwidth);
if (box.right > docwidth) {
console.log("test");
obj.style.left = docwidth - box.width + 'px';
obj.style.left = docwidth - box.width + "px";
}
if (box.bottom > docheight) {
obj.style.top = docheight - box.height + 'px';
obj.style.top = docheight - box.height + "px";
}
}
}
Contextmenu.setup();
export { Contextmenu as Contextmenu };
export { Contextmenu };

View file

@ -58,7 +58,7 @@ class Dialog {
case "checkbox":
{
const div = document.createElement("div");
const checkbox = document.createElement('input');
const checkbox = document.createElement("input");
div.appendChild(checkbox);
const label = document.createElement("span");
checkbox.checked = array[2];
@ -71,7 +71,7 @@ class Dialog {
case "button":
{
const div = document.createElement("div");
const input = document.createElement('button');
const input = document.createElement("button");
const label = document.createElement("span");
input.textContent = array[2];
label.textContent = array[1];
@ -134,7 +134,7 @@ class Dialog {
case "radio": {
const div = document.createElement("div");
const fieldset = document.createElement("fieldset");
fieldset.addEventListener("change", function () {
fieldset.addEventListener("change", () => {
let i = -1;
for (const thing of fieldset.children) {
i++;
@ -173,9 +173,8 @@ class Dialog {
div.appendChild(fieldset);
return div;
}
case "html": {
case "html":
return array[1];
}
case "select": {
const div = document.createElement("div");
const label = document.createElement("label");
@ -227,7 +226,6 @@ class Dialog {
}
default:
console.error("can't find element:" + array[0], " full element:" + array);
return;
}
}
show() {
@ -237,7 +235,9 @@ class Dialog {
this.background.classList.add("background");
document.body.appendChild(this.background);
document.body.appendChild(this.html);
this.background.onclick = _ => { this.hide(); };
this.background.onclick = _ => {
this.hide();
};
}
hide() {
document.body.removeChild(this.background);

View file

@ -96,7 +96,6 @@ class Group extends Channel {
this.messageids = new Map();
this.permission_overwrites = new Map();
this.lastmessageid = json.last_message_id;
this.lastmessageid ??= null;
this.mentions = 0;
this.setUpInfiniteScroller();
if (this.lastmessageid) {
@ -140,8 +139,8 @@ class Group extends Channel {
const messagez = new Message(messagep.d, this);
if (this.lastmessageid) {
this.idToNext.set(this.lastmessageid, messagez.id);
}
this.idToPrev.set(messagez.id, this.lastmessageid);
}
this.lastmessageid = messagez.id;
this.messageids.set(messagez.snowflake, messagez);
if (messagez.author === this.localuser.user) {

View file

@ -119,7 +119,6 @@ class Embed {
if (this.json?.timestamp) {
const span = document.createElement("span");
span.textContent = new Date(this.json.timestamp).toLocaleString();
;
footer.append(span);
}
embed.append(footer);

View file

@ -62,10 +62,8 @@ class Emoji {
for (let i = 0; i < length; i++) {
array[i] = read8();
}
const decoded = new TextDecoder("utf-8").decode(array.buffer);
;
//console.log(array);
return decoded;
return new TextDecoder("utf-8").decode(array.buffer);
}
const build = [];
let cats = read16();
@ -78,7 +76,7 @@ class Emoji {
const name = readString8();
const len = read8();
const skin_tone_support = len > 127;
const emoji = readStringNo(len - (+skin_tone_support * 128));
const emoji = readStringNo(len - (Number(skin_tone_support) * 128));
emojis.push({
name,
skin_tone_support,
@ -102,7 +100,9 @@ class Emoji {
}
static async emojiPicker(x, y, localuser) {
let res;
const promise = new Promise((r) => { res = r; });
const promise = new Promise(r => {
res = r;
});
const menu = document.createElement("div");
menu.classList.add("flextttb", "emojiPicker");
menu.style.top = y + "px";

View file

@ -31,7 +31,7 @@ class File {
this.width /= scale;
this.height /= scale;
}
if (this.content_type.startsWith('image/')) {
if (this.content_type.startsWith("image/")) {
const div = document.createElement("div");
const img = document.createElement("img");
img.classList.add("messageimg");
@ -50,7 +50,7 @@ class File {
console.log(this.width, this.height);
return div;
}
else if (this.content_type.startsWith('video/')) {
else if (this.content_type.startsWith("video/")) {
const video = document.createElement("video");
const source = document.createElement("source");
source.src = src;
@ -63,7 +63,7 @@ class File {
}
return video;
}
else if (this.content_type.startsWith('audio/')) {
else if (this.content_type.startsWith("audio/")) {
const audio = document.createElement("audio");
const source = document.createElement("source");
source.src = src;
@ -138,8 +138,8 @@ class File {
return div;
}
static filesizehuman(fsize) {
var i = fsize == 0 ? 0 : Math.floor(Math.log(fsize) / Math.log(1024));
return +((fsize / Math.pow(1024, i)).toFixed(2)) * 1 + ' ' + ['Bytes', 'Kilobytes', 'Megabytes', 'Gigabytes', 'Terabytes'][i];
const i = fsize == 0 ? 0 : Math.floor(Math.log(fsize) / Math.log(1024));
return Number((fsize / Math.pow(1024, i)).toFixed(2)) * 1 + " " + ["Bytes", "Kilobytes", "Megabytes", "Gigabytes", "Terabytes"][i];
}
}
export { File };

View file

@ -149,7 +149,7 @@ class Guild {
method: "PATCH",
headers: this.headers,
body: JSON.stringify({
"message_notifications": noti
message_notifications: noti
})
});
this.message_notifications = noti;
@ -202,7 +202,7 @@ class Guild {
}
calculateReorder() {
let position = -1;
let build = [];
const build = [];
for (const thing of this.headchannels) {
const thisthing = { id: thing.snowflake, position: undefined, parent_id: undefined };
if (thing.position <= position) {
@ -256,7 +256,9 @@ class Guild {
return this.owner.info;
}
sortchannels() {
this.headchannels.sort((a, b) => { return a.position - b.position; });
this.headchannels.sort((a, b) => {
return a.position - b.position;
});
}
generateGuildIcon() {
const divy = document.createElement("div");
@ -279,7 +281,7 @@ class Guild {
}
else {
const div = document.createElement("div");
let build = this.properties.name.replace(/'s /g, " ").replace(/\w+/g, word => word[0]).replace(/\s/g, "");
const build = this.properties.name.replace(/'s /g, " ").replace(/\w+/g, word => word[0]).replace(/\s/g, "");
div.textContent = build;
div.classList.add("blankserver", "servericon");
divy.appendChild(div);
@ -336,7 +338,7 @@ class Guild {
headers: this.headers,
});
}
unreads(html = undefined) {
unreads(html) {
if (html) {
this.html = html;
}
@ -399,7 +401,7 @@ class Guild {
}
return this.member.hasRole(r);
}
loadChannel(ID = undefined) {
loadChannel(ID) {
if (ID && this.channelids[ID]) {
this.channelids[ID].getHTML();
return;
@ -451,7 +453,7 @@ class Guild {
["voice", "text", "announcement"],
function (e) {
console.log(e);
category = { "text": 0, "voice": 2, "announcement": 5, "category": 4 }[e];
category = { text: 0, voice: 2, announcement: 5, category: 4 }[e];
},
1
],
@ -463,12 +465,12 @@ class Guild {
console.log(name, category);
func(name, category);
channelselect.hide();
}.bind(this)]]);
}]]);
channelselect.show();
}
createcategory() {
let name = "";
let category = 4;
const category = 4;
const channelselect = new Dialog(["vdiv",
["textbox", "Name of category", "", function () {
console.log(this);
@ -510,7 +512,7 @@ class Guild {
fetch(this.info.api + "/guilds/" + this.snowflake + "/channels", {
method: "POST",
headers: this.headers,
body: JSON.stringify({ name: name, type: type })
body: JSON.stringify({ name, type })
});
}
async createRole(name) {
@ -518,7 +520,7 @@ class Guild {
method: "POST",
headers: this.headers,
body: JSON.stringify({
name: name,
name,
color: 0,
permissions: "0"
})

View file

@ -33,7 +33,7 @@ fetch("/instances.json").then(_ => _.json()).then((json) => {
if (instance.descriptionLong) {
p.innerText = instance.descriptionLong;
}
else {
else if (instance.description) {
p.innerText = instance.description;
}
textbox.append(p);

View file

@ -6,8 +6,10 @@ import { File } from "./file.js";
(async () => {
async function waitforload() {
let res;
new Promise(r => { res = r; });
document.addEventListener("DOMContentLoaded", function () {
new Promise(r => {
res = r;
});
document.addEventListener("DOMContentLoaded", () => {
res();
});
await res;
@ -15,7 +17,7 @@ import { File } from "./file.js";
await waitforload();
const users = getBulkUsers();
if (!users.currentuser) {
window.location.href = '/login.html';
window.location.href = "/login.html";
}
function showAccountSwitcher() {
const table = document.createElement("div");
@ -45,7 +47,7 @@ import { File } from "./file.js";
loading.classList.remove("doneloading");
loading.classList.add("loading");
thisuser = new Localuser(specialuser);
users["currentuser"] = specialuser.uid;
users.currentuser = specialuser.uid;
localStorage.setItem("userinfos", JSON.stringify(users));
thisuser.initwebsocket().then(_ => {
thisuser.loaduser();
@ -107,16 +109,20 @@ import { File } from "./file.js";
}
{
const menu = new Contextmenu("create rightclick"); //Really should go into the localuser class, but that's a later thing
menu.addbutton("Create channel", function () {
menu.addbutton("Create channel", () => {
if (thisuser.lookingguild) {
thisuser.lookingguild.createchannels();
}
}, null, _ => { return thisuser.isAdmin(); });
menu.addbutton("Create category", function () {
}, null, _ => {
return thisuser.isAdmin();
});
menu.addbutton("Create category", () => {
if (thisuser.lookingguild) {
thisuser.lookingguild.createcategory();
}
}, null, _ => { return thisuser.isAdmin(); });
}, null, _ => {
return thisuser.isAdmin();
});
menu.bindContextmenu(document.getElementById("channels"), 0, 0);
}
const pasteimage = document.getElementById("pasteimage");
@ -134,7 +140,7 @@ import { File } from "./file.js";
}
else {
replyingto = thisuser.channelfocus.replyingto;
let replying = replyingto;
const replying = replyingto;
if (replyingto?.div) {
replyingto.div.classList.remove("replying");
}
@ -151,7 +157,6 @@ import { File } from "./file.js";
pasteimage.removeChild(imageshtml.pop());
}
typebox.innerHTML = "";
return;
}
}
const typebox = document.getElementById("typebox");
@ -174,7 +179,7 @@ import { File } from "./file.js";
*/
const images = [];
const imageshtml = [];
document.addEventListener('paste', async (e) => {
document.addEventListener("paste", async (e) => {
if (!e.clipboardData)
return;
Array.from(e.clipboardData.files).forEach(async (f) => {

View file

@ -32,7 +32,7 @@ class InfiniteScroller {
this.watchForChange();
});
this.scroll.addEventListener("scroll", _ => {
if (null === this.timeout) {
if (this.timeout === null) {
this.timeout = setTimeout(this.updatestuff.bind(this), 300);
}
this.watchForChange();
@ -71,11 +71,9 @@ class InfiniteScroller {
this.averageheight = 60;
}
this.scrollTop = this.scroll.scrollTop;
if (!this.scrollBottom) {
if (!await this.watchForChange()) {
if (!this.scrollBottom && !await this.watchForChange()) {
this.reachesBottom();
}
}
if (!this.scrollTop) {
await this.watchForChange();
}
@ -129,7 +127,6 @@ class InfiniteScroller {
this.HTMLElements.unshift([html, nextid]);
this.scrollTop += this.averageheight;
}
;
}
if (this.scrollTop > this.maxDist) {
const html = this.HTMLElements.shift();
@ -176,7 +173,6 @@ class InfiniteScroller {
this.HTMLElements.push([html, nextid]);
this.scrollBottom += this.averageheight;
}
;
}
if (scrollBottom > this.maxDist) {
const html = this.HTMLElements.pop();
@ -225,14 +221,14 @@ class InfiniteScroller {
}
const out = await Promise.allSettled([this.watchForTop(), this.watchForBottom()]);
const changed = (out[0].value || out[1].value);
if (null === this.timeout && changed) {
if (this.timeout === null && changed) {
this.timeout = setTimeout(this.updatestuff.bind(this), 300);
}
if (!this.currrunning) {
console.error("something really bad happened");
}
res(!!changed);
return !!changed;
res(Boolean(changed));
return Boolean(changed);
}
catch (e) {
console.error(e);

View file

@ -11,7 +11,7 @@ import { getBulkUsers, getapiurls } from "./login.js";
console.log(users.users[thing]);
}
let urls;
if (!joinable.length) {
if (!joinable.length && well) {
const out = await getapiurls(well);
if (out) {
urls = out;
@ -24,7 +24,7 @@ import { getBulkUsers, getapiurls } from "./login.js";
}
}
else {
throw Error("someone needs to handle the case where the servers don't exist");
throw new Error("someone needs to handle the case where the servers don't exist");
}
}
else {
@ -86,7 +86,7 @@ import { getBulkUsers, getapiurls } from "./login.js";
Authorization: thing.token
}
}).then(_ => {
users["currentuser"] = specialuser.uid;
users.currentuser = specialuser.uid;
localStorage.setItem("userinfos", JSON.stringify(users));
window.location.href = "/channels/" + guildinfo.id;
});

View file

@ -22,13 +22,13 @@ function trimswitcher() {
for (const thing in json.users) {
const user = json.users[thing];
let wellknown = user.serverurls.wellknown;
if (wellknown[wellknown.length - 1] !== "/") {
if (wellknown.at(-1) !== "/") {
wellknown += "/";
}
wellknown += user.username;
if (map.has(wellknown)) {
const otheruser = map.get(wellknown);
if (otheruser[1].serverurls.wellknown[otheruser[1].serverurls.wellknown.length - 1] === "/") {
if (otheruser[1].serverurls.wellknown.at(-1) === "/") {
delete json.users[otheruser[0]];
map.set(wellknown, [thing, user]);
}
@ -41,7 +41,7 @@ function trimswitcher() {
}
}
for (const thing in json.users) {
if (thing[thing.length - 1] === "/") {
if (thing.at(-1) === "/") {
const user = json.users[thing];
delete json.users[thing];
json.users[thing.slice(0, -1)] = user;
@ -73,7 +73,7 @@ function setDefaults() {
if (userinfos.accent_color === undefined) {
userinfos.accent_color = "#242443";
}
document.documentElement.style.setProperty('--accent-color', userinfos.accent_color);
document.documentElement.style.setProperty("--accent-color", userinfos.accent_color);
if (userinfos.preferences === undefined) {
userinfos.preferences = {
theme: "Dark",
@ -103,11 +103,8 @@ class Specialuser {
this.serverurls.api = apistring;
this.serverurls.cdn = new URL(json.serverurls.cdn).toString().replace(/\/$/, "");
this.serverurls.gateway = new URL(json.serverurls.gateway).toString().replace(/\/$/, "");
;
this.serverurls.wellknown = new URL(json.serverurls.wellknown).toString().replace(/\/$/, "");
;
this.serverurls.login = new URL(json.serverurls.login).toString().replace(/\/$/, "");
;
this.email = json.email;
this.token = json.token;
this.loggedin = json.loggedin;
@ -178,12 +175,12 @@ async function getapiurls(str) {
}
}
}
if (str[str.length - 1] !== "/") {
if (str.at(-1) !== "/") {
str += "/";
}
let api;
try {
const info = await fetch(`${str}/.well-known/spacebar`).then((x) => x.json());
const info = await fetch(`${str}/.well-known/spacebar`).then(x => x.json());
api = info.api;
}
catch {
@ -191,7 +188,7 @@ async function getapiurls(str) {
}
const url = new URL(api);
try {
const info = await fetch(`${api}${url.pathname.includes("api") ? "" : "api"}/policies/instance/domains`).then((x) => x.json());
const info = await fetch(`${api}${url.pathname.includes("api") ? "" : "api"}/policies/instance/domains`).then(x => x.json());
return {
api: info.apiEndpoint,
gateway: info.gateway,
@ -226,8 +223,8 @@ async function checkInstance(e) {
instanceinfo.value = instancein.value;
localStorage.setItem("instanceinfo", JSON.stringify(instanceinfo));
verify.textContent = "Instance is all good";
if (checkInstance["alt"]) {
checkInstance["alt"]();
if (checkInstance.alt) {
checkInstance.alt();
}
setTimeout(_ => {
console.log(verify.textContent);
@ -238,7 +235,7 @@ async function checkInstance(e) {
verify.textContent = "Invalid Instance, try again";
}
}
catch (e) {
catch {
console.log("catch");
verify.textContent = "Invalid Instance, try again";
}
@ -271,10 +268,10 @@ async function login(username, password, captcha) {
const options = {
method: "POST",
body: JSON.stringify({
"login": username,
"password": password,
"undelete": false,
"captcha_key": captcha
login: username,
password,
undelete: false,
captcha_key: captcha
}),
headers: {
"Content-type": "application/json; charset=UTF-8",
@ -283,10 +280,10 @@ async function login(username, password, captcha) {
try {
const info = JSON.parse(localStorage.getItem("instanceinfo"));
const api = info.login + (info.login.startsWith("/") ? "/" : "");
return await fetch(api + '/auth/login', options).then(response => response.json())
.then((response) => {
return await fetch(api + "/auth/login", options).then(response => response.json())
.then(response => {
console.log(response, response.message);
if ("Invalid Form Body" === response.message) {
if (response.message === "Invalid Form Body") {
return response.errors.login._errors[0].message;
console.log("test");
}
@ -306,13 +303,14 @@ async function login(username, password, captcha) {
else {
eval("hcaptcha.reset()");
}
return;
}
else {
console.log(response);
if (response.ticket) {
let onetimecode = "";
new Dialog(["vdiv", ["title", "2FA code:"], ["textbox", "", "", function () { onetimecode = this.value; }], ["button", "", "Submit", function () {
new Dialog(["vdiv", ["title", "2FA code:"], ["textbox", "", "", function () {
onetimecode = this.value;
}], ["button", "", "Submit", function () {
fetch(api + "/auth/mfa/totp", {
method: "POST",
headers: {
@ -336,7 +334,7 @@ async function login(username, password, captcha) {
window.location.href = redir;
}
else {
window.location.href = '/channels/@me';
window.location.href = "/channels/@me";
}
}
});
@ -352,7 +350,7 @@ async function login(username, password, captcha) {
window.location.href = redir;
}
else {
window.location.href = '/channels/@me';
window.location.href = "/channels/@me";
}
return "";
}
@ -360,13 +358,12 @@ async function login(username, password, captcha) {
});
}
catch (error) {
console.error('Error:', error);
console.error("Error:", error);
}
;
}
async function check(e) {
e.preventDefault();
let h = await login(e.srcElement[1].value, e.srcElement[2].value, e.srcElement[3].value);
const h = await login(e.srcElement[1].value, e.srcElement[2].value, e.srcElement[3].value);
document.getElementById("wrong").textContent = h;
console.log(h);
}

View file

@ -28,7 +28,7 @@ class MarkDown {
return this.makeHTML().textContent;
}
makeHTML({ keep = this.keep, stdsize = this.stdsize } = {}) {
return this.markdown(this.txt, { keep: keep, stdsize: stdsize });
return this.markdown(this.txt, { keep, stdsize });
}
markdown(text, { keep = false, stdsize = false } = {}) {
let txt;
@ -105,7 +105,7 @@ class MarkDown {
if (keep) {
element.append(keepys);
}
element.appendChild(this.markdown(build, { keep: keep, stdsize: stdsize }));
element.appendChild(this.markdown(build, { keep, stdsize }));
span.append(element);
}
finally {
@ -179,7 +179,7 @@ class MarkDown {
}
else {
const pre = document.createElement("pre");
if (build[build.length - 1] === "\n") {
if (build.at(-1) === "\n") {
build = build.substring(0, build.length - 1);
}
if (txt[i] === "\n") {
@ -224,7 +224,7 @@ class MarkDown {
if (keep) {
i.append(stars);
}
i.appendChild(this.markdown(build, { keep: keep, stdsize: stdsize }));
i.appendChild(this.markdown(build, { keep, stdsize }));
if (keep) {
i.append(stars);
}
@ -235,7 +235,7 @@ class MarkDown {
if (keep) {
b.append(stars);
}
b.appendChild(this.markdown(build, { keep: keep, stdsize: stdsize }));
b.appendChild(this.markdown(build, { keep, stdsize }));
if (keep) {
b.append(stars);
}
@ -247,7 +247,7 @@ class MarkDown {
if (keep) {
b.append(stars);
}
b.appendChild(this.markdown(build, { keep: keep, stdsize: stdsize }));
b.appendChild(this.markdown(build, { keep, stdsize }));
if (keep) {
b.append(stars);
}
@ -290,7 +290,7 @@ class MarkDown {
if (keep) {
i.append(underscores);
}
i.appendChild(this.markdown(build, { keep: keep, stdsize: stdsize }));
i.appendChild(this.markdown(build, { keep, stdsize }));
if (keep) {
i.append(underscores);
}
@ -301,7 +301,7 @@ class MarkDown {
if (keep) {
u.append(underscores);
}
u.appendChild(this.markdown(build, { keep: keep, stdsize: stdsize }));
u.appendChild(this.markdown(build, { keep, stdsize }));
if (keep) {
u.append(underscores);
}
@ -313,7 +313,7 @@ class MarkDown {
if (keep) {
i.append(underscores);
}
i.appendChild(this.markdown(build, { keep: keep, stdsize: stdsize }));
i.appendChild(this.markdown(build, { keep, stdsize }));
if (keep) {
i.append(underscores);
}
@ -325,7 +325,7 @@ class MarkDown {
}
}
if (txt[i] === "~" && txt[i + 1] === "~") {
let count = 2;
const count = 2;
let build = [];
let find = 0;
let j = i + 2;
@ -350,7 +350,7 @@ class MarkDown {
if (keep) {
s.append(tildes);
}
s.appendChild(this.markdown(build, { keep: keep, stdsize: stdsize }));
s.appendChild(this.markdown(build, { keep, stdsize }));
if (keep) {
s.append(tildes);
}
@ -360,7 +360,7 @@ class MarkDown {
}
}
if (txt[i] === "|" && txt[i + 1] === "|") {
let count = 2;
const count = 2;
let build = [];
let find = 0;
let j = i + 2;
@ -385,7 +385,7 @@ class MarkDown {
if (keep) {
j.append(pipes);
}
j.appendChild(this.markdown(build, { keep: keep, stdsize: stdsize }));
j.appendChild(this.markdown(build, { keep, stdsize }));
j.classList.add("spoiler");
j.onclick = MarkDown.unspoil;
if (keep) {
@ -459,7 +459,7 @@ class MarkDown {
i = j;
const isEmojiOnly = txt.join("").trim() === buildjoin.trim();
const owner = (this.owner instanceof Channel) ? this.owner.guild : this.owner;
const emoji = new Emoji({ name: buildjoin, id: parts[2], animated: !!parts[1] }, owner);
const emoji = new Emoji({ name: buildjoin, id: parts[2], animated: Boolean(parts[1]) }, owner);
span.appendChild(emoji.getHTML(isEmojiOnly));
continue;
}
@ -479,7 +479,6 @@ class MarkDown {
else {
break;
}
;
}
else if (partsFound === 1 && txt[j] === ")") {
partsFound++;
@ -529,7 +528,7 @@ class MarkDown {
return;
console.log(_.clipboardData.types);
const data = _.clipboardData.getData("text");
document.execCommand('insertHTML', false, data);
document.execCommand("insertHTML", false, data);
_.preventDefault();
if (!box.onkeyup)
return;
@ -568,25 +567,25 @@ class MarkDown {
}
//solution from https://stackoverflow.com/questions/4576694/saving-and-restoring-caret-position-for-contenteditable-div
function saveCaretPosition(context) {
var selection = window.getSelection();
const selection = window.getSelection();
if (!selection)
return;
var range = selection.getRangeAt(0);
const range = selection.getRangeAt(0);
range.setStart(context, 0);
var len = range.toString().length;
const len = range.toString().length;
return function restore() {
if (!selection)
return;
var pos = getTextNodeAtPosition(context, len);
const pos = getTextNodeAtPosition(context, len);
selection.removeAllRanges();
var range = new Range();
const range = new Range();
range.setStart(pos.node, pos.position);
selection.addRange(range);
};
}
function getTextNodeAtPosition(root, index) {
const NODE_TYPE = NodeFilter.SHOW_TEXT;
var treeWalker = document.createTreeWalker(root, NODE_TYPE, function next(elem) {
const treeWalker = document.createTreeWalker(root, NODE_TYPE, elem => {
if (!elem.textContent)
return 0;
if (index > elem.textContent.length) {
@ -595,7 +594,7 @@ function getTextNodeAtPosition(root, index) {
}
return NodeFilter.FILTER_ACCEPT;
});
var c = treeWalker.nextNode();
const c = treeWalker.nextNode();
return {
node: c ? c : root,
position: index

View file

@ -28,7 +28,7 @@ class Member {
continue;
}
if (thing === "roles") {
for (const strrole of memberjson["roles"]) {
for (const strrole of memberjson.roles) {
const role = SnowFlake.getSnowFlakeFromID(strrole, Role).getObject();
this.roles.push(role);
}
@ -38,7 +38,6 @@ class Member {
}
if (this.localuser.userMap.has(this?.id)) {
this.user = this.localuser.userMap.get(this?.id);
return;
}
}
get guild() {
@ -89,7 +88,6 @@ class Member {
const membjson = await membpromise;
if (membjson === undefined) {
res(undefined);
return undefined;
}
else {
const member = new Member(membjson, guild);
@ -149,7 +147,6 @@ class Member {
if (!this) {
return;
}
;
/*
if(this.error){

View file

@ -42,7 +42,9 @@ class Message {
return this.snowflake.id;
}
static setup() {
this.del = new Promise(_ => { this.resolve = _; });
this.del = new Promise(_ => {
this.resolve = _;
});
Message.setupcmenu();
}
static setupcmenu() {
@ -63,7 +65,7 @@ class Message {
Message.contextmenu.addbutton("Edit", function () {
this.channel.editing = this;
const markdown = document.getElementById("typebox")["markdown"];
markdown.txt = this.content.rawString.split('');
markdown.txt = this.content.rawString.split("");
markdown.boxupdate(document.getElementById("typebox"));
}, null, function () {
return this.author.id === this.localuser.user.id;
@ -199,7 +201,7 @@ class Message {
getimages() {
const build = [];
for (const thing of this.attachments) {
if (thing.content_type.startsWith('image/')) {
if (thing.content_type.startsWith("image/")) {
build.push(thing);
}
}
@ -209,7 +211,7 @@ class Message {
return await fetch(this.info.api + "/channels/" + this.channel.snowflake + "/messages/" + this.id, {
method: "PATCH",
headers: this.headers,
body: JSON.stringify({ content: content })
body: JSON.stringify({ content })
});
}
delete() {
@ -266,7 +268,7 @@ class Message {
this.generateMessage();
}
}
generateMessage(premessage = undefined, ignoredblock = false) {
generateMessage(premessage, ignoredblock = false) {
if (!this.div)
return;
if (!premessage) {
@ -277,21 +279,21 @@ class Message {
div.classList.add("replying");
}
div.innerHTML = "";
const build = document.createElement('div');
const build = document.createElement("div");
build.classList.add("flexltr", "message");
div.classList.remove("zeroheight");
if (this.author.relationshipType === 2) {
if (ignoredblock) {
if (premessage?.author !== this.author) {
const span = document.createElement("span");
span.textContent = `You have this user blocked, click to hide these messages.`;
span.textContent = "You have this user blocked, click to hide these messages.";
div.append(span);
span.classList.add("blocked");
span.onclick = _ => {
const scroll = this.channel.infinite.scrollTop;
let next = this;
while (next?.author === this.author) {
next.generateMessage(undefined);
next.generateMessage();
next = this.channel.messages.get(this.channel.idToNext.get(next.id));
}
if (this.channel.infinite.scroll && scroll) {
@ -375,7 +377,7 @@ class Message {
}
div.appendChild(build);
if ({ 0: true, 19: true }[this.type] || this.attachments.length !== 0) {
const pfpRow = document.createElement('div');
const pfpRow = document.createElement("div");
pfpRow.classList.add("flexltr");
let pfpparent, current;
if (premessage != null) {
@ -545,7 +547,7 @@ class Message {
if (thing.emoji.name === data.name) {
thing.count--;
if (thing.count === 0) {
this.reactions.splice(+i, 1);
this.reactions.splice(Number(i), 1);
this.updateReactions();
return;
}
@ -565,16 +567,16 @@ class Message {
for (const i in this.reactions) {
const reaction = this.reactions[i];
if ((reaction.emoji.id && reaction.emoji.id == emoji.id) || (!reaction.emoji.id && reaction.emoji.name == emoji.name)) {
this.reactions.splice(+i, 1);
this.reactions.splice(Number(i), 1);
this.updateReactions();
break;
}
}
}
buildhtml(premessage = undefined) {
buildhtml(premessage) {
if (this.div) {
console.error(`HTML for ${this.snowflake} already exists, aborting`);
return;
return this.div;
}
try {
const div = document.createElement("div");
@ -585,15 +587,16 @@ class Message {
catch (e) {
console.error(e);
}
return this.div;
}
}
let now = new Date().toLocaleDateString();
const now = new Date().toLocaleDateString();
const yesterday = new Date(now);
yesterday.setDate(new Date().getDate() - 1);
let yesterdayStr = yesterday.toLocaleDateString();
const yesterdayStr = yesterday.toLocaleDateString();
function formatTime(date) {
const datestring = date.toLocaleDateString();
const formatTime = (date) => date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
const formatTime = (date) => date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
if (datestring === now) {
return `Today at ${formatTime(date)}`;
}

View file

@ -3,12 +3,12 @@ class Permissions {
deny;
hasDeny;
constructor(allow, deny = "") {
this.hasDeny = !!deny;
this.hasDeny = Boolean(deny);
try {
this.allow = BigInt(allow);
this.deny = BigInt(deny);
}
catch (e) {
catch {
this.allow = 0n;
this.deny = 0n;
console.error(`Something really stupid happened with a permission with allow being ${allow} and deny being, ${deny}, execution will still happen, but something really stupid happened, please report if you know what caused this.`);

View file

@ -17,9 +17,9 @@ async function registertry(e) {
await fetch(apiurl + "/auth/register", {
body: JSON.stringify({
date_of_birth: dateofbirth,
email: email,
username: username,
password: password,
email,
username,
password,
consent: elements[6].checked,
captcha_key: elements[7]?.value
}),
@ -67,14 +67,14 @@ async function registertry(e) {
}
}
else {
adduser({ serverurls: JSON.parse(localStorage.getItem("instanceinfo")), email: email, token: e.token }).username = username;
adduser({ serverurls: JSON.parse(localStorage.getItem("instanceinfo")), email, token: e.token }).username = username;
localStorage.setItem("token", e.token);
const redir = new URLSearchParams(window.location.search).get("goback");
if (redir) {
window.location.href = redir;
}
else {
window.location.href = '/channels/@me';
window.location.href = "/channels/@me";
}
}
});
@ -93,7 +93,9 @@ function error(e, message) {
}
else {
element.classList.remove("suberror");
setTimeout(_ => { element.classList.add("suberror"); }, 100);
setTimeout(_ => {
element.classList.add("suberror");
}, 100);
}
element.textContent = message;
}

View file

@ -38,7 +38,6 @@ class Role {
if (this.color === 0) {
return null;
}
;
return `#${this.color.toString(16)}`;
}
}
@ -55,7 +54,6 @@ class PermissionToggle {
this.owner = owner;
}
watchForChange() { }
;
generateHTML() {
const div = document.createElement("div");
div.classList.add("setting");
@ -80,7 +78,6 @@ class PermissionToggle {
if (state === 1) {
on.checked = true;
}
;
on.onclick = _ => {
this.permissions.setPermission(this.rolejson.name, 1);
this.owner.changed();
@ -92,7 +89,6 @@ class PermissionToggle {
if (state === 0) {
no.checked = true;
}
;
no.onclick = _ => {
this.permissions.setPermission(this.rolejson.name, 0);
this.owner.changed();
@ -105,7 +101,6 @@ class PermissionToggle {
if (state === -1) {
off.checked = true;
}
;
off.onclick = _ => {
this.permissions.setPermission(this.rolejson.name, -1);
this.owner.changed();

View file

@ -4,7 +4,7 @@ function deleteoldcache() {
}
async function putInCache(request, response) {
console.log(request, response);
const cache = await caches.open('cache');
const cache = await caches.open("cache");
console.log("Grabbed");
try {
console.log(await cache.put(request, response));
@ -13,7 +13,6 @@ async function putInCache(request, response) {
console.error(error);
}
}
;
console.log("test");
let lastcache;
self.addEventListener("activate", async (event) => {
@ -37,7 +36,9 @@ async function checkCache() {
putInCache("/getupdates", data.clone());
}
checkedrecently = true;
setTimeout(_ => { checkedrecently = false; }, 1000 * 60 * 30);
setTimeout(_ => {
checkedrecently = false;
}, 1000 * 60 * 30);
});
}
var checkedrecently = false;
@ -83,7 +84,7 @@ async function getfile(event) {
console.error(e);
}
}
self.addEventListener('fetch', (event) => {
self.addEventListener("fetch", (event) => {
try {
event.respondWith(getfile(event));
}

View file

@ -9,7 +9,7 @@ class Buttons {
this.buttons = [];
this.name = name;
}
add(name, thing = undefined) {
add(name, thing) {
if (!thing) {
thing = new Options(name, this);
}
@ -380,7 +380,6 @@ class FileInput {
if (this.onchange) {
this.onchange(null);
}
;
this.value = null;
this.owner.changed();
};
@ -424,7 +423,6 @@ class HtmlArea {
}
}
watchForChange() { }
;
}
class Options {
name;
@ -451,7 +449,6 @@ class Options {
}
}
watchForChange() { }
;
addOptions(name, { ltr = false } = {}) {
const options = new Options(name, this, { ltr });
this.options.push(options);
@ -467,7 +464,7 @@ class Options {
this.generateContainter();
}
else {
throw Error("Tried to make a subOptions when the options weren't rendered");
throw new Error("Tried to make a subOptions when the options weren't rendered");
}
return options;
}
@ -479,7 +476,7 @@ class Options {
this.generateContainter();
}
else {
throw Error("Tried to make a subForm when the options weren't rendered");
throw new Error("Tried to make a subForm when the options weren't rendered");
}
return options;
}
@ -758,7 +755,6 @@ class Form {
watchForChange(func) {
this.onSubmit = func;
}
;
changed() {
if (this.traditionalSubmit) {
this.owner.changed();
@ -819,7 +815,6 @@ class Form {
if (!(errors instanceof Object)) {
return;
}
;
for (const error of Object.keys(errors)) {
const elm = this.names.get(error);
if (elm) {
@ -858,7 +853,9 @@ class Form {
}
else {
element.classList.remove("suberror");
setTimeout(_ => { element.classList.add("suberror"); }, 100);
setTimeout(_ => {
element.classList.add("suberror");
}, 100);
}
element.textContent = message;
}
@ -887,7 +884,9 @@ class Settings extends Buttons {
exit.textContent = "✖";
exit.classList.add("exitsettings");
background.append(exit);
exit.onclick = _ => { this.hide(); };
exit.onclick = _ => {
this.hide();
};
document.body.append(background);
this.html = background;
}

View file

@ -72,7 +72,7 @@ class User {
});
this.contextmenu.addbutton("Message user", function () {
fetch(this.info.api + "/users/@me/channels", { method: "POST",
body: JSON.stringify({ "recipients": [this.id] }),
body: JSON.stringify({ recipients: [this.id] }),
headers: this.localuser.headers
});
});
@ -97,7 +97,7 @@ class User {
});
this.contextmenu.addbutton("Kick member", function (member) {
member.kick();
}, null, function (member) {
}, null, member => {
if (!member)
return false;
const us = member.guild.member;
@ -111,7 +111,7 @@ class User {
});
this.contextmenu.addbutton("Ban member", function (member) {
member.ban();
}, null, function (member) {
}, null, member => {
if (!member)
return false;
const us = member.guild.member;
@ -192,7 +192,7 @@ class User {
}
}
buildpfp() {
const pfp = document.createElement('img');
const pfp = document.createElement("img");
pfp.loading = "lazy";
pfp.src = this.getpfpsrc();
pfp.classList.add("pfp");
@ -419,7 +419,7 @@ class User {
}
return div;
}
profileclick(obj, guild = undefined) {
profileclick(obj, guild) {
obj.onclick = e => {
this.buildprofile(e.clientX, e.clientY, guild);
e.stopPropagation();

View file

@ -45,7 +45,7 @@ for(const thing of emojilist){
}
const out=new ArrayBuffer(i);
const ar=new Uint8Array(out);
const br=new Uint8Array(buffer)
const br=new Uint8Array(buffer);
for(const thing in ar){
ar[thing]=br[thing];
}
@ -76,10 +76,8 @@ function decodeEmojiList(buffer){
for(let i=0;i<length;i++){
array[i]=read8();
}
const decoded=new TextDecoder("utf-8").decode(array.buffer);;
//console.log(array);
return decoded;
return new TextDecoder("utf-8").decode(array.buffer);
}
const build=[];
let cats=read16();
@ -98,18 +96,18 @@ function decodeEmojiList(buffer){
name,
skin_tone_support,
emoji
})
});
}
build.push({
name,
emojis
})
});
}
return build;
}
console.log(JSON.stringify(decodeEmojiList(out)));
const fs = require('fs');
const fs = require("node:fs");
fs.writeFile("./webpage/emoji.bin",new Uint8Array(out),_=>{
});

View file

@ -10,10 +10,10 @@ const tsParser = require("@typescript-eslint/parser");
const linterOptions = {
reportUnusedDisableDirectives: "error"
}
};
const global = {
...globals.browser
}
};
const rules = {
"array-callback-return": 2,
@ -227,7 +227,7 @@ const rules = {
"sonarjs/prefer-while": 2,
"sonarjs/no-gratuitous-expressions": 2,
"sonarjs/no-duplicated-branches": 2
}
};
module.exports = [
{
@ -307,4 +307,4 @@ module.exports = [
"@html-eslint/require-img-alt": 1
}
}
]
];

View file

@ -1,8 +1,8 @@
#! /usr/bin/env node
const compression = require('compression')
const compression = require("compression");
const express = require('express');
const fs = require('fs');
const express = require("express");
const fs = require("node:fs");
const app = express();
const instances=require("./webpage/instances.json");
const stats=require("./stats.js");
@ -10,13 +10,13 @@ const instancenames=new Map();
for(const instance of instances){
instancenames.set(instance.name,instance);
}
app.use(compression())
app.use(compression());
fetch("https://raw.githubusercontent.com/spacebarchat/spacebarchat/master/instances/instances.json").then(_=>_.json()).then(json=>{
for(const instance of json){
if(!instancenames.has(instance.name)){
instances.push(instance);
}else{
const ofinst=instancenames.get(instance.name)
const ofinst=instancenames.get(instance.name);
for(const key of Object.keys(instance)){
if(!ofinst[key]){
ofinst[key]=instance[key];
@ -24,32 +24,31 @@ fetch("https://raw.githubusercontent.com/spacebarchat/spacebarchat/master/instan
}
}
}
stats.observe(instances)
})
stats.observe(instances);
});
app.use("/getupdates",(req, res)=>{
const out=fs.statSync(`${__dirname}/webpage`);
res.send(out.mtimeMs+"");
});
let debugging=true;//Do not turn this off, the service worker is all kinds of jank as is, it'll really mess your day up if you disable this
const debugging=true;//Do not turn this off, the service worker is all kinds of jank as is, it'll really mess your day up if you disable this
function isembed(str){
return str.includes("discord")||str.includes("Spacebar");
}
async function getapiurls(str){
if(str[str.length-1]!=="/"){
str+="/"
if(str.at(-1)!=="/"){
str+="/";
}
let api;
try{
const info=await fetch(`${str}/.well-known/spacebar`).then((x) => x.json());
const info=await fetch(`${str}/.well-known/spacebar`).then(x=>x.json());
api=info.api;
}catch{
return false
return false;
}
const url = new URL(api);
try{
const info=await fetch(`${api}${url.pathname.includes("api") ? "" : "api"}/policies/instance/domains`).then((x) => x.json());
const info=await fetch(`${api}${url.pathname.includes("api") ? "" : "api"}/policies/instance/domains`).then(x=>x.json());
return{
api: info.apiEndpoint,
gateway: info.gateway,
@ -66,7 +65,7 @@ async function inviteres(req,res){
if(URL.canParse(req.query.url)){
url=new URL(req.query.url);
}else{
const scheme = req.secure ? 'https' : 'http';
const scheme = req.secure ? "https" : "http";
const host=`${scheme}://${req.get("Host")}`;
url=new URL(host);
}
@ -143,28 +142,27 @@ async function inviteres(req,res){
return false;
*/
app.use('/services/oembed', (req, res) => {
app.use("/services/oembed", (req, res)=>{
inviteres(req, res);
})
});
app.use("/uptime",(req,res)=>{
console.log(req.query.name)
console.log(req.query.name);
const uptime=stats.uptime[req.query.name];
console.log(req.query.name,uptime,stats.uptime)
console.log(req.query.name,uptime,stats.uptime);
res.send(uptime);
})
app.use('/', async (req, res) => {
const scheme = req.secure ? 'https' : 'http';
});
app.use("/", async (req, res)=>{
const scheme = req.secure ? "https" : "http";
const host=`${scheme}://${req.get("Host")}`;
const ref=host+req.originalUrl;
if(host&&ref){
const link=`${host}/services/oembed?url=${encodeURIComponent(ref)}`;
res.set("Link",`<${link}>; rel="alternate"; type="application/json+oembed"; title="Jank Client oEmbed format"`);
}else{
console.log(req);
}
if(req.path==="/"){
res.sendFile(`./webpage/home.html`, {root: __dirname});
res.sendFile("./webpage/home.html", {root: __dirname});
return;
}
if(debugging&&req.path.startsWith("/service.js")){
@ -176,7 +174,7 @@ app.use('/', async (req, res) => {
return;
}
if(req.path.startsWith("/invite/")){
res.sendFile(`./webpage/invite.html`, {root: __dirname});
res.sendFile("./webpage/invite.html", {root: __dirname});
return;
}
if(fs.existsSync(`${__dirname}/webpage${req.path}`)){
@ -184,18 +182,15 @@ app.use('/', async (req, res) => {
}else if(req.path.endsWith(".js") && fs.existsSync(`${__dirname}/.dist${req.path}`)){
const dir=`./.dist${req.path}`;
res.sendFile(dir, {root: __dirname});
return;
}
else if(fs.existsSync(`${__dirname}/webpage${req.path}.html`)) {
}else if(fs.existsSync(`${__dirname}/webpage${req.path}.html`)){
res.sendFile(`./webpage${req.path}.html`, {root: __dirname});
}
else {
}else{
res.sendFile("./webpage/index.html", {root: __dirname});
}
});
const PORT = process.env.PORT || +process.argv[1] || 8080;
const PORT = process.env.PORT || Number(process.argv[1]) || 8080;
app.listen(PORT, ()=>{});
console.log("this ran :P");

View file

@ -1,22 +1,25 @@
const index = require('./index.js');
const fs=require("fs");
const index = require("./index.js");
const fs=require("node:fs");
let uptimeObject={};
if(fs.existsSync("./uptime.json")){
try{
uptimeObject=JSON.parse(fs.readFileSync('./uptime.json', 'utf8'));
uptimeObject=JSON.parse(fs.readFileSync("./uptime.json", "utf8"));
}catch{
uptimeObject={};
}
}
if(uptimeObject["undefined"]){
delete uptimeObject["undefined"];
if(uptimeObject.undefined){
delete uptimeObject.undefined;
updatejson();
}
async function observe(instances){
const active=new Set();
async function resolveinstance(instance){
try{calcStats(instance)}catch(e){console.error(e)}
try{
calcStats(instance);
}catch(e){
console.error(e);
}
let api;
if(instance.urls){
api=instance.urls.api;
@ -27,27 +30,28 @@ async function observe(instances){
}
}
if(!api||api===""){
setStatus(instance,false);
console.warn(instance.name+" does not resolve api URL");
setTimeout(_=>{resolveinstance(instance)},1000*60*30,);
return
setTimeout(_=>{
resolveinstance(instance);
},1000*60*30,);
return;
}
active.add(instance.name);
api+=api.endsWith("/")?"":"/"
api+=api.endsWith("/")?"":"/";
function check(){
fetch(api+"ping",{method: "HEAD"}).then(_=>{
setStatus(instance,_.ok);
})
});
}
setTimeout(
_=>{
check();
setInterval(_=>{
check();
},1000*60*30)
},1000*60*30);
},Math.random()*1000*60*10
)
);
}
const promlist=[];
for(const instance of instances){
@ -61,7 +65,7 @@ async function observe(instances){
}
}
function calcStats(instance){
let obj=uptimeObject[instance.name];
const obj=uptimeObject[instance.name];
if(!obj)return;
const day=Date.now()-1000*60*60*24;
const week=Date.now()-1000*60*60*24*7;
@ -119,10 +123,10 @@ function calcStats(instance){
weektime=alltime;
}
}else{
weektime=alltime
weektime=alltime;
daytime=alltime;
}
instance.uptime={daytime,weektime,alltime}
instance.uptime={daytime,weektime,alltime};
}
/**
* @param {string|Object} instance
@ -141,7 +145,7 @@ function setStatus(instance,status){
uptimeObject[name]=obj;
needSetting=true;
}else{
if(obj[obj.length-1].online!==status){
if(obj.at(-1).online!==status){
needSetting=true;
}
}
@ -154,7 +158,7 @@ function setStatus(instance,status){
}
}
function updatejson(){
fs.writeFile('./uptime.json',JSON.stringify(uptimeObject),_=>{});
fs.writeFile("./uptime.json",JSON.stringify(uptimeObject),_=>{});
}
exports.observe=observe;
exports.uptime=uptimeObject;

View file

@ -10,7 +10,7 @@ class Voice{
source:AudioBufferSourceNode;
constructor(wave:string|Function,freq:number,volume=1){
this.audioCtx = new (window.AudioContext)();
this.info={wave:wave,freq:freq}
this.info={wave,freq};
this.playing=false;
this.myArrayBuffer=this.audioCtx.createBuffer(
1,
@ -46,37 +46,36 @@ class Voice{
for(let i = 0; i < this.buffer.length; i++){
this.buffer[i]=func(i/this.audioCtx.sampleRate,this.freq);
}
}
waveFunction():Function{
if(typeof this.wave === 'function'){
if(typeof this.wave === "function"){
return this.wave;
}
switch(this.wave){
case"sin":
return(t:number,freq:number)=>{
return Math.sin(t*Math.PI*2*freq);
}
};
case"triangle":
return(t:number,freq:number)=>{
return Math.abs((4*t*freq)%4-2)-1;
}
};
case"sawtooth":
return(t:number,freq:number)=>{
return((t*freq)%1)*2-1;
}
};
case"square":
return(t:number,freq:number)=>{
return(t*freq)%2<1?1:-1;
}
};
case"white":
return(_t:number,_freq:number)=>{
return Math.random()*2-1;
}
};
case"noise":
return(_t:number,_freq:number)=>{
return 0;
}
};
}
return new Function();
}
@ -86,7 +85,6 @@ class Voice{
}
this.source.connect(this.gainNode);
this.playing=true;
}
stop():void{
if(this.playing){
@ -99,9 +97,15 @@ class Voice{
case"three":{
const voicy=new Voice("sin",800);
voicy.play();
setTimeout(_=>{voicy.freq=1000},50);
setTimeout(_=>{voicy.freq=1300},100);
setTimeout(_=>{voicy.stop()},150);
setTimeout(_=>{
voicy.freq=1000;
},50);
setTimeout(_=>{
voicy.freq=1300;
},100);
setTimeout(_=>{
voicy.stop();
},150);
break;
}
case"zip":{
@ -109,23 +113,37 @@ class Voice{
return Math.sin(((t+2)**(Math.cos(t*4)))*Math.PI*2*freq);
},700);
voicy.play();
setTimeout(_=>{voicy.stop()},150);
setTimeout(_=>{
voicy.stop();
},150);
break;
}
case"square":{
const voicy=new Voice("square",600,.4);
voicy.play()
setTimeout(_=>{voicy.freq=800},50);
setTimeout(_=>{voicy.freq=1000},100);
setTimeout(_=>{voicy.stop()},150);
const voicy=new Voice("square",600,0.4);
voicy.play();
setTimeout(_=>{
voicy.freq=800;
},50);
setTimeout(_=>{
voicy.freq=1000;
},100);
setTimeout(_=>{
voicy.stop();
},150);
break;
}
case"beep":{
const voicy=new Voice("sin",800);
voicy.play();
setTimeout(_=>{voicy.stop()},50);
setTimeout(_=>{voicy.play();},100);
setTimeout(_=>{voicy.stop()},150);
setTimeout(_=>{
voicy.stop();
},50);
setTimeout(_=>{
voicy.play();
},100);
setTimeout(_=>{
voicy.stop();
},150);
break;
}
}
@ -134,13 +152,13 @@ class Voice{
return["three","zip","square","beep"];
}
static setNotificationSound(sound:string){
let userinfos=getBulkInfo();
const userinfos=getBulkInfo();
userinfos.preferences.notisound=sound;
localStorage.setItem("userinfos",JSON.stringify(userinfos));
}
static getNotificationSound(){
let userinfos=getBulkInfo();
const userinfos=getBulkInfo();
return userinfos.preferences.notisound;
}
}
export {Voice as Voice};
export{Voice};

View file

@ -1,4 +1,4 @@
"use strict"
"use strict";
import{ Message }from"./message.js";
import{Voice}from"./audio.js";
import{Contextmenu}from"./contextmenu.js";
@ -31,7 +31,7 @@ class Channel{
guild_id:string;
messageids:Map<SnowFlake<Message>,Message>;
permission_overwrites:Map<string,Permissions>;
permission_overwritesar:[SnowFlake<Role>,Permissions][]
permission_overwritesar:[SnowFlake<Role>,Permissions][];
topic:string;
nsfw:boolean;
position:number;
@ -54,12 +54,12 @@ class Channel{
}
static setupcontextmenu(){
this.contextmenu.addbutton("Copy channel id",function(this:Channel){
console.log(this)
console.log(this);
navigator.clipboard.writeText(this.id);
});
this.contextmenu.addbutton("Mark as read",function(this:Channel){
console.log(this)
console.log(this);
this.readbottom();
});
@ -68,18 +68,22 @@ class Channel{
});
this.contextmenu.addbutton("Delete channel",function(this:Channel){
console.log(this)
console.log(this);
this.deleteChannel();
},null,function(){return this.isAdmin()});
},null,function(){
return this.isAdmin();
});
this.contextmenu.addbutton("Edit channel",function(this:Channel){
this.editChannel();
},null,function(){return this.isAdmin()});
},null,function(){
return this.isAdmin();
});
this.contextmenu.addbutton("Make invite",function(this:Channel){
this.createInvite();
},null,function(){
return this.hasPermission("CREATE_INSTANT_INVITE")&&this.type!==4
return this.hasPermission("CREATE_INSTANT_INVITE")&&this.type!==4;
});
/*
this.contextmenu.addbutton("Test button",function(){
@ -108,7 +112,7 @@ class Channel{
let uses=0;
let expires=1800;
const copycontainer=document.createElement("div");
copycontainer.classList.add("copycontainer")
copycontainer.classList.add("copycontainer");
const copy=document.createElement("img");
copy.src="/icons/copy.svg";
copy.classList.add("copybutton","svgtheme");
@ -117,7 +121,7 @@ class Channel{
if(text.textContent){
navigator.clipboard.writeText(text.textContent);
}
}
};
div.append(copycontainer);
const update=()=>{
fetch(`${this.info.api}/channels/${this.id}/invites`,{
@ -133,11 +137,11 @@ class Channel{
})
}).then(_=>_.json()).then(json=>{
const params=new URLSearchParams("");
params.set("instance",this.info.wellknown)
params.set("instance",this.info.wellknown);
const encoded=params.toString();
text.textContent=`${location.origin}/invite/${json.code}?${encoded}`
})
}
text.textContent=`${location.origin}/invite/${json.code}?${encoded}`;
});
};
update();
new Dialog(["vdiv",
["title","Invite people"],
@ -151,7 +155,7 @@ class Channel{
update();
},0],
["html",div]
]).show()
]).show();
}
generateSettings(){
this.sortPerms();
@ -159,17 +163,16 @@ class Channel{
const s1=settings.addButton("roles");
s1.options.push(new RoleList(this.permission_overwritesar,this.guild,this.updateRolePermissions.bind(this),true))
s1.options.push(new RoleList(this.permission_overwritesar,this.guild,this.updateRolePermissions.bind(this),true));
settings.show();
}
sortPerms(){
this.permission_overwritesar.sort((a,b)=>{
const order=this.guild.roles.findIndex(_=>_.snowflake===a[0])-this.guild.roles.findIndex(_=>_.snowflake===b[0]);
return order;
})
return this.guild.roles.findIndex(_=>_.snowflake===a[0])-this.guild.roles.findIndex(_=>_.snowflake===b[0]);
});
}
setUpInfiniteScroller(){
this.infinite=new InfiniteScroller(async function(this:Channel,id:string,offset:number):Promise<string|undefined>{
this.infinite=new InfiniteScroller((async (id:string,offset:number):Promise<string|undefined>=>{
const snowflake=id;
if(offset===1){
if(this.idToPrev.has(snowflake)){
@ -185,37 +188,40 @@ class Channel{
await this.grabAfter(id);
return this.idToNext.get(snowflake);
}else{
console.log("at bottom")
console.log("at bottom");
}
}
}.bind(this),
async function(this:Channel,id:string){
}),
(async (id:string):Promise<HTMLElement>=>{
//await new Promise(_=>{setTimeout(_,Math.random()*10)})
const messgage=this.messages.get(id);
try{
if(messgage){
const html=messgage.buildhtml();
return html;
return messgage.buildhtml();
}else{
console.error(id+" not found")
console.error(id+" not found");
}
}catch(e){
console.error(e);
}
}.bind(this),
async function(this:Channel,id:string){
return document.createElement("div");
}),
(async (id:string)=>{
const message=this.messages.get(id);
try{
if(message){
message.deleteDiv();
return true;
}
}catch(e){console.error(e)}finally{}
}.bind(this),
}catch(e){
console.error(e);
}finally{}
return false;
}),
this.readbottom.bind(this)
);
}
constructor(json:channeljson|-1,owner:Guild){
if(json===-1){
return;
}
@ -235,7 +241,9 @@ class Channel{
this.permission_overwrites=new Map();
this.permission_overwritesar=[];
for(const thing of json.permission_overwrites){
if(thing.id==="1182819038095799904"||thing.id==="1182820803700625444"){continue;};
if(thing.id==="1182819038095799904"||thing.id==="1182820803700625444"){
continue;
}
this.permission_overwrites.set(thing.id,new Permissions(thing.allow,thing.deny));
const permission=this.permission_overwrites.get(thing.id);
if(permission){
@ -273,8 +281,10 @@ class Channel{
this.lastpin=json.last_pin_timestamp;
}
get hasunreads():boolean{
if(!this.hasPermission("VIEW_CHANNEL")){return false;}
return this.lastmessageid!==this.lastreadmessageid&&this.type!==4&&!!this.lastmessageid;
if(!this.hasPermission("VIEW_CHANNEL")){
return false;
}
return this.lastmessageid!==this.lastreadmessageid&&this.type!==4&&Boolean(this.lastmessageid);
}
hasPermission(name:string,member=this.guild.member):boolean{
if(member.isAdmin()){
@ -283,7 +293,7 @@ class Channel{
for(const thing of member.roles){
const premission=this.permission_overwrites.get(thing.id);
if(premission){
let perm=premission.getPermission(name);
const perm=premission.getPermission(name);
if(perm){
return perm===1;
}
@ -295,7 +305,7 @@ class Channel{
return false;
}
get canMessage():boolean{
if((0===this.permission_overwritesar.length)&&this.hasPermission("MANAGE_CHANNELS")){
if((this.permission_overwritesar.length===0)&&this.hasPermission("MANAGE_CHANNELS")){
const role=this.guild.roles.find(_=>_.name==="@everyone");
if(role){
this.addRoleToPerms(role);
@ -304,7 +314,9 @@ class Channel{
return this.hasPermission("SEND_MESSAGES");
}
sortchildren(){
this.children.sort((a,b)=>{return a.position-b.position});
this.children.sort((a,b)=>{
return a.position-b.position;
});
}
resolveparent(guild:Guild){
const parentid=this.parent_id?.id;
@ -318,7 +330,7 @@ class Channel{
}
calculateReorder(){
let position=-1;
let build:{id:SnowFlake<Channel>,position:number|undefined,parent_id:SnowFlake<Channel>|undefined}[]=[];
const build:{id:SnowFlake<Channel>,position:number|undefined,parent_id:SnowFlake<Channel>|undefined}[]=[];
for(const thing of this.children){
const thisthing:{id:SnowFlake<Channel>,position:number|undefined,parent_id:SnowFlake<Channel>|undefined}={id: thing.snowflake,position: undefined,parent_id: undefined};
if(thing.position<position){
@ -341,7 +353,7 @@ class Channel{
createguildHTML(admin=false):HTMLDivElement{
const div=document.createElement("div");
if(!this.hasPermission("VIEW_CHANNEL")){
let quit=true
let quit=true;
for(const thing of this.children){
if(thing.hasPermission("VIEW_CHANNEL")){
quit=false;
@ -353,8 +365,12 @@ class Channel{
}
div["all"]=this;
div.draggable=admin;
div.addEventListener("dragstart",(e)=>{Channel.dragged=[this,div];e.stopImmediatePropagation()})
div.addEventListener("dragend",()=>{Channel.dragged=[]})
div.addEventListener("dragstart",e=>{
Channel.dragged=[this,div];e.stopImmediatePropagation();
});
div.addEventListener("dragend",()=>{
Channel.dragged=[];
});
if(this.type===4){
this.sortchildren();
const caps=document.createElement("div");
@ -362,8 +378,8 @@ class Channel{
const decdiv=document.createElement("div");
const decoration=document.createElement("img");
decoration.src="/icons/category.svg";
decoration.classList.add("svgtheme","colaspeicon")
decdiv.appendChild(decoration)
decoration.classList.add("svgtheme","colaspeicon");
decdiv.appendChild(decoration);
const myhtml=document.createElement("p2");
myhtml.textContent=this.name;
@ -377,11 +393,11 @@ class Channel{
caps.appendChild(addchannel);
addchannel.onclick=_=>{
this.guild.createchannels(this.createChannel.bind(this));
}
};
this.coatDropDiv(decdiv,childrendiv);
}
div.appendChild(caps)
caps.classList.add("capsflex")
div.appendChild(caps);
caps.classList.add("capsflex");
decdiv.classList.add("channeleffects");
decdiv.classList.add("channel");
@ -393,18 +409,20 @@ class Channel{
childrendiv.appendChild(channel.createguildHTML(admin));
}
childrendiv.classList.add("channels");
setTimeout(_=>{childrendiv.style.height = childrendiv.scrollHeight + 'px';},100)
setTimeout(_=>{
childrendiv.style.height = childrendiv.scrollHeight + "px";
},100);
decdiv.onclick=function(){
if(childrendiv.style.height!=='0px'){
if(childrendiv.style.height!=="0px"){
decoration.classList.add("hiddencat");
//childrendiv.classList.add("colapsediv");
childrendiv.style.height = '0px';
childrendiv.style.height = "0px";
}else{
decoration.classList.remove("hiddencat");
//childrendiv.classList.remove("colapsediv")
childrendiv.style.height = childrendiv.scrollHeight + 'px';
}
childrendiv.style.height = childrendiv.scrollHeight + "px";
}
};
div.appendChild(childrendiv);
}else{
div.classList.add("channel");
@ -412,39 +430,41 @@ class Channel{
div.classList.add("cunread");
}
Channel.contextmenu.bindContextmenu(div,this,undefined);
if(admin){this.coatDropDiv(div);}
if(admin){
this.coatDropDiv(div);
}
div["all"]=this;
const myhtml=document.createElement("span");
myhtml.textContent=this.name;
if(this.type===0){
const decoration=document.createElement("img");
decoration.src="/icons/channel.svg";
div.appendChild(decoration)
div.appendChild(decoration);
decoration.classList.add("space","svgtheme");
}else if(this.type===2){//
const decoration=document.createElement("img");
decoration.src="/icons/voice.svg";
div.appendChild(decoration)
div.appendChild(decoration);
decoration.classList.add("space","svgtheme");
}else if(this.type===5){//
const decoration=document.createElement("img");
decoration.src="/icons/announce.svg";
div.appendChild(decoration)
div.appendChild(decoration);
decoration.classList.add("space","svgtheme");
}else{
console.log(this.type)
console.log(this.type);
}
div.appendChild(myhtml);
div.onclick=_=>{
this.getHTML();
}
};
}
return div;
}
get myhtml(){
const search=(document.getElementById("channels") as HTMLDivElement).children[0].children
const search=(document.getElementById("channels") as HTMLDivElement).children[0].children;
if(this.guild!==this.localuser.lookingguild){
return null
return null;
}else if(this.parent){
for(const thing of search){
if(thing["all"]===this.parent){
@ -480,16 +500,16 @@ class Channel{
}
}
coatDropDiv(div:HTMLDivElement,container:HTMLElement|boolean=false){
div.addEventListener("dragenter", (event) => {
console.log("enter")
div.addEventListener("dragenter", event=>{
console.log("enter");
event.preventDefault();
});
div.addEventListener("dragover", (event) => {
div.addEventListener("dragover", event=>{
event.preventDefault();
});
div.addEventListener("drop", (event) => {
div.addEventListener("drop", event=>{
const that=Channel.dragged[0];
if(!that)return;
event.preventDefault();
@ -513,7 +533,7 @@ class Channel{
if(that.parent){
const build:Channel[]=[];
for(let i=0;i<that.parent.children.length;i++){
build.push(that.parent.children[i])
build.push(that.parent.children[i]);
if(that.parent.children[i]===this){
build.push(that);
}
@ -522,7 +542,7 @@ class Channel{
}else{
const build:Channel[]=[];
for(let i=0;i<this.guild.headchannels.length;i++){
build.push(this.guild.headchannels[i])
build.push(this.guild.headchannels[i]);
if(this.guild.headchannels[i]===this){
build.push(that);
}
@ -533,7 +553,7 @@ class Channel{
div.after(Channel.dragged[1]);
}
}
this.guild.calculateReorder()
this.guild.calculateReorder();
});
return div;
@ -543,12 +563,12 @@ class Channel{
method: "POST",
headers: this.headers,
body: JSON.stringify({
name: name,
type: type,
name,
type,
parent_id: this.snowflake,
permission_overwrites: [],
})
})
});
}
editChannel(){
let name=this.name;
@ -559,41 +579,46 @@ class Channel{
const full=new Dialog(
["hdiv",
["vdiv",
["textbox","Channel name:",this.name,function(this:HTMLInputElement){name=this.value}],
["mdbox","Channel topic:",this.topic,function(this:HTMLTextAreaElement){topic=this.value}],
["checkbox","NSFW Channel",this.nsfw,function(this:HTMLInputElement){nsfw=this.checked}],
["textbox","Channel name:",this.name,function(this:HTMLInputElement){
name=this.value;
}],
["mdbox","Channel topic:",this.topic,function(this:HTMLTextAreaElement){
topic=this.value;
}],
["checkbox","NSFW Channel",this.nsfw,function(this:HTMLInputElement){
nsfw=this.checked;
}],
["button","","submit",()=>{
fetch(this.info.api+"/channels/"+thisid,{
method: "PATCH",
headers: this.headers,
body: JSON.stringify({
"name": name,
"type": thistype,
"topic": topic,
"bitrate": 64000,
"user_limit": 0,
"nsfw": nsfw,
"flags": 0,
"rate_limit_per_user": 0
name,
type: thistype,
topic,
bitrate: 64000,
user_limit: 0,
nsfw,
flags: 0,
rate_limit_per_user: 0
})
})
console.log(full)
});
console.log(full);
full.hide();
}]
]
]);
full.show();
console.log(full)
console.log(full);
}
deleteChannel(){
fetch(this.info.api+"/channels/"+this.snowflake,{
method: "DELETE",
headers: this.headers
})
});
}
setReplying(message:Message){
if(this.replyingto?.div){
this.replyingto.div.classList.remove("replying");
}
@ -602,7 +627,6 @@ class Channel{
console.log(message);
this.replyingto.div.classList.add("replying");
this.makereplybox();
}
makereplybox(){
const replybox=document.getElementById("replybox") as HTMLElement;
@ -618,7 +642,7 @@ class Channel{
replybox.classList.add("hideReplyBox");
this.replyingto=null;
replybox.innerHTML="";
}
};
replybox.classList.remove("hideReplyBox");
X.textContent="⦻";
X.classList.add("cancelReply");
@ -633,7 +657,7 @@ class Channel{
if(message){
return message;
}else{
const gety=await fetch(this.info.api+"/channels/"+this.snowflake+"/messages?limit=1&around="+id,{headers:this.headers})
const gety=await fetch(this.info.api+"/channels/"+this.snowflake+"/messages?limit=1&around="+id,{headers: this.headers});
const json=await gety.json();
return new Message(json[0],this);
}
@ -651,7 +675,7 @@ class Channel{
this.localuser.channelfocus.myhtml.classList.remove("viewChannel");
}
if(this.myhtml){
this.myhtml.classList.add("viewChannel")
this.myhtml.classList.add("viewChannel");
}
this.guild.prevchannel=this;
this.localuser.channelfocus=this;
@ -686,8 +710,8 @@ class Channel{
for(let i=0;i<15;i++){
const div=document.createElement("div");
div.classList.add("loadingmessage");
if(Math.random()<.5){
const pfp=document.createElement("div")
if(Math.random()<0.5){
const pfp=document.createElement("div");
pfp.classList.add("loadingpfp");
const username=document.createElement("div");
username.style.width=Math.floor(Math.random()*96*1.5+40)+"px";
@ -704,9 +728,11 @@ class Channel{
}
lastmessage:Message|undefined;
async putmessages(){
if(this.allthewayup){return};
if(this.allthewayup){
return;
}
if(this.lastreadmessageid&&this.messages.has(this.lastreadmessageid)){
return
return;
}
const j=await fetch(this.info.api+"/channels/"+this.snowflake+"/messages?limit=100",{
headers: this.headers,
@ -716,7 +742,7 @@ class Channel{
if(response.length!==100){
this.allthewayup=true;
}
let prev:Message|undefined=undefined;
let prev:Message|undefined;
for(const thing of response){
const message=new Message(thing,this);
if(prev){
@ -736,7 +762,7 @@ class Channel{
const build:Channel[]=[];
for(const thing of this.children){
if(thing.id!==json.id){
build.push(thing)
build.push(thing);
}
}
this.children=build;
@ -747,11 +773,13 @@ class Channel{
}
await fetch(this.info.api+"/channels/"+this.id+"/messages?limit=100&after="+id,{
headers: this.headers
}).then((j)=>{return j.json()}).then(response=>{
}).then(j=>{
return j.json();
}).then(response=>{
let previd:string=id;
for(const i in response){
let messager:Message;
let willbreak=false
let willbreak=false;
if(!SnowFlake.hasSnowFlakeFromID(response[i].id,Message)){
messager=new Message(response[i],this);
}else{
@ -767,8 +795,7 @@ class Channel{
}
}
//out.buildmessages();
})
return;
});
}
topid:string;
async grabBefore(id:string){
@ -778,7 +805,9 @@ class Channel{
await fetch(this.info.api+"/channels/"+this.id+"/messages?before="+id+"&limit=100",{
headers: this.headers
}).then((j)=>{return j.json()}).then((response:messagejson[])=>{
}).then(j=>{
return j.json();
}).then((response:messagejson[])=>{
if(response.length<100){
this.allthewayup=true;
if(response.length===0){
@ -790,7 +819,7 @@ class Channel{
let messager:Message;
let willbreak=false;
if(this.messages.has(response[i].id)){
console.log("flaky")
console.log("flaky");
messager=this.messages.get(response[i].id) as Message;
willbreak=true;
}else{
@ -802,15 +831,14 @@ class Channel{
previd=messager.id;
this.messageids.set(messager.snowflake,messager);
if(+i===response.length-1&&response.length<100){
if(Number(i)===response.length-1&&response.length<100){
this.topid=previd;
}
if(willbreak){
break;
}
}
})
return;
});
}
/**
* Please dont use this, its not implemented.
@ -818,7 +846,7 @@ class Channel{
* @todo
**/
async grabArround(id:string){//currently unused and no plans to use it yet
throw new Error("please don't call this, no one has implemented it :P")
throw new Error("please don't call this, no one has implemented it :P");
}
async buildmessages(){
/*
@ -852,7 +880,7 @@ class Channel{
if(!removetitle){
const title=document.createElement("h2");
title.id="removetitle";
title.textContent="No messages appear to be here, be the first to say something!"
title.textContent="No messages appear to be here, be the first to say something!";
title.classList.add("titlespace");
messages.append(title);
}
@ -870,7 +898,6 @@ class Channel{
loading.classList.remove("loading");
});
//this.infinite.focus(id.id,false);
}
private goBackIds(id:string,back:number,returnifnotexistant=true):string|undefined{
while(back!==0){
@ -897,7 +924,7 @@ class Channel{
flake=this.idToPrev.get(flake);
if(!flake){
return undefined;
return;
}
flaketime=Number((BigInt(flake)>>22n)+1420070400000n);
}
@ -913,7 +940,9 @@ class Channel{
this.messageids=new Map();
this.permission_overwrites=new Map();
for(const thing of json.permission_overwrites){
if(thing.id==="1182819038095799904"||thing.id==="1182820803700625444"){continue;};
if(thing.id==="1182819038095799904"||thing.id==="1182820803700625444"){
continue;
}
this.permission_overwrites.set(thing.id,new Permissions(thing.allow,thing.deny));
const permisions=this.permission_overwrites.get(thing.id);
if(permisions){
@ -924,20 +953,22 @@ class Channel{
this.nsfw=json.nsfw;
}
typingstart(){
if(this.typing>new Date().getTime()){
if(this.typing>Date.now()){
return;
}
this.typing=new Date().getTime()+6000;
this.typing=Date.now()+6000;
fetch(this.info.api+"/channels/"+this.snowflake+"/typing",{
method: "POST",
headers: this.headers
})
});
}
get notification(){
let notinumber:number|null=this.message_notifications;
if(+notinumber===3){notinumber=null;}
if(Number(notinumber)===3){
notinumber=null;
}
notinumber??=this.guild.message_notifications;
switch(+notinumber){
switch(Number(notinumber)){
case 0:
return"all";
case 1:
@ -954,14 +985,14 @@ class Channel{
if(replyingto){
replyjson=
{
"guild_id":replyingto.guild.id,
"channel_id": replyingto.channel.id,
"message_id": replyingto.id,
};
guild_id: replyingto.guild.id,
channel_id: replyingto.channel.id,
message_id: replyingto.id,
};
}
if(attachments.length===0){
const body={
content:content,
content,
nonce: Math.floor(Math.random()*1000000000),
message_reference: undefined
};
@ -972,30 +1003,32 @@ class Channel{
method: "POST",
headers: this.headers,
body: JSON.stringify(body)
})
});
}else{
const formData = new FormData();
const body={
content:content,
content,
nonce: Math.floor(Math.random()*1000000000),
message_reference: undefined
}
};
if(replyjson){
body.message_reference=replyjson;
}
formData.append('payload_json', JSON.stringify(body));
formData.append("payload_json", JSON.stringify(body));
for(const i in attachments){
formData.append("files["+i+"]",attachments[i]);
}
return await fetch(this.info.api+"/channels/"+this.snowflake+"/messages", {
method: 'POST',
method: "POST",
body: formData,
headers:{"Authorization":this.headers.Authorization}
headers: {Authorization: this.headers.Authorization}
});
}
}
messageCreate(messagep:messageCreateJson):void{
if(!this.hasPermission("VIEW_CHANNEL")){return}
if(!this.hasPermission("VIEW_CHANNEL")){
return;
}
const messagez=new Message(messagep.d,this);
this.lastmessage=messagez;
if(this.lastmessageid){
@ -1018,7 +1051,9 @@ class Channel{
}
this.guild.unreads();
if(this===this.localuser.channelfocus){
if(!this.infinitefocus){this.tryfocusinfinate();}
if(!this.infinitefocus){
this.tryfocusinfinate();
}
this.infinite.addedBottom();
}
if(messagez.author===this.localuser.user){
@ -1032,7 +1067,6 @@ class Channel{
}else if(this.notification==="mentions"&&messagez.mentionsuser(this.localuser.user)){
this.notify(messagez);
}
}
notititle(message:Message):string{
return message.author.username+" > "+this.guild.properties.name+" > "+this.name;
@ -1065,10 +1099,12 @@ class Channel{
notification.addEventListener("click",_=>{
window.focus();
this.getHTML();
})
});
}else if(Notification.permission !== "denied"){
Notification.requestPermission().then(()=>{
if(deep===3){return};
if(deep===3){
return;
}
this.notify(message,deep+1);
});
}
@ -1083,7 +1119,7 @@ class Channel{
id: role.id,
type: 0
})
})
});
const perm=new Permissions("0","0");
this.permission_overwrites.set(role.id,perm);
this.permission_overwritesar.push([role.snowflake,perm]);
@ -1099,10 +1135,10 @@ class Channel{
body: JSON.stringify({
allow: permission.allow.toString(),
deny: permission.deny.toString(),
id:id,
id,
type: 0
})
})
});
}
}
}

View file

@ -5,7 +5,7 @@ class Contextmenu<x,y>{
div:HTMLDivElement;
static setup(){
Contextmenu.currentmenu="";
document.addEventListener('click', function(event) {
document.addEventListener("click", event=>{
if(Contextmenu.currentmenu==""){
return;
}
@ -17,14 +17,14 @@ class Contextmenu<x,y>{
}
constructor(name:string){
this.name=name;
this.buttons=[]
this.buttons=[];
}
addbutton(text:string,onclick:(this:x,arg:y,e:MouseEvent)=>void,img:null|string=null,shown:(this:x,arg:y)=>boolean=_=>true,enabled:(this:x,arg:y)=>boolean=_=>true){
this.buttons.push([text,onclick,img,shown,enabled,"button"]);
return{};
}
addsubmenu(text:string,onclick:(this:x,arg:y,e:MouseEvent)=>void,img=null,shown:(this:x,arg:y)=>boolean=_=>true,enabled:(this:x,arg:y)=>boolean=_=>true){
this.buttons.push([text,onclick,img,shown,enabled,"submenu"])
this.buttons.push([text,onclick,img,shown,enabled,"submenu"]);
return{};
}
makemenu(x:number,y:number,addinfo:any,other:y){
@ -36,11 +36,11 @@ class Contextmenu<x,y>{
if(!thing[3].bind(addinfo)(other))continue;
visibleButtons++;
const intext=document.createElement("button")
const intext=document.createElement("button");
intext.disabled=!thing[4].bind(addinfo)(other);
intext.classList.add("contextbutton")
intext.textContent=thing[0]
console.log(thing)
intext.classList.add("contextbutton");
intext.textContent=thing[0];
console.log(thing);
if(thing[5]==="button"||thing[5]==="submenu"){
intext.onclick=thing[1].bind(addinfo,other);
}
@ -52,37 +52,37 @@ class Contextmenu<x,y>{
if(Contextmenu.currentmenu!=""){
Contextmenu.currentmenu.remove();
}
div.style.top = y+'px';
div.style.left = x+'px';
div.style.top = y+"px";
div.style.left = x+"px";
document.body.appendChild(div);
Contextmenu.keepOnScreen(div);
console.log(div)
console.log(div);
Contextmenu.currentmenu=div;
return this.div;
}
bindContextmenu(obj:HTMLElement,addinfo:x,other:y){
const func=(event) => {
const func=event=>{
event.preventDefault();
event.stopImmediatePropagation();
this.makemenu(event.clientX,event.clientY,addinfo,other);
}
};
obj.addEventListener("contextmenu", func);
return func;
}
static keepOnScreen(obj:HTMLElement){
const html = document.documentElement.getBoundingClientRect();
const docheight=html.height
const docwidth=html.width
const docheight=html.height;
const docwidth=html.width;
const box=obj.getBoundingClientRect();
console.log(box,docheight,docwidth);
if(box.right>docwidth){
console.log("test")
obj.style.left = docwidth-box.width+'px';
console.log("test");
obj.style.left = docwidth-box.width+"px";
}
if(box.bottom>docheight){
obj.style.top = docheight-box.height+'px';
obj.style.top = docheight-box.height+"px";
}
}
}
Contextmenu.setup();
export {Contextmenu as Contextmenu}
export{Contextmenu};

View file

@ -10,11 +10,10 @@ class Dialog{
this.onclose=onclose;
this.onopen=onopen;
const div=document.createElement("div");
div.appendChild(this.tohtml(layout))
div.appendChild(this.tohtml(layout));
this.html=div;
this.html.classList.add("centeritem");
if(!(layout[0]==="img")){
this.html.classList.add("nonimagecenter");
}
}
@ -28,17 +27,19 @@ class Dialog{
img.width=array[2][0];
img.height=array[2][1];
}else if(array[2][0]=="fit"){
img.classList.add("imgfit")
img.classList.add("imgfit");
}
}
return img;
case"hdiv":
const hdiv=document.createElement("table");
const tr=document.createElement("tr");
hdiv.appendChild(tr)
hdiv.appendChild(tr);
for(const thing of array){
if(thing==="hdiv"){continue;}
if(thing==="hdiv"){
continue;
}
const td=document.createElement("td");
td.appendChild(this.tohtml(thing));
tr.appendChild(td);
@ -47,7 +48,9 @@ class Dialog{
case"vdiv":
const vdiv=document.createElement("table");
for(const thing of array){
if(thing==="vdiv"){continue;}
if(thing==="vdiv"){
continue;
}
const tr=document.createElement("tr");
tr.appendChild(this.tohtml(thing));
vdiv.appendChild(tr);
@ -56,8 +59,8 @@ class Dialog{
case"checkbox":
{
const div=document.createElement("div");
const checkbox = document.createElement('input');
div.appendChild(checkbox)
const checkbox = document.createElement("input");
div.appendChild(checkbox);
const label=document.createElement("span");
checkbox.checked=array[2];
label.textContent=array[1];
@ -69,13 +72,13 @@ class Dialog{
case"button":
{
const div=document.createElement("div");
const input = document.createElement('button');
const input = document.createElement("button");
const label=document.createElement("span");
input.textContent=array[2];
label.textContent=array[1];
div.appendChild(label);
div.appendChild(input)
div.appendChild(input);
input.addEventListener("click",array[3]);
return div;
}
@ -100,7 +103,7 @@ class Dialog{
input.type="text";
const label=document.createElement("span");
label.textContent=array[1];
console.log(array[3])
console.log(array[3]);
input.addEventListener("input",array[3]);
div.appendChild(label);
div.appendChild(input);
@ -116,7 +119,7 @@ class Dialog{
div.appendChild(label);
div.appendChild(input);
input.addEventListener("change",array[2]);
console.log(array)
console.log(array);
return div;
}
case"text":{
@ -126,14 +129,14 @@ class Dialog{
}
case"title":{
const span =document.createElement("span");
span.classList.add("title")
span.classList.add("title");
span.textContent=array[1];
return span;
}
case"radio":{
const div=document.createElement("div");
const fieldset=document.createElement("fieldset");
fieldset.addEventListener("change",function(){
fieldset.addEventListener("change",()=>{
let i=-1;
for(const thing of fieldset.children){
i++;
@ -153,7 +156,7 @@ class Dialog{
for(const thing of array[2]){
const div=document.createElement("div");
const input=document.createElement("input");
input.classList.add("radio")
input.classList.add("radio");
input.type="radio";
input.name=array[1];
input.value=thing;
@ -168,14 +171,14 @@ class Dialog{
label.appendChild(span);
div.appendChild(label);
fieldset.appendChild(div);
i++
i++;
}
div.appendChild(fieldset);
return div;
}
case "html":{
case"html":
return array[1];
}
case"select":{
const div=document.createElement("div");
const label=document.createElement("label");
@ -206,7 +209,6 @@ class Dialog{
let shown;
for(const thing of array[1]){
const button=document.createElement("button");
button.textContent=thing[0];
td.appendChild(button);
@ -225,23 +227,24 @@ class Dialog{
shown.hidden=true;
tdcontent.hidden=false;
shown=tdcontent;
})
});
}
return table;
}
default:
console.error("can't find element:"+array[0]," full element:"+array)
return;
console.error("can't find element:"+array[0]," full element:"+array);
}
}
show(){
this.onopen();
console.log("fullscreen")
console.log("fullscreen");
this.background=document.createElement("div");
this.background.classList.add("background");
document.body.appendChild(this.background);
document.body.appendChild(this.html);
this.background.onclick = _=>{this.hide()};
this.background.onclick = _=>{
this.hide();
};
}
hide(){
document.body.removeChild(this.background);

View file

@ -14,7 +14,7 @@ class Direct extends Guild{
this.message_notifications=0;
this.owner=owner;
if(!this.localuser){
console.error("Owner was not included, please fix")
console.error("Owner was not included, please fix");
}
this.headers=this.localuser.headers;
this.channels=[];
@ -40,7 +40,7 @@ class Direct extends Guild{
this.printServers();
}
giveMember(_member:memberjson){
console.error("not a real guild, can't give member object")
console.error("not a real guild, can't give member object");
}
getRole(ID:string){
return null;
@ -102,7 +102,6 @@ class Group extends Channel{
this.messageids=new Map();
this.permission_overwrites=new Map();
this.lastmessageid=json.last_message_id;
this.lastmessageid??=null;
this.mentions=0;
this.setUpInfiniteScroller();
if(this.lastmessageid){
@ -111,7 +110,7 @@ class Group extends Channel{
this.position=-Math.max(this.position,this.snowflake.getUnixTime());
}
createguildHTML(){
const div=document.createElement("div")
const div=document.createElement("div");
div.classList.add("channeleffects");
const myhtml=document.createElement("span");
myhtml.textContent=this.name;
@ -120,7 +119,7 @@ class Group extends Channel{
div["myinfo"]=this;
div.onclick=_=>{
this.getHTML();
}
};
return div;
}
async getHTML(){
@ -146,8 +145,8 @@ class Group extends Channel{
const messagez=new Message(messagep.d,this);
if(this.lastmessageid){
this.idToNext.set(this.lastmessageid,messagez.id);
}
this.idToPrev.set(messagez.id,this.lastmessageid);
}
this.lastmessageid=messagez.id;
this.messageids.set(messagez.snowflake,messagez);
if(messagez.author===this.localuser.user){
@ -186,25 +185,26 @@ class Group extends Channel{
}
}
if(this.hasunreads){
if(current){current["noti"].textContent=this.mentions;return;}
if(current){
current["noti"].textContent=this.mentions;return;
}
const div=document.createElement("div");
div.classList.add("servernoti");
const noti=document.createElement("div");
noti.classList.add("unread","notiunread","pinged");
noti.textContent=""+this.mentions;
div["noti"]=noti;
div.append(noti)
div.append(noti);
const buildpfp=this.user.buildpfp();
div["all"]=this;
buildpfp.classList.add("mentioned");
div.append(buildpfp)
div.append(buildpfp);
sentdms.append(div);
div.onclick=_=>{
this.guild.loadGuild();
this.getHTML();
}
};
}else if(current){
current.remove();
}else{

View file

@ -64,9 +64,9 @@ class Embed{
const a=document.createElement("a");
a.textContent=this.json.author.name as string;
if(this.json.author.url){
a.href=this.json.author.url
a.href=this.json.author.url;
}
a.classList.add("username")
a.classList.add("username");
authorline.append(a);
embed.append(authorline);
}
@ -92,12 +92,14 @@ class Embed{
const b=document.createElement("b");
b.textContent=thing.name;
div.append(b);
const p=document.createElement("p")
const p=document.createElement("p");
p.append(new MarkDown(thing.value,this.channel).makeHTML());
p.classList.add("embedp");
div.append(p);
if(thing.inline){div.classList.add("inline");}
if(thing.inline){
div.classList.add("inline");
}
embed.append(div);
}
}
@ -122,8 +124,8 @@ class Embed{
footer.append(span);
}
if(this.json?.timestamp){
const span=document.createElement("span")
span.textContent=new Date(this.json.timestamp).toLocaleString();;
const span=document.createElement("span");
span.textContent=new Date(this.json.timestamp).toLocaleString();
footer.append(span);
}
embed.append(footer);
@ -132,11 +134,11 @@ class Embed{
}
generateImage(){
const img=document.createElement("img");
img.classList.add("messageimg")
img.classList.add("messageimg");
img.onclick=function(){
const full=new Dialog(["img",img.src,["fit"]]);
full.show();
}
};
img.src=this.json.thumbnail.proxy_url;
if(this.json.thumbnail.width){
let scale=1;
@ -172,7 +174,7 @@ class Embed{
img.onclick=function(){
const full=new Dialog(["img",img.src,["fit"]]);
full.show();
}
};
img.src=this.json.thumbnail.proxy_url;
td.append(img);
}
@ -186,7 +188,7 @@ class Embed{
td.append(span);
}
bottomtr.append(td);
table.append(bottomtr)
table.append(bottomtr);
return table;
}
generateArticle(){
@ -219,7 +221,7 @@ class Embed{
img.onclick=function(){
const full=new Dialog(["img",img.src,["fit"]]);
full.show();
}
};
img.src=this.json.thumbnail.proxy_url||this.json.thumbnail.url;
div.append(img);
}

View file

@ -33,7 +33,7 @@ class Emoji{
constructor(json:{name:string,id:string,animated:boolean},owner:Guild|Localuser){
this.name=json.name;
this.id=json.id;
this.animated=json.animated
this.animated=json.animated;
this.owner=owner;
}
getHTML(bigemoji:boolean=false){
@ -72,10 +72,8 @@ class Emoji{
for(let i=0;i<length;i++){
array[i]=read8();
}
const decoded=new TextDecoder("utf-8").decode(array.buffer);;
//console.log(array);
return decoded;
return new TextDecoder("utf-8").decode(array.buffer);
}
const build:{name:string,emojis:{name:string,emoji:string}[]}[]=[];
let cats=read16();
@ -93,33 +91,35 @@ class Emoji{
const name=readString8();
const len=read8();
const skin_tone_support=len>127;
const emoji=readStringNo(len-(+skin_tone_support*128));
const emoji=readStringNo(len-(Number(skin_tone_support)*128));
emojis.push({
name,
skin_tone_support,
emoji
})
});
}
build.push({
name,
emojis
})
});
}
this.emojis=build;
console.log(build);
}
static grabEmoji(){
fetch("/emoji.bin").then(e=>{
return e.arrayBuffer()
return e.arrayBuffer();
}).then(e=>{
Emoji.decodeEmojiList(e);
})
});
}
static async emojiPicker(x:number,y:number, localuser:Localuser):Promise<Emoji|string>{
let res:(r:Emoji|string)=>void;
const promise:Promise<Emoji|string>=new Promise((r)=>{res=r;})
const promise:Promise<Emoji|string>=new Promise(r=>{
res=r;
});
const menu=document.createElement("div");
menu.classList.add("flextttb", "emojiPicker")
menu.classList.add("flextttb", "emojiPicker");
menu.style.top=y+"px";
menu.style.left=x+"px";
@ -134,52 +134,52 @@ class Emoji{
let isFirst = true;
localuser.guilds.filter(guild=>guild.id != "@me" && guild.emojis.length > 0).forEach(guild=>{
const select = document.createElement("div")
select.classList.add("emojiSelect")
const select = document.createElement("div");
select.classList.add("emojiSelect");
if(guild.properties.icon){
const img = document.createElement("img")
img.classList.add("pfp", "servericon", "emoji-server")
img.crossOrigin = "anonymous"
img.src = localuser.info.cdn + "/icons/" + guild.properties.id + "/" + guild.properties.icon + ".png?size=48"
img.alt = "Server: " + guild.properties.name
select.appendChild(img)
const img = document.createElement("img");
img.classList.add("pfp", "servericon", "emoji-server");
img.crossOrigin = "anonymous";
img.src = localuser.info.cdn + "/icons/" + guild.properties.id + "/" + guild.properties.icon + ".png?size=48";
img.alt = "Server: " + guild.properties.name;
select.appendChild(img);
}else{
const div = document.createElement("span")
div.textContent = guild.properties.name.replace(/'s /g, " ").replace(/\w+/g, word => word[0]).replace(/\s/g, "")
select.append(div)
const div = document.createElement("span");
div.textContent = guild.properties.name.replace(/'s /g, " ").replace(/\w+/g, word=>word[0]).replace(/\s/g, "");
select.append(div);
}
selection.append(select)
selection.append(select);
const clickEvent = ()=>{
title.textContent = guild.properties.name
body.innerHTML = ""
title.textContent = guild.properties.name;
body.innerHTML = "";
for(const emojit of guild.emojis){
const emojiElem = document.createElement("div")
emojiElem.classList.add("emojiSelect")
const emojiElem = document.createElement("div");
emojiElem.classList.add("emojiSelect");
const emojiClass = new Emoji({
id: emojit.id as string,
name: emojit.name,
animated: emojit.animated as boolean
},localuser)
emojiElem.append(emojiClass.getHTML())
body.append(emojiElem)
},localuser);
emojiElem.append(emojiClass.getHTML());
body.append(emojiElem);
emojiElem.addEventListener("click", ()=>{
res(emojiClass)
Contextmenu.currentmenu.remove()
})
}
res(emojiClass);
Contextmenu.currentmenu.remove();
});
}
};
select.addEventListener("click", clickEvent)
select.addEventListener("click", clickEvent);
if(isFirst){
clickEvent()
isFirst = false
clickEvent();
isFirst = false;
}
})
});
setTimeout(()=>{
if(Contextmenu.currentmenu!=""){
@ -188,7 +188,7 @@ class Emoji{
document.body.append(menu);
Contextmenu.currentmenu=menu;
Contextmenu.keepOnScreen(menu);
},10)
},10);
let i=0;
@ -208,10 +208,10 @@ class Emoji{
emoji.onclick=_=>{
res(emojit.emoji);
Contextmenu.currentmenu.remove();
}
};
}
};
select.onclick=clickEvent
select.onclick=clickEvent;
if(i===0){
clickEvent();
}

View file

@ -34,25 +34,25 @@ class File{
this.width/=scale;
this.height/=scale;
}
if(this.content_type.startsWith('image/')){
const div=document.createElement("div")
if(this.content_type.startsWith("image/")){
const div=document.createElement("div");
const img=document.createElement("img");
img.classList.add("messageimg");
div.classList.add("messageimgdiv")
div.classList.add("messageimgdiv");
img.onclick=function(){
const full=new Dialog(["img",img.src,["fit"]]);
full.show();
}
};
img.src=src;
div.append(img)
div.append(img);
if(this.width){
div.style.width=this.width+"px";
div.style.height=this.height+"px";
}
console.log(img);
console.log(this.width,this.height)
console.log(this.width,this.height);
return div;
}else if(this.content_type.startsWith('video/')){
}else if(this.content_type.startsWith("video/")){
const video=document.createElement("video");
const source=document.createElement("source");
source.src=src;
@ -64,7 +64,7 @@ class File{
video.height=this.height;
}
return video;
}else if(this.content_type.startsWith('audio/')){
}else if(this.content_type.startsWith("audio/")){
const audio=document.createElement("audio");
const source=document.createElement("source");
source.src=src;
@ -87,7 +87,7 @@ class File{
garbage.onclick=_=>{
div.remove();
files.splice(files.indexOf(file),1);
}
};
controls.classList.add("controls");
div.append(controls);
controls.append(garbage);
@ -103,10 +103,10 @@ class File{
height: undefined,
url: URL.createObjectURL(file),
proxy_url: undefined
},null)
},null);
}
createunknown():HTMLElement{
console.log("🗎")
console.log("🗎");
const src=this.proxy_url||this.url;
const div=document.createElement("table");
div.classList.add("unknownfile");
@ -138,8 +138,8 @@ class File{
return div;
}
static filesizehuman(fsize:number){
var i = fsize == 0 ? 0 : Math.floor(Math.log(fsize) / Math.log(1024));
return +((fsize / Math.pow(1024, i)).toFixed(2)) * 1 + ' ' + ['Bytes', 'Kilobytes', 'Megabytes', 'Gigabytes', 'Terabytes'][i];
const i = fsize == 0 ? 0 : Math.floor(Math.log(fsize) / Math.log(1024));
return Number((fsize / Math.pow(1024, i)).toFixed(2)) * 1 + " " + ["Bytes", "Kilobytes", "Megabytes", "Gigabytes", "Terabytes"][i];
}
}
export{File}
export{File};

View file

@ -16,7 +16,7 @@ class Guild{
channels:Channel[];
channelids:{[key:string]:Channel};
snowflake:SnowFlake<Guild>;
properties
properties;
roles:Role[];
roleids:Map<SnowFlake<Role>,Role>;
prevchannel:Channel|undefined;
@ -33,30 +33,30 @@ class Guild{
static contextmenu=new Contextmenu<Guild,undefined>("guild menu");
static setupcontextmenu(){
Guild.contextmenu.addbutton("Copy Guild id",function(this:Guild){
console.log(this)
console.log(this);
navigator.clipboard.writeText(this.id);
});
Guild.contextmenu.addbutton("Mark as read",function(this:Guild){
console.log(this)
console.log(this);
this.markAsRead();
});
Guild.contextmenu.addbutton("Notifications",function(this:Guild){
console.log(this)
console.log(this);
this.setnotifcation();
});
Guild.contextmenu.addbutton("Leave guild",function(this:Guild){
this.confirmleave();
},null,function(_){
return this.properties.owner_id!==this.member.user.id
return this.properties.owner_id!==this.member.user.id;
});
Guild.contextmenu.addbutton("Delete guild",function(this:Guild){
this.confirmDelete();
},null,function(_){
return this.properties.owner_id===this.member.user.id
return this.properties.owner_id===this.member.user.id;
});
Guild.contextmenu.addbutton("Create invite",function(this:Guild){
@ -92,9 +92,9 @@ class Guild{
return;
}
if(json.stickers.length){
console.log(json.stickers,":3")
console.log(json.stickers,":3");
}
this.emojis = json.emojis
this.emojis = json.emojis;
this.owner=owner;
this.headers=this.owner.headers;
this.channels=[];
@ -107,13 +107,13 @@ class Guild{
this.message_notifications=0;
for(const roley of json.roles){
const roleh=new Role(roley,this);
this.roles.push(roleh)
this.roles.push(roleh);
this.roleids.set(roleh.snowflake,roleh);
}
if(member instanceof User){
Member.resolveMember(member,this).then(_=>{
if(_){
this.member=_
this.member=_;
}else{
console.error("Member was unable to resolve");
}
@ -121,7 +121,7 @@ class Guild{
}else{
Member.new(member,this).then(_=>{
if(_){
this.member=_
this.member=_;
}
});
}
@ -138,13 +138,12 @@ class Guild{
this.headchannels.push(thing);
}
}
}
notisetting(settings){
this.message_notifications=settings.message_notifications;
}
setnotifcation(){
let noti=this.message_notifications
let noti=this.message_notifications;
const notiselect=new Dialog(
["vdiv",
["radio","select notifications type",
@ -160,9 +159,9 @@ class Guild{
method: "PATCH",
headers: this.headers,
body: JSON.stringify({
"message_notifications": noti
})
message_notifications: noti
})
});
this.message_notifications=noti;
}]
]);
@ -200,10 +199,10 @@ class Guild{
return fetch(this.info.api+"/users/@me/guilds/"+this.snowflake,{
method: "DELETE",
headers: this.headers
})
});
}
printServers(){
let build=""
let build="";
for(const thing of this.headchannels){
build+=(thing.name+":"+thing.position)+"\n";
for(const thingy of thing.children){
@ -214,9 +213,9 @@ class Guild{
}
calculateReorder(){
let position=-1;
let build:{id:SnowFlake<Channel>,position:number|undefined,parent_id:SnowFlake<Channel>|undefined}[]=[];
const build:{id:SnowFlake<Channel>,position:number|undefined,parent_id:SnowFlake<Channel>|undefined}[]=[];
for(const thing of this.headchannels){
const thisthing:{id:SnowFlake<Channel>,position:number|undefined,parent_id:SnowFlake<Channel>|undefined}={id:thing.snowflake,position:undefined,parent_id:undefined}
const thisthing:{id:SnowFlake<Channel>,position:number|undefined,parent_id:SnowFlake<Channel>|undefined}={id: thing.snowflake,position: undefined,parent_id: undefined};
if(thing.position<=position){
thing.position=(thisthing.position=position+1);
}
@ -231,19 +230,21 @@ class Guild{
build.push(thisthing);
}
if(thing.children.length>0){
const things=thing.calculateReorder()
const things=thing.calculateReorder();
for(const thing of things){
build.push(thing);
}
}
}
console.log(build)
console.log(build);
this.printServers();
if(build.length===0){return}
if(build.length===0){
return;
}
const serverbug=false;
if(serverbug){
for(const thing of build){
console.log(build,thing)
console.log(build,thing);
fetch(this.info.api+"/guilds/"+this.snowflake+"/channels",{
method: "PATCH",
headers: this.headers,
@ -257,7 +258,6 @@ class Guild{
body: JSON.stringify(build)
});
}
}
get localuser(){
return this.owner;
@ -266,7 +266,9 @@ class Guild{
return this.owner.info;
}
sortchannels(){
this.headchannels.sort((a,b)=>{return a.position-b.position;});
this.headchannels.sort((a,b)=>{
return a.position-b.position;
});
}
generateGuildIcon(){
const divy=document.createElement("div");
@ -280,24 +282,24 @@ class Guild{
const img=document.createElement("img");
img.classList.add("pfp","servericon");
img.src=this.info.cdn+"/icons/"+this.properties.id+"/"+this.properties.icon+".png";
divy.appendChild(img)
divy.appendChild(img);
img.onclick=()=>{
console.log(this.loadGuild)
console.log(this.loadGuild);
this.loadGuild();
this.loadChannel();
}
};
Guild.contextmenu.bindContextmenu(img,this,undefined);
}else{
const div=document.createElement("div");
let build=this.properties.name.replace(/'s /g, " ").replace(/\w+/g, word => word[0]).replace(/\s/g, "");
const build=this.properties.name.replace(/'s /g, " ").replace(/\w+/g, word=>word[0]).replace(/\s/g, "");
div.textContent=build;
div.classList.add("blankserver","servericon")
divy.appendChild(div)
div.classList.add("blankserver","servericon");
divy.appendChild(div);
div.onclick=()=>{
this.loadGuild();
this.loadChannel();
}
Guild.contextmenu.bindContextmenu(div,this,undefined)
};
Guild.contextmenu.bindContextmenu(div,this,undefined);
}
return divy;
}
@ -314,14 +316,13 @@ class Guild{
function(this:HTMLInputElement){
confirmname=this.value;
}
]
,
],
["hdiv",
["button",
"",
"Yes, I'm sure",
_=>{
console.log(confirmname)
console.log(confirmname);
if(confirmname!==this.properties.name){
return;
}
@ -346,9 +347,9 @@ class Guild{
return fetch(this.info.api+"/guilds/"+this.snowflake+"/delete",{
method: "POST",
headers: this.headers,
})
});
}
unreads(html:HTMLElement|undefined=undefined){
unreads(html?:HTMLElement|undefined){
if(html){
this.html=html;
}else{
@ -357,12 +358,14 @@ class Guild{
let read=true;
for(const thing of this.channels){
if(thing.hasunreads){
console.log(thing)
console.log(thing);
read=false;
break;
}
}
if(!html){return;}
if(!html){
return;
}
if(read){
html.children[0].classList.remove("notiunread");
}else{
@ -381,10 +384,10 @@ class Guild{
return build;
}
isAdmin(){
return this.member.isAdmin()
return this.member.isAdmin();
}
async markAsRead(){
const build:{read_states:{channel_id:SnowFlake<Channel>,message_id:string|null,read_state_type:number}[]}={read_states:[]};
const build:{read_states:{channel_id:SnowFlake<Channel>,message_id:string|null|undefined,read_state_type:number}[]}={read_states: []};
for(const thing of this.channels){
if(thing.hasunreads){
build.read_states.push({channel_id: thing.snowflake,message_id: thing.lastmessageid,read_state_type: 0});
@ -398,7 +401,7 @@ class Guild{
method: "POST",
headers: this.headers,
body: JSON.stringify(build)
})
});
}
hasRole(r:Role|string){
console.log("this should run");
@ -407,20 +410,20 @@ class Guild{
}
return this.member.hasRole(r);
}
loadChannel(ID:string|undefined=undefined){
loadChannel(ID?:string|undefined){
if(ID&&this.channelids[ID]){
this.channelids[ID].getHTML();
return;
}
if(this.prevchannel){
console.log(this.prevchannel)
console.log(this.prevchannel);
this.prevchannel.getHTML();
return;
}
for(const thing of this.channels){
if(thing.children.length===0){
thing.getHTML();
return
return;
}
}
}
@ -459,26 +462,26 @@ class Guild{
["radio","select channel type",
["voice","text","announcement"],
function(e){
console.log(e)
category={"text":0,"voice":2,"announcement":5,"category":4}[e]
console.log(e);
category={text: 0,voice: 2,announcement: 5,category: 4}[e];
},
1
],
["textbox","Name of channel","",function(this:HTMLInputElement){
console.log(this)
name=this.value
console.log(this);
name=this.value;
}],
["button","","submit",function(){
console.log(name,category)
console.log(name,category);
func(name,category);
channelselect.hide();
}.bind(this)]
}]
]);
channelselect.show();
}
createcategory(){
let name="";
let category=4;
const category=4;
const channelselect=new Dialog(
["vdiv",
["textbox","Name of category","",function(this:HTMLInputElement){
@ -486,7 +489,7 @@ class Guild{
name=this.value;
}],
["button","","submit",()=>{
console.log(name,category)
console.log(name,category);
this.createChannel(name,category);
channelselect.hide();
}]
@ -524,19 +527,19 @@ class Guild{
fetch(this.info.api+"/guilds/"+this.snowflake+"/channels",{
method: "POST",
headers: this.headers,
body:JSON.stringify({name: name, type: type})
})
body: JSON.stringify({name, type})
});
}
async createRole(name:string){
const fetched=await fetch(this.info.api+"/guilds/"+this.snowflake+"roles",{
method: "POST",
headers: this.headers,
body: JSON.stringify({
name:name,
name,
color: 0,
permissions: "0"
})
})
});
const json=await fetched.json();
const role=new Role(json,this);
this.roleids.set(role.snowflake,role);
@ -560,7 +563,7 @@ class Guild{
permissions: role.permissions.allow.toString(),
unicode_emoji: role.unicode_emoji,
})
})
});
}
}
Guild.setupcontextmenu();

View file

@ -4,12 +4,12 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Jank Client</title>
<meta content="Jank Client" property="og:title" />
<meta content="A spacebar client that has DMs, replying and more" property="og:description" />
<meta content="/logo.webp" property="og:image" />
<meta content="#4b458c" data-react-helmet="true" name="theme-color" />
<link href="/style.css" rel="stylesheet" type="text/css" />
<link href="/themes.css" rel="stylesheet" type="text/css" id="lightcss"/>
<meta content="Jank Client" property="og:title">
<meta content="A spacebar client that has DMs, replying and more" property="og:description">
<meta content="/logo.webp" property="og:image">
<meta content="#4b458c" data-react-helmet="true" name="theme-color">
<link href="/style.css" rel="stylesheet">
<link href="/themes.css" rel="stylesheet" id="lightcss">
</head>
<body class="Dark-theme">

View file

@ -36,18 +36,18 @@ fetch("/instances.json").then(_=>_.json()).then((json:{name:string,description?:
const p=document.createElement("p");
if(instance.descriptionLong){
p.innerText=instance.descriptionLong;
}else{
}else if(instance.description){
p.innerText=instance.description;
}
textbox.append(p);
}
statbox.append(textbox)
statbox.append(textbox);
}
if(instance.uptime){
const stats=document.createElement("div");
stats.classList.add("flexltr");
const span=document.createElement("span");
span.innerText=`Uptime: All time: ${Math.floor(instance.uptime.alltime*100)}% This week: ${Math.floor(instance.uptime.weektime*100)}% Today: ${Math.floor(instance.uptime.daytime*100)}%`
span.innerText=`Uptime: All time: ${Math.floor(instance.uptime.alltime*100)}% This week: ${Math.floor(instance.uptime.weektime*100)}% Today: ${Math.floor(instance.uptime.daytime*100)}%`;
stats.append(span);
statbox.append(stats);
}
@ -58,7 +58,7 @@ fetch("/instances.json").then(_=>_.json()).then((json:{name:string,description?:
}else{
alert("Instance is offline, can't connect");
}
}
};
serverbox.append(div);
}
})
});

View file

@ -4,14 +4,14 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Jank Client</title>
<meta content="Jank Client" property="og:title" />
<meta content="A spacebar client that has DMs, replying and more" property="og:description" />
<meta content="/logo.webp" property="og:image" />
<meta content="#4b458c" data-react-helmet="true" name="theme-color" />
<link href="/style.css" rel="stylesheet" type="text/css" />
<link href="/themes.css" rel="stylesheet" type="text/css" id="lightcss"/>
<meta content="Jank Client" property="og:title">
<meta content="A spacebar client that has DMs, replying and more" property="og:description">
<meta content="/logo.webp" property="og:image">
<meta content="#4b458c" data-react-helmet="true" name="theme-color">
<link href="/style.css" rel="stylesheet">
<link href="/themes.css" rel="stylesheet" id="lightcss">
<link rel="manifest" href="/manifest.json" />
<link rel="manifest" href="/manifest.json">
</head>
<body class="Dark-theme">

View file

@ -7,8 +7,10 @@ import { File } from "./file.js";
(async ()=>{
async function waitforload(){
let res;
new Promise(r=>{res=r});
document.addEventListener("DOMContentLoaded", function(){
new Promise(r=>{
res=r;
});
document.addEventListener("DOMContentLoaded", ()=>{
res();
});
await res;
@ -19,7 +21,7 @@ import { File } from "./file.js";
const users=getBulkUsers();
if(!users.currentuser){
window.location.href = '/login.html';
window.location.href = "/login.html";
}
@ -27,7 +29,7 @@ import { File } from "./file.js";
const table=document.createElement("div");
for(const thing of Object.values(users.users)){
const specialuser=thing as Specialuser;
console.log(specialuser.pfpsrc)
console.log(specialuser.pfpsrc);
const userinfo=document.createElement("div");
userinfo.classList.add("flexltr","switchtable");
@ -41,8 +43,8 @@ import { File } from "./file.js";
const span=document.createElement("span");
span.textContent=specialuser.serverurls.wellknown.replace("https://","").replace("http://","");
user.append(span);
user.classList.add("userinfo")
span.classList.add("serverURL")
user.classList.add("userinfo");
span.classList.add("serverURL");
pfp.src=specialuser.pfpsrc;
pfp.classList.add("pfp");
@ -54,26 +56,25 @@ import { File } from "./file.js";
loading.classList.remove("doneloading");
loading.classList.add("loading");
thisuser=new Localuser(specialuser);
users["currentuser"]=specialuser.uid;
users.currentuser=specialuser.uid;
localStorage.setItem("userinfos",JSON.stringify(users));
thisuser.initwebsocket().then(_=>{
thisuser.loaduser();
thisuser.init();
loading.classList.add("doneloading");
loading.classList.remove("loading");
console.log("done loading")
console.log("done loading");
});
userinfo.remove();
})
});
}
{
const td=document.createElement("div");
td.classList.add("switchtable")
td.classList.add("switchtable");
td.append("Switch accounts ⇌");
td.addEventListener("click",_=>{
window.location.href="/login.html";
})
});
table.append(td);
}
table.classList.add("accountSwitcher");
@ -89,17 +90,17 @@ import { File } from "./file.js";
userinfo.addEventListener("click",_=>{
_.stopImmediatePropagation();
showAccountSwitcher();
})
});
const switchaccounts=document.getElementById("switchaccounts") as HTMLDivElement;
switchaccounts.addEventListener("click",_=>{
_.stopImmediatePropagation();
showAccountSwitcher();
})
console.log("this ran")
});
console.log("this ran");
}
let thisuser:Localuser;
try{
console.log(users.users,users.currentuser)
console.log(users.users,users.currentuser);
thisuser=new Localuser(users.users[users.currentuser]);
thisuser.initwebsocket().then(_=>{
thisuser.loaduser();
@ -107,7 +108,7 @@ import { File } from "./file.js";
const loading=document.getElementById("loading") as HTMLDivElement;
loading.classList.add("doneloading");
loading.classList.remove("loading");
console.log("done loading")
console.log("done loading");
});
}catch(e){
console.error(e);
@ -118,24 +119,28 @@ import { File } from "./file.js";
{
const menu=new Contextmenu("create rightclick");//Really should go into the localuser class, but that's a later thing
menu.addbutton("Create channel",function(){
menu.addbutton("Create channel",()=>{
if(thisuser.lookingguild){
thisuser.lookingguild.createchannels();
}
},null,_=>{return thisuser.isAdmin()})
},null,_=>{
return thisuser.isAdmin();
});
menu.addbutton("Create category",function(){
menu.addbutton("Create category",()=>{
if(thisuser.lookingguild){
thisuser.lookingguild.createcategory();
}
},null,_=>{return thisuser.isAdmin()})
menu.bindContextmenu(document.getElementById("channels") as HTMLDivElement,0,0)
},null,_=>{
return thisuser.isAdmin();
});
menu.bindContextmenu(document.getElementById("channels") as HTMLDivElement,0,0);
}
const pasteimage=document.getElementById("pasteimage") as HTMLDivElement;
let replyingto:Message|null=null;
async function enter(event){
const channel=thisuser.channelfocus
const channel=thisuser.channelfocus;
if(!channel||!thisuser.channelfocus)return;
channel.typingstart();
if(event.key === "Enter"&&!event.shiftKey){
@ -145,7 +150,7 @@ import { File } from "./file.js";
channel.editing=null;
}else{
replyingto= thisuser.channelfocus.replyingto;
let replying=replyingto;
const replying=replyingto;
if(replyingto?.div){
replyingto.div.classList.remove("replying");
}
@ -154,7 +159,7 @@ import { File } from "./file.js";
attachments: images,
embeds: [],
replyingto: replying
})
});
thisuser.channelfocus.makereplybox();
}
while(images.length!=0){
@ -162,7 +167,6 @@ import { File } from "./file.js";
pasteimage.removeChild(imageshtml.pop() as HTMLElement);
}
typebox.innerHTML="";
return;
}
}
@ -174,7 +178,7 @@ import { File } from "./file.js";
typebox.addEventListener("keydown",event=>{
if(event.key === "Enter"&&!event.shiftKey) event.preventDefault();
});
console.log(typebox)
console.log(typebox);
typebox.onclick=console.log;
/*
@ -190,14 +194,14 @@ import { File } from "./file.js";
document.addEventListener('paste', async (e) => {
document.addEventListener("paste", async e=>{
if(!e.clipboardData)return;
Array.from(e.clipboardData.files).forEach(async (f) => {
Array.from(e.clipboardData.files).forEach(async f=>{
const file=File.initFromBlob(f);
e.preventDefault();
const html=file.upHTML(images,f);
pasteimage.appendChild(html);
images.push(f)
images.push(f);
imageshtml.push(html);
});
});
@ -214,12 +218,12 @@ import { File } from "./file.js";
((document.getElementById("channels") as HTMLDivElement).parentNode as HTMLElement).classList.add("collapse");
(document.getElementById("servertd") as HTMLDivElement).classList.add("collapse");
(document.getElementById("servers") as HTMLDivElement).classList.add("collapse");
}
};
(document.getElementById("mobileback") as HTMLDivElement).textContent="#";
(document.getElementById("mobileback") as HTMLDivElement).onclick=()=>{
((document.getElementById("channels") as HTMLDivElement).parentNode as HTMLElement).classList.remove("collapse");
(document.getElementById("servertd") as HTMLDivElement).classList.remove("collapse");
(document.getElementById("servers") as HTMLDivElement).classList.remove("collapse");
};
}
}
})()
})();

View file

@ -21,7 +21,7 @@ class InfiniteScroller{
div.classList.add("messagecontainer");
//div.classList.add("flexttb")
const scroll=document.createElement("div");
scroll.classList.add("flexttb","scroller")
scroll.classList.add("flexttb","scroller");
div.appendChild(scroll);
this.div=div;
//this.interval=setInterval(this.updatestuff.bind(this,true),100);
@ -29,14 +29,14 @@ class InfiniteScroller{
this.scroll=scroll;
this.div.addEventListener("scroll",_=>{
if(this.scroll)this.scrollTop=this.scroll.scrollTop;
this.watchForChange()
this.watchForChange();
});
this.scroll.addEventListener("scroll",_=>{
if(null===this.timeout){
if(this.timeout===null){
this.timeout=setTimeout(this.updatestuff.bind(this),300);
}
this.watchForChange()
this.watchForChange();
});
{
let oldheight=0;
@ -52,11 +52,11 @@ class InfiniteScroller{
}
new ResizeObserver(this.watchForChange.bind(this)).observe(scroll);
await this.firstElement(initialId)
await this.firstElement(initialId);
this.updatestuff();
await this.watchForChange().then(_=>{
this.updatestuff();
})
});
return div;
}
scrollBottom:number;
@ -72,13 +72,11 @@ class InfiniteScroller{
this.averageheight=60;
}
this.scrollTop=this.scroll.scrollTop;
if(!this.scrollBottom){
if(!await this.watchForChange()){
if(!this.scrollBottom && !await this.watchForChange()){
this.reachesBottom();
}
}
if(!this.scrollTop){
await this.watchForChange()
await this.watchForChange();
}
this.needsupdate=false;
//this.watchForChange();
@ -102,7 +100,7 @@ class InfiniteScroller{
if(this.scroll&&scrollBottom<30){
this.scroll.scrollTop=this.scroll.scrollHeight+20;
}
}
};
}
private async watchForTop(already=false,fragement=new DocumentFragment()):Promise<boolean>{
if(!this.scroll)return false;
@ -129,11 +127,9 @@ class InfiniteScroller{
fragement.prepend(html);
this.HTMLElements.unshift([html,nextid]);
this.scrollTop+=this.averageheight;
};
}
}
if(this.scrollTop>this.maxDist){
const html=this.HTMLElements.shift();
if(html){
again=true;
@ -161,7 +157,6 @@ class InfiniteScroller{
let again=false;
const scrollBottom = this.scrollBottom;
if(scrollBottom<(already?this.fillDist:this.minDist)){
let nextid:string|undefined;
const lastelm=this.HTMLElements.at(-1);
if(lastelm){
@ -175,11 +170,9 @@ class InfiniteScroller{
fragement.appendChild(html);
this.HTMLElements.push([html,nextid]);
this.scrollBottom+=this.averageheight;
};
}
}
if(scrollBottom>this.maxDist){
const html=this.HTMLElements.pop();
if(html){
await this.destroyFromID(html[1]);
@ -213,23 +206,24 @@ class InfiniteScroller{
}else{
this.watchtime=false;
this.currrunning=true;
}
this.changePromise=new Promise<boolean>(async res=>{
try{
try{
if(!this.div){res(false);return false}
if(!this.div){
res(false);return false;
}
const out=await Promise.allSettled([this.watchForTop(),this.watchForBottom()]) as {value:boolean}[];
const changed=(out[0].value||out[1].value);
if(null===this.timeout&&changed){
if(this.timeout===null&&changed){
this.timeout=setTimeout(this.updatestuff.bind(this),300);
}
if(!this.currrunning){console.error("something really bad happened")}
res(!!changed);
return !!changed;
if(!this.currrunning){
console.error("something really bad happened");
}
res(Boolean(changed));
return Boolean(changed);
}catch(e){
console.error(e);
}
@ -238,22 +232,18 @@ class InfiniteScroller{
}catch(e){
throw e;
}finally{
setTimeout(_=>{
this.changePromise=undefined;
this.currrunning=false;
if(this.watchtime){
this.watchForChange();
}
},300)
},300);
}
})
});
return await this.changePromise;
}
async focus(id:string,flash=true){
let element:HTMLElement|undefined;
for(const thing of this.HTMLElements){
if(thing[1]===id){
@ -262,7 +252,6 @@ class InfiniteScroller{
}
console.log(id,element,this.HTMLElements.length,":3");
if(element){
if(flash){
element.scrollIntoView({
behavior: "smooth",

View file

@ -3,12 +3,12 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Jank Client</title>
<meta content="Invite" property="og:title" />
<meta content="You shouldn't see this, but this is an invite URL" property="og:description" />
<meta content="/logo.webp" property="og:image" />
<meta content="#4b458c" data-react-helmet="true" name="theme-color" />
<link href="/style.css" rel="stylesheet" type="text/css" />
<link href="/themes.css" rel="stylesheet" type="text/css" id="lightcss"/>
<meta content="Invite" property="og:title">
<meta content="You shouldn't see this, but this is an invite URL" property="og:description">
<meta content="/logo.webp" property="og:image">
<meta content="#4b458c" data-react-helmet="true" name="theme-color">
<link href="/style.css" rel="stylesheet">
<link href="/themes.css" rel="stylesheet" id="lightcss">
</head>
<div>
<div id="invitebody">

View file

@ -4,33 +4,32 @@ import {getBulkUsers, Specialuser, getapiurls} from "./login.js";
const well=new URLSearchParams(window.location.search).get("instance");
const joinable:Specialuser[]=[];
for(const thing in users.users){
const user:Specialuser = users.users[thing]
const user:Specialuser = users.users[thing];
if(user.serverurls.wellknown.includes(well)){
joinable.push(user);
}
console.log(users.users[thing]);
}
let urls:{api:string,cdn:string};
if(!joinable.length){
if(!joinable.length&&well){
const out=await getapiurls(well);
if(out){
urls=out;
for(const thing in users.users){
const user:Specialuser = users.users[thing]
const user:Specialuser = users.users[thing];
if(user.serverurls.api.includes(out.api)){
joinable.push(user);
}
console.log(users.users[thing]);
}
}else{
throw Error("someone needs to handle the case where the servers don't exist")
throw new Error("someone needs to handle the case where the servers don't exist");
}
}else{
urls=joinable[0].serverurls;
}
if(!joinable.length){
document.getElementById("AcceptInvite").textContent="Create an account to accept the invite"
document.getElementById("AcceptInvite").textContent="Create an account to accept the invite";
}
const code=window.location.pathname.split("/")[2];
let guildinfo;
@ -54,13 +53,12 @@ import {getBulkUsers, Specialuser, getapiurls} from "./login.js";
div.classList.add("inviteGuild");
document.getElementById("inviteimg").append(div);
}
})
});
function showAccounts(){
const table=document.createElement("dialog");
for(const thing of Object.values(joinable)){
const specialuser=thing as Specialuser;
console.log(specialuser.pfpsrc)
console.log(specialuser.pfpsrc);
const userinfo=document.createElement("div");
userinfo.classList.add("flexltr","switchtable");
@ -74,8 +72,8 @@ import {getBulkUsers, Specialuser, getapiurls} from "./login.js";
const span=document.createElement("span");
span.textContent=specialuser.serverurls.wellknown.replace("https://","").replace("http://","");
user.append(span);
user.classList.add("userinfo")
span.classList.add("serverURL")
user.classList.add("userinfo");
span.classList.add("serverURL");
pfp.src=specialuser.pfpsrc;
pfp.classList.add("pfp");
@ -88,24 +86,24 @@ import {getBulkUsers, Specialuser, getapiurls} from "./login.js";
Authorization: thing.token
}
}).then(_=>{
users["currentuser"]=specialuser.uid;
users.currentuser=specialuser.uid;
localStorage.setItem("userinfos",JSON.stringify(users));
window.location.href="/channels/"+guildinfo.id;
})
})
});
});
}
{
const td=document.createElement("div");
td.classList.add("switchtable")
td.classList.add("switchtable");
td.append("Login or create an account ⇌");
td.addEventListener("click",_=>{
const l=new URLSearchParams("?")
const l=new URLSearchParams("?");
l.set("goback",window.location.href);
l.set("instance",well);
window.location.href="/login?"+l.toString();
})
});
if(!joinable.length){
const l=new URLSearchParams("?")
const l=new URLSearchParams("?");
l.set("goback",window.location.href);
l.set("instance",well);
window.location.href="/login?"+l.toString();

View file

@ -3,12 +3,12 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Jank Client</title>
<meta content="Jank Client" property="og:title" />
<meta content="A spacebar client that has DMs, replying and more" property="og:description" />
<meta content="/logo.webp" property="og:image" />
<meta content="#4b458c" data-react-helmet="true" name="theme-color" />
<link href="/style.css" rel="stylesheet" type="text/css" />
<link href="/themes.css" rel="stylesheet" type="text/css" id="lightcss"/>
<meta content="Jank Client" property="og:title">
<meta content="A spacebar client that has DMs, replying and more" property="og:description">
<meta content="/logo.webp" property="og:image">
<meta content="#4b458c" data-react-helmet="true" name="theme-color">
<link href="/style.css" rel="stylesheet">
<link href="/themes.css" rel="stylesheet" id="lightcss">
</head>
<div id="logindiv">
<h1>Login</h1><br>

View file

@ -12,25 +12,25 @@ function setTheme(){
}
setTheme();
function getBulkUsers(){
const json=getBulkInfo()
const json=getBulkInfo();
for(const thing in json.users){
json.users[thing]=new Specialuser(json.users[thing]);
}
return json;
}
function trimswitcher(){
const json=getBulkInfo()
const json=getBulkInfo();
const map=new Map();
for(const thing in json.users){
const user=json.users[thing];
let wellknown=user.serverurls.wellknown;
if(wellknown[wellknown.length-1]!=="/"){
if(wellknown.at(-1)!=="/"){
wellknown+="/";
}
wellknown+=user.username;
if(map.has(wellknown)){
const otheruser=map.get(wellknown);
if(otheruser[1].serverurls.wellknown[otheruser[1].serverurls.wellknown.length-1]==="/"){
if(otheruser[1].serverurls.wellknown.at(-1)==="/"){
delete json.users[otheruser[0]];
map.set(wellknown,[thing,user]);
}else{
@ -41,7 +41,7 @@ function trimswitcher(){
}
}
for(const thing in json.users){
if(thing[thing.length-1]==="/"){
if(thing.at(-1)==="/"){
const user=json.users[thing];
delete json.users[thing];
json.users[thing.slice(0, -1)]=user;
@ -75,18 +75,18 @@ function setDefaults(){
if(userinfos.accent_color===undefined){
userinfos.accent_color="#242443";
}
document.documentElement.style.setProperty('--accent-color', userinfos.accent_color);
document.documentElement.style.setProperty("--accent-color", userinfos.accent_color);
if(userinfos.preferences===undefined){
userinfos.preferences={
theme: "Dark",
notifications: false,
notisound: "three",
}
};
}
if(userinfos.preferences&&(userinfos.preferences.notisound===undefined)){
userinfos.preferences.notisound="three";
}
localStorage.setItem("userinfos",JSON.stringify(userinfos))
localStorage.setItem("userinfos",JSON.stringify(userinfos));
}
setDefaults();
class Specialuser{
@ -104,9 +104,9 @@ class Specialuser{
apistring=apistring.replace(/\/(v\d+\/?)?$/, "")+"/v9";
this.serverurls.api=apistring;
this.serverurls.cdn=new URL(json.serverurls.cdn).toString().replace(/\/$/,"");
this.serverurls.gateway=new URL(json.serverurls.gateway).toString().replace(/\/$/,"");;
this.serverurls.wellknown=new URL(json.serverurls.wellknown).toString().replace(/\/$/,"");;
this.serverurls.login=new URL(json.serverurls.login).toString().replace(/\/$/,"");;
this.serverurls.gateway=new URL(json.serverurls.gateway).toString().replace(/\/$/,"");
this.serverurls.wellknown=new URL(json.serverurls.wellknown).toString().replace(/\/$/,"");
this.serverurls.login=new URL(json.serverurls.login).toString().replace(/\/$/,"");
this.email=json.email;
this.token=json.token;
this.loggedin=json.loggedin;
@ -116,7 +116,7 @@ class Specialuser{
}
}
set pfpsrc(e){
console.log("this ran fr")
console.log("this ran fr");
this.json.pfpsrc=e;
this.updateLocal();
}
@ -162,7 +162,7 @@ async function getapiurls(str:string):Promise<{api:string,cdn:string,gateway:str
if(val){
str=val;
}else{
const val=stringURLsMap.get(str)
const val=stringURLsMap.get(str);
if(val){
const responce=await fetch(val.api+val.api.endsWith("/")?"":"/"+"ping");
if(responce.ok){
@ -172,25 +172,23 @@ async function getapiurls(str:string):Promise<{api:string,cdn:string,gateway:str
val.login=val.api;
return val as {wellknown:string,api:string,cdn:string,gateway:string,login:string};
}
}
}
}
}
if(str[str.length-1]!=="/"){
str+="/"
if(str.at(-1)!=="/"){
str+="/";
}
let api:string;
try{
const info=await fetch(`${str}/.well-known/spacebar`).then((x) => x.json());
const info=await fetch(`${str}/.well-known/spacebar`).then(x=>x.json());
api=info.api;
}catch{
return false
return false;
}
const url = new URL(api);
try{
const info=await fetch(`${api}${url.pathname.includes("api") ? "" : "api"}/policies/instance/domains`).then((x) => x.json());
const info=await fetch(`${api}${url.pathname.includes("api") ? "" : "api"}/policies/instance/domains`).then(x=>x.json());
return{
api: info.apiEndpoint,
gateway: info.gateway,
@ -199,7 +197,7 @@ async function getapiurls(str:string):Promise<{api:string,cdn:string,gateway:str
login: url.toString()
};
}catch{
const val=stringURLsMap.get(str)
const val=stringURLsMap.get(str);
if(val){
const responce=await fetch(val.api+val.api.endsWith("/")?"":"/"+"ping");
if(responce.ok){
@ -209,12 +207,10 @@ async function getapiurls(str:string):Promise<{api:string,cdn:string,gateway:str
val.login=val.api;
return val as {wellknown:string,api:string,cdn:string,gateway:string,login:string};
}
}
}
return false;
}
}
async function checkInstance(e:string){
const verify=document.getElementById("verify");
@ -224,39 +220,40 @@ async function checkInstance(e:string){
if(instanceinfo){
instanceinfo.value=(instancein as HTMLInputElement).value;
localStorage.setItem("instanceinfo",JSON.stringify(instanceinfo));
verify.textContent="Instance is all good"
if(checkInstance["alt"]){checkInstance["alt"]();}
verify.textContent="Instance is all good";
if(checkInstance.alt){
checkInstance.alt();
}
setTimeout(_=>{
console.log(verify.textContent)
console.log(verify.textContent);
verify.textContent="";
},3000);
}else{
verify.textContent="Invalid Instance, try again"
verify.textContent="Invalid Instance, try again";
}
}catch(e){
console.log("catch")
verify.textContent="Invalid Instance, try again"
}catch{
console.log("catch");
verify.textContent="Invalid Instance, try again";
}
}
if(instancein){
console.log(instancein)
console.log(instancein);
instancein.addEventListener("keydown",e=>{
const verify=document.getElementById("verify");
verify.textContent="Waiting to check Instance"
verify.textContent="Waiting to check Instance";
clearTimeout(timeout);
timeout=setTimeout(checkInstance,1000);
});
if(localStorage.getItem("instanceinfo")){
const json=JSON.parse(localStorage.getItem("instanceinfo"));
if(json.value){
(instancein as HTMLInputElement).value=json.value
(instancein as HTMLInputElement).value=json.value;
}else{
(instancein as HTMLInputElement).value=json.wellknown
(instancein as HTMLInputElement).value=json.wellknown;
}
}else{
checkInstance("https://spacebar.chat/");
}
}
async function login(username:string, password:string, captcha:string){
@ -266,29 +263,28 @@ async function login(username:string, password:string, captcha:string){
const options={
method: "POST",
body: JSON.stringify({
"login": username,
"password": password,
"undelete":false,
"captcha_key":captcha
login: username,
password,
undelete: false,
captcha_key: captcha
}),
headers: {
"Content-type": "application/json; charset=UTF-8",
}}
}};
try{
const info=JSON.parse(localStorage.getItem("instanceinfo"));
const api=info.login+(info.login.startsWith("/")?"/":"");
return await fetch(api+'/auth/login',options).then(response=>response.json())
.then((response) => {
console.log(response,response.message)
if("Invalid Form Body"===response.message){
return await fetch(api+"/auth/login",options).then(response=>response.json())
.then(response=>{
console.log(response,response.message);
if(response.message==="Invalid Form Body"){
return response.errors.login._errors[0].message;
console.log("test")
console.log("test");
}
//this.serverurls||!this.email||!this.token
console.log(response);
if(response.captcha_sitekey){
const capt=document.getElementById("h-captcha");
if(!capt.children.length){
const capty=document.createElement("div");
@ -302,12 +298,13 @@ async function login(username:string, password:string, captcha:string){
}else{
eval("hcaptcha.reset()");
}
return;
}else{
console.log(response);
if(response.ticket){
let onetimecode="";
new Dialog(["vdiv",["title","2FA code:"],["textbox","","",function(this:HTMLInputElement){onetimecode=this.value}],["button","","Submit",function(){
new Dialog(["vdiv",["title","2FA code:"],["textbox","","",function(this:HTMLInputElement){
onetimecode=this.value;
}],["button","","Submit",function(){
fetch(api+"/auth/mfa/totp",{
method: "POST",
headers: {
@ -319,7 +316,7 @@ async function login(username:string, password:string, captcha:string){
})
}).then(r=>r.json()).then(response=>{
if(response.message){
alert(response.message)
alert(response.message);
}else{
console.warn(response);
if(!response.token)return;
@ -328,10 +325,10 @@ async function login(username:string, password:string, captcha:string){
if(redir){
window.location.href = redir;
}else{
window.location.href = '/channels/@me';
window.location.href = "/channels/@me";
}
}
})
});
}]]).show();
}else{
console.warn(response);
@ -341,21 +338,20 @@ async function login(username:string, password:string, captcha:string){
if(redir){
window.location.href = redir;
}else{
window.location.href = '/channels/@me';
window.location.href = "/channels/@me";
}
return"";
}
}
})
});
}catch(error){
console.error('Error:', error);
};
console.error("Error:", error);
}
}
async function check(e){
e.preventDefault();
let h=await login(e.srcElement[1].value,e.srcElement[2].value,e.srcElement[3].value);
const h=await login(e.srcElement[1].value,e.srcElement[2].value,e.srcElement[3].value);
document.getElementById("wrong").textContent=h;
console.log(h);
}
@ -400,7 +396,7 @@ if(switchurl){
}
export{checkInstance};
trimswitcher();
export {mobile, getBulkUsers,getBulkInfo,setTheme,Specialuser,getapiurls,adduser}
export{mobile, getBulkUsers,getBulkInfo,setTheme,Specialuser,getapiurls,adduser};
const datalist=document.getElementById("instances");
console.warn(datalist);
@ -435,5 +431,5 @@ if(datalist){
datalist.append(option);
}
checkInstance("");
})
});
}

View file

@ -30,7 +30,7 @@ class MarkDown{
return this.makeHTML().textContent;
}
makeHTML({keep=this.keep,stdsize=this.stdsize}={}){
return this.markdown(this.txt,{keep:keep,stdsize:stdsize});
return this.markdown(this.txt,{keep,stdsize});
}
markdown(text : string|string[],{keep=false,stdsize=false} = {}){
let txt : string[];
@ -49,7 +49,6 @@ class MarkDown{
span.append(current);
current=document.createElement("span");
}
}
for(let i=0;i<txt.length;i++){
if(txt[i]==="\n"||i===0){
@ -103,7 +102,7 @@ class MarkDown{
if(keep){
element.append(keepys);
}
element.appendChild(this.markdown(build,{keep:keep,stdsize:stdsize}));
element.appendChild(this.markdown(build,{keep,stdsize}));
span.append(element);
}finally{
i-=1;
@ -116,7 +115,6 @@ class MarkDown{
}
}
if(txt[i]==="\n"){
if(!stdsize){
appendcurrent();
span.append(document.createElement("br"));
@ -175,11 +173,11 @@ class MarkDown{
span.appendChild(samp);
}else{
const pre=document.createElement("pre");
if(build[build.length-1]==="\n"){
if(build.at(-1)==="\n"){
build=build.substring(0,build.length-1);
}
if(txt[i]==="\n"){
i++
i++;
}
pre.textContent=build;
span.appendChild(pre);
@ -201,7 +199,6 @@ class MarkDown{
let find=0;
let j=i+count;
for(;txt[j]!==undefined&&find!==count;j++){
if(txt[j]==="*"){
find++;
}else{
@ -219,26 +216,38 @@ class MarkDown{
const stars="*".repeat(count);
if(count===1){
const i=document.createElement("i");
if(keep){i.append(stars)}
i.appendChild(this.markdown(build,{keep:keep,stdsize:stdsize}));
if(keep){i.append(stars)}
if(keep){
i.append(stars);
}
i.appendChild(this.markdown(build,{keep,stdsize}));
if(keep){
i.append(stars);
}
span.appendChild(i);
}else if(count===2){
const b=document.createElement("b");
if(keep){b.append(stars)}
b.appendChild(this.markdown(build,{keep:keep,stdsize:stdsize}));
if(keep){b.append(stars)}
if(keep){
b.append(stars);
}
b.appendChild(this.markdown(build,{keep,stdsize}));
if(keep){
b.append(stars);
}
span.appendChild(b);
}else{
const b=document.createElement("b");
const i=document.createElement("i");
if(keep){b.append(stars)}
b.appendChild(this.markdown(build,{keep:keep,stdsize:stdsize}));
if(keep){b.append(stars)}
if(keep){
b.append(stars);
}
b.appendChild(this.markdown(build,{keep,stdsize}));
if(keep){
b.append(stars);
}
i.appendChild(b);
span.appendChild(i);
}
i--
i--;
continue;
}
}
@ -255,7 +264,6 @@ class MarkDown{
let find=0;
let j=i+count;
for(;txt[j]!==undefined&&find!==count;j++){
if(txt[j]==="_"){
find++;
}else{
@ -272,23 +280,35 @@ class MarkDown{
const underscores="_".repeat(count);
if(count===1){
const i=document.createElement("i");
if(keep){i.append(underscores)}
i.appendChild(this.markdown(build,{keep:keep,stdsize:stdsize}));
if(keep){i.append(underscores)}
if(keep){
i.append(underscores);
}
i.appendChild(this.markdown(build,{keep,stdsize}));
if(keep){
i.append(underscores);
}
span.appendChild(i);
}else if(count===2){
const u=document.createElement("u");
if(keep){u.append(underscores)}
u.appendChild(this.markdown(build,{keep:keep,stdsize:stdsize}));
if(keep){u.append(underscores)}
if(keep){
u.append(underscores);
}
u.appendChild(this.markdown(build,{keep,stdsize}));
if(keep){
u.append(underscores);
}
span.appendChild(u);
}else{
const u=document.createElement("u");
const i=document.createElement("i");
if(keep){i.append(underscores)}
i.appendChild(this.markdown(build,{keep:keep,stdsize:stdsize}));
if(keep){i.append(underscores)}
u.appendChild(i)
if(keep){
i.append(underscores);
}
i.appendChild(this.markdown(build,{keep,stdsize}));
if(keep){
i.append(underscores);
}
u.appendChild(i);
span.appendChild(u);
}
i--;
@ -297,7 +317,7 @@ class MarkDown{
}
if(txt[i]==="~"&&txt[i+1]==="~"){
let count=2;
const count=2;
let build:string[]=[];
let find=0;
let j=i+2;
@ -318,16 +338,20 @@ class MarkDown{
const tildes="~~";
if(count===2){
const s=document.createElement("s");
if(keep){s.append(tildes)}
s.appendChild(this.markdown(build,{keep:keep,stdsize:stdsize}));
if(keep){s.append(tildes)}
if(keep){
s.append(tildes);
}
s.appendChild(this.markdown(build,{keep,stdsize}));
if(keep){
s.append(tildes);
}
span.appendChild(s);
}
continue;
}
}
if(txt[i]==="|"&&txt[i+1]==="|"){
let count=2;
const count=2;
let build:string[]=[];
let find=0;
let j=i+2;
@ -348,11 +372,15 @@ class MarkDown{
const pipes="||";
if(count===2){
const j=document.createElement("j");
if(keep){j.append(pipes)}
j.appendChild(this.markdown(build,{keep:keep,stdsize:stdsize}));
if(keep){
j.append(pipes);
}
j.appendChild(this.markdown(build,{keep,stdsize}));
j.classList.add("spoiler");
j.onclick=MarkDown.unspoil;
if(keep){j.append(pipes)}
if(keep){
j.append(pipes);
}
span.appendChild(j);
}
continue;
@ -419,8 +447,8 @@ class MarkDown{
appendcurrent();
i=j;
const isEmojiOnly = txt.join("").trim()===buildjoin.trim();
const owner=(this.owner instanceof Channel)?this.owner.guild:this.owner
const emoji=new Emoji({name:buildjoin,id:parts[2],animated:!!parts[1]},owner);
const owner=(this.owner instanceof Channel)?this.owner.guild:this.owner;
const emoji=new Emoji({name: buildjoin,id: parts[2],animated: Boolean(parts[1])},owner);
span.appendChild(emoji.getHTML(isEmojiOnly));
continue;
@ -442,7 +470,7 @@ class MarkDown{
partsFound++;
}else{
break;
};
}
}else if(partsFound === 1 && txt[j] === ")"){
partsFound++;
break;
@ -492,19 +520,19 @@ class MarkDown{
};
box.onpaste=_=>{
if(!_.clipboardData)return;
console.log(_.clipboardData.types)
console.log(_.clipboardData.types);
const data=_.clipboardData.getData("text");
document.execCommand('insertHTML', false, data);
document.execCommand("insertHTML", false, data);
_.preventDefault();
if(!box.onkeyup)return;
box.onkeyup(new KeyboardEvent("_"))
}
box.onkeyup(new KeyboardEvent("_"));
};
}
boxupdate(box:HTMLElement){
const restore = saveCaretPosition(box);
box.innerHTML="";
box.append(this.makeHTML({keep:true}))
box.append(this.makeHTML({keep: true}));
if(restore){
restore();
}
@ -519,9 +547,7 @@ class MarkDown{
let build="";
for(const thing of element.childNodes){
if(thing instanceof Text){
const text=thing.textContent;
build+=text;
continue;
@ -537,34 +563,33 @@ class MarkDown{
//solution from https://stackoverflow.com/questions/4576694/saving-and-restoring-caret-position-for-contenteditable-div
function saveCaretPosition(context){
var selection = window.getSelection();
const selection = window.getSelection();
if(!selection)return;
var range = selection.getRangeAt(0);
const range = selection.getRangeAt(0);
range.setStart(context, 0);
var len = range.toString().length;
const len = range.toString().length;
return function restore(){
if(!selection)return;
var pos = getTextNodeAtPosition(context, len);
const pos = getTextNodeAtPosition(context, len);
selection.removeAllRanges();
var range = new Range();
const range = new Range();
range.setStart(pos.node ,pos.position);
selection.addRange(range);
}
};
}
function getTextNodeAtPosition(root, index){
const NODE_TYPE = NodeFilter.SHOW_TEXT;
var treeWalker = document.createTreeWalker(root, NODE_TYPE, function next(elem) {
const treeWalker = document.createTreeWalker(root, NODE_TYPE, elem=>{
if(!elem.textContent)return 0;
if(index > elem.textContent.length){
index -= elem.textContent.length;
return NodeFilter.FILTER_REJECT
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_ACCEPT;
});
var c = treeWalker.nextNode();
const c = treeWalker.nextNode();
return{
node: c? c: root,
position: index

View file

@ -23,11 +23,14 @@ class Member{
}
for(const thing of Object.keys(memberjson)){
if(thing==="guild"){continue}
if(thing==="owner"){continue}
if(thing==="guild"){
continue;
}
if(thing==="owner"){
continue;
}
if(thing==="roles"){
for(const strrole of memberjson["roles"]){
for(const strrole of memberjson.roles){
const role=SnowFlake.getSnowFlakeFromID(strrole,Role).getObject();
this.roles.push(role);
}
@ -37,10 +40,7 @@ class Member{
}
if(this.localuser.userMap.has(this?.id)){
this.user=this.localuser.userMap.get(this?.id) as User;
return;
}
}
get guild(){
return this.owner;
@ -54,18 +54,18 @@ class Member{
static async new(memberjson:memberjson,owner:Guild):Promise<Member|undefined>{
let user:User;
if(owner.localuser.userMap.has(memberjson.id)){
user=owner.localuser.userMap.get(memberjson.id);
user=owner.localuser.userMap.get(memberjson.id) as User;
}else if(memberjson.user){
user=new User(memberjson.user,owner.localuser);
}else{
throw new Error("missing user object of this member");
}
if(user.members.has(owner)){
let memb=user.members.get(owner)
let memb=user.members.get(owner);
if(memb===undefined){
memb=new Member(memberjson,owner);
user.members.set(owner,memb);
return memb
return memb;
}else if(memb instanceof Promise){
return await memb;//I should do something else, though for now this is "good enough"
}else{
@ -85,7 +85,6 @@ class Member{
const membjson=await membpromise;
if(membjson===undefined){
res(undefined);
return undefined;
}else{
const member=new Member(membjson,guild);
const map=guild.localuser.presences;
@ -94,13 +93,13 @@ class Member{
res(member);
return member;
}
})
});
user.members.set(guild,promise);
}
if(maybe instanceof Promise){
return await maybe;
}else{
return maybe
return maybe;
}
}
public getPresence(presence:presencejson|undefined){
@ -110,7 +109,7 @@ class Member{
* @todo
*/
highInfo(){
fetch(this.info.api+"/users/"+this.id+"/profile?with_mutual_guilds=true&with_mutual_friends_count=true&guild_id="+this.guild.id,{headers:this.guild.headers})
fetch(this.info.api+"/users/"+this.id+"/profile?with_mutual_guilds=true&with_mutual_friends_count=true&guild_id="+this.guild.id,{headers: this.guild.headers});
}
hasRole(ID:string){
console.log(this.roles,ID);
@ -140,7 +139,9 @@ class Member{
}
bind(html:HTMLElement){
if(html.tagName==="SPAN"){
if(!this) {return};
if(!this){
return;
}
/*
if(this.error){
@ -158,7 +159,7 @@ class Member{
return this.nick||this.user.username;
}
kick(){
let reason=""
let reason="";
const menu=new Dialog(["vdiv",
["title","Kick "+this.name+" from "+this.guild.properties.name],
["textbox","Reason:","",function(e:Event){
@ -173,15 +174,15 @@ class Member{
}
kickAPI(reason:string){
const headers=structuredClone(this.guild.headers);
headers["x-audit-log-reason"]=reason
headers["x-audit-log-reason"]=reason;
fetch(`${this.info.api}/guilds/${this.guild.id}/members/${this.id}`,{
method: "DELETE",
headers,
})
});
}
ban(){
let reason=""
let reason="";
const menu=new Dialog(["vdiv",
["title","Ban "+this.name+" from "+this.guild.properties.name],
["textbox","Reason:","",function(e:Event){
@ -196,12 +197,12 @@ class Member{
}
banAPI(reason:string){
const headers=structuredClone(this.guild.headers);
headers["x-audit-log-reason"]=reason
headers["x-audit-log-reason"]=reason;
fetch(`${this.info.api}/guilds/${this.guild.id}/bans/${this.id}`,{
method: "PUT",
headers
})
});
}
hasPermission(name:string):boolean{
if(this.isAdmin()){

View file

@ -47,7 +47,9 @@ class Message{
return this.snowflake.id;
}
static setup(){
this.del=new Promise(_=>{this.resolve=_});
this.del=new Promise(_=>{
this.resolve=_;
});
Message.setupcmenu();
}
static setupcmenu(){
@ -68,17 +70,16 @@ class Message{
Message.contextmenu.addbutton("Edit",function(this:Message){
this.channel.editing=this;
const markdown=(document.getElementById("typebox") as HTMLDivElement)["markdown"] as MarkDown;
markdown.txt=this.content.rawString.split('');
markdown.txt=this.content.rawString.split("");
markdown.boxupdate(document.getElementById("typebox") as HTMLDivElement);
},null,function(){
return this.author.id===this.localuser.user.id
return this.author.id===this.localuser.user.id;
});
Message.contextmenu.addbutton("Delete message",function(this:Message){
this.delete();
},null,function(){
return this.canDelete()
})
return this.canDelete();
});
}
constructor(messagejson:messagejson,owner:Channel){
this.owner=owner;
@ -87,14 +88,12 @@ class Message{
this.owner.messages.set(this.id,this);
}
reactionToggle(emoji:string|Emoji){
let remove = false
let remove = false;
for(const thing of this.reactions){
if(thing.emoji.name === emoji){
remove = thing.me
break
remove = thing.me;
break;
}
}
let reactiontxt:string;
if(emoji instanceof Emoji){
@ -105,7 +104,7 @@ class Message{
fetch(`${this.info.api}/channels/${this.channel.id}/messages/${this.id}/reactions/${reactiontxt}/@me`, {
method: remove ? "DELETE" : "PUT",
headers: this.headers
})
});
}
giveData(messagejson:messagejson){
const func=this.channel.infinite.snapBottom();
@ -130,7 +129,7 @@ class Message{
}else if(thing ==="embeds"){
this.embeds=[];
for(const thing in messagejson.embeds){
console.log(thing,messagejson.embeds)
console.log(thing,messagejson.embeds);
this.embeds[thing]=new Embed(messagejson.embeds[thing],this);
}
continue;
@ -148,10 +147,10 @@ class Message{
if(!this.member&&this.guild.id!=="@me"){
this.author.resolvemember(this.guild).then(_=>{
this.member=_;
})
});
}
if(this.mentions.length||this.mention_roles.length){//currently mention_roles isn't implemented on the spacebar servers
console.log(this.mentions,this.mention_roles)
console.log(this.mentions,this.mention_roles);
}
if(this.mentionsuser(this.localuser.user)){
console.log(this);
@ -187,7 +186,7 @@ class Message{
this.div.remove();
this.div=undefined;
}catch(e){
console.error(e)
console.error(e);
}
}
mentionsuser(userd:User|Member){
@ -200,7 +199,7 @@ class Message{
getimages(){
const build:File[]=[];
for(const thing of this.attachments){
if(thing.content_type.startsWith('image/')){
if(thing.content_type.startsWith("image/")){
build.push(thing);
}
}
@ -210,14 +209,14 @@ class Message{
return await fetch(this.info.api+"/channels/"+this.channel.snowflake+"/messages/"+this.id,{
method: "PATCH",
headers: this.headers,
body:JSON.stringify({content:content})
body: JSON.stringify({content})
});
}
delete(){
fetch(`${this.info.api}/channels/${this.channel.snowflake}/messages/${this.id}`,{
headers: this.headers,
method: "DELETE",
})
});
}
deleteEvent(){
if(this.div){
@ -227,10 +226,10 @@ class Message{
const prev=this.channel.idToPrev.get(this.id);
const next=this.channel.idToNext.get(this.id);
if(prev){
this.channel.idToPrev.delete(this.id)
this.channel.idToPrev.delete(this.id);
}
if(next){
this.channel.idToNext.delete(this.id)
this.channel.idToNext.delete(this.id);
}
if(prev&&next){
this.channel.idToPrev.set(next,prev);
@ -265,7 +264,7 @@ class Message{
this.generateMessage();
}
}
generateMessage(premessage:Message|undefined=undefined,ignoredblock=false){
generateMessage(premessage?:Message|undefined,ignoredblock=false){
if(!this.div)return;
if(!premessage){
premessage=this.channel.messages.get(this.channel.idToPrev.get(this.id) as string);
@ -275,38 +274,38 @@ class Message{
div.classList.add("replying");
}
div.innerHTML="";
const build = document.createElement('div');
const build = document.createElement("div");
build.classList.add("flexltr","message");
div.classList.remove("zeroheight")
div.classList.remove("zeroheight");
if(this.author.relationshipType===2){
if(ignoredblock){
if(premessage?.author!==this.author){
const span=document.createElement("span");
span.textContent=`You have this user blocked, click to hide these messages.`;
span.textContent="You have this user blocked, click to hide these messages.";
div.append(span);
span.classList.add("blocked")
span.classList.add("blocked");
span.onclick=_=>{
const scroll=this.channel.infinite.scrollTop;
let next:Message|undefined=this;
while(next?.author===this.author){
next.generateMessage(undefined);
next.generateMessage();
next=this.channel.messages.get(this.channel.idToNext.get(next.id) as string);
}
if(this.channel.infinite.scroll&&scroll){
this.channel.infinite.scroll.scrollTop=scroll;
}
}
};
}
}else{
div.classList.remove("topMessage");
if(premessage?.author===this.author){
div.classList.add("zeroheight")
div.classList.add("zeroheight");
premessage.blockedPropigate();
div.appendChild(build);
return div;
}else{
build.classList.add("blocked","topMessage")
build.classList.add("blocked","topMessage");
const span=document.createElement("span");
let count=1;
let next=this.channel.messages.get(this.channel.idToNext.get(this.id) as string);
@ -323,13 +322,13 @@ class Message{
while(next?.author===this.author){
next.generateMessage(undefined,true);
next=this.channel.messages.get(this.channel.idToNext.get(next.id) as string);
console.log("loopy")
console.log("loopy");
}
if(this.channel.infinite.scroll&&scroll){
func();
this.channel.infinite.scroll.scrollTop=scroll;
}
}
};
div.appendChild(build);
return div;
}
@ -338,7 +337,7 @@ class Message{
if(this.message_reference){
const replyline=document.createElement("div");
const line=document.createElement("hr");
const minipfp=document.createElement("img")
const minipfp=document.createElement("img");
minipfp.classList.add("replypfp");
replyline.appendChild(line);
replyline.appendChild(minipfp);
@ -352,7 +351,7 @@ class Message{
replyline.appendChild(line2);
line2.classList.add("reply");
line.classList.add("startreply");
replyline.classList.add("replyflex")
replyline.classList.add("replyflex");
this.channel.getmessage(this.message_reference.message_id).then(message=>{
if(message.author.relationshipType===2){
username.textContent="Blocked user";
@ -360,21 +359,21 @@ class Message{
}
const author=message.author;
reply.appendChild(message.content.makeHTML({stdsize: true}));
minipfp.src=author.getpfpsrc()
minipfp.src=author.getpfpsrc();
author.bind(minipfp);
username.textContent=author.username;
author.bind(username);
});
reply.onclick=_=>{
this.channel.infinite.focus(this.message_reference.message_id);
}
};
div.appendChild(replyline);
}
div.appendChild(build);
if({0: true,19: true}[this.type]||this.attachments.length!==0){
const pfpRow = document.createElement('div');
const pfpRow = document.createElement("div");
pfpRow.classList.add("flexltr");
let pfpparent, current
let pfpparent, current;
if(premessage!=null){
pfpparent??=premessage;
let pfpparent2=pfpparent.all;
@ -383,7 +382,7 @@ class Message{
const newt=(new Date(this.timestamp).getTime())/1000;
current=(newt-old)>600;
}
const combine=(premessage?.author?.snowflake!=this.author.snowflake)||(current)||this.message_reference
const combine=(premessage?.author?.snowflake!=this.author.snowflake)||(current)||this.message_reference;
if(combine){
const pfp=this.author.buildpfp();
this.author.bind(pfp,this.guild,false);
@ -391,68 +390,67 @@ class Message{
}else{
div["pfpparent"]=pfpparent;
}
pfpRow.classList.add("pfprow")
pfpRow.classList.add("pfprow");
build.appendChild(pfpRow);
const text=document.createElement("div");
text.classList.add("flexttb")
text.classList.add("flexttb");
const texttxt=document.createElement("div");
texttxt.classList.add("commentrow","flexttb");
text.appendChild(texttxt);
if(combine){
const username=document.createElement("span");
username.classList.add("username")
username.classList.add("username");
this.author.bind(username,this.guild);
div.classList.add("topMessage");
username.textContent=this.author.username;
const userwrap=document.createElement("div");
userwrap.classList.add("flexltr");
userwrap.appendChild(username)
userwrap.appendChild(username);
if(this.author.bot){
const username=document.createElement("span");
username.classList.add("bot")
username.classList.add("bot");
username.textContent="BOT";
userwrap.appendChild(username)
userwrap.appendChild(username);
}
const time=document.createElement("span");
time.textContent=" "+formatTime(new Date(this.timestamp));
time.classList.add("timestamp")
time.classList.add("timestamp");
userwrap.appendChild(time);
texttxt.appendChild(userwrap)
texttxt.appendChild(userwrap);
}else{
div.classList.remove("topMessage");
}
const messaged=this.content.makeHTML();
div["txt"]=messaged;
const messagedwrap=document.createElement("div");
messagedwrap.classList.add("flexttb")
messagedwrap.appendChild(messaged)
texttxt.appendChild(messagedwrap)
messagedwrap.classList.add("flexttb");
messagedwrap.appendChild(messaged);
texttxt.appendChild(messagedwrap);
build.appendChild(text)
build.appendChild(text);
if(this.attachments.length){
console.log(this.attachments)
console.log(this.attachments);
const attach = document.createElement("div");
attach.classList.add("flexltr");
for(const thing of this.attachments){
attach.appendChild(thing.getHTML())
attach.appendChild(thing.getHTML());
}
messagedwrap.appendChild(attach)
messagedwrap.appendChild(attach);
}
if(this.embeds.length){
console.log(this.embeds);
const embeds = document.createElement("div")
const embeds = document.createElement("div");
embeds.classList.add("flexltr");
for(const thing of this.embeds){
embeds.appendChild(thing.generateHTML());
}
messagedwrap.appendChild(embeds)
messagedwrap.appendChild(embeds);
}
//
}else if(this.type===7){
const text=document.createElement("div");
text.classList.add("flexttb")
text.classList.add("flexttb");
const texttxt=document.createElement("div");
text.appendChild(texttxt);
build.appendChild(text);
@ -473,16 +471,15 @@ class Message{
time.textContent=" "+formatTime(new Date(this.timestamp));
time.classList.add("timestamp");
texttxt.append(time);
div.classList.add("topMessage")
div.classList.add("topMessage");
}
div["all"]=this;
const reactions=document.createElement("div");
reactions.classList.add("flexltr","reactiondiv");
this.reactdiv=new WeakRef(reactions);
this.updateReactions();
div.append(reactions)
return(div)
div.append(reactions);
return(div);
}
updateReactions(){
const reactdiv=this.reactdiv.deref();
@ -493,7 +490,7 @@ class Message{
const reaction=document.createElement("div");
reaction.classList.add("reaction");
if(thing.me){
reaction.classList.add("meReacted")
reaction.classList.add("meReacted");
}
let emoji:HTMLElement;
if(thing.emoji.id || /\d{17,21}/.test(thing.emoji.name)){
@ -513,7 +510,7 @@ class Message{
reaction.onclick=_=>{
this.reactionToggle(thing.emoji.name);
}
};
}
func();
}
@ -543,7 +540,7 @@ class Message{
if(thing.emoji.name===data.name){
thing.count--;
if(thing.count===0){
this.reactions.splice(+i,1);
this.reactions.splice(Number(i),1);
this.updateReactions();
return;
}
@ -563,32 +560,34 @@ class Message{
for(const i in this.reactions){
const reaction = this.reactions[i];
if((reaction.emoji.id && reaction.emoji.id == emoji.id) || (!reaction.emoji.id && reaction.emoji.name == emoji.name)){
this.reactions.splice(+i, 1);
this.reactions.splice(Number(i), 1);
this.updateReactions();
break;
}
}
}
buildhtml(premessage:Message|undefined=undefined){
if(this.div){console.error(`HTML for ${this.snowflake} already exists, aborting`);return;}
buildhtml(premessage?:Message|undefined):HTMLElement{
if(this.div){
console.error(`HTML for ${this.snowflake} already exists, aborting`);return this.div;
}
try{
const div=document.createElement("div");
this.div=div;
this.messageevents(div);
return this.generateMessage(premessage);
return this.generateMessage(premessage) as HTMLElement;
}catch(e){
console.error(e);
}
return this.div as HTMLElement;
}
}
let now = new Date().toLocaleDateString();
const now = new Date().toLocaleDateString();
const yesterday = new Date(now);
yesterday.setDate(new Date().getDate() - 1);
let yesterdayStr=yesterday.toLocaleDateString();
const yesterdayStr=yesterday.toLocaleDateString();
function formatTime(date:Date){
const datestring=date.toLocaleDateString();
const formatTime = (date:Date) => date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
const formatTime = (date:Date)=>date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
if(datestring=== now){
return`Today at ${formatTime(date)}`;

View file

@ -3,14 +3,14 @@ class Permissions{
deny:bigint;
readonly hasDeny:boolean;
constructor(allow:string,deny:string=""){
this.hasDeny=!!deny;
this.hasDeny=Boolean(deny);
try{
this.allow = BigInt(allow);
this.deny = BigInt(deny);
}catch(e){
}catch{
this.allow = 0n;
this.deny = 0n;
console.error(`Something really stupid happened with a permission with allow being ${allow} and deny being, ${deny}, execution will still happen, but something really stupid happened, please report if you know what caused this.`)
console.error(`Something really stupid happened with a permission with allow being ${allow} and deny being, ${deny}, execution will still happen, but something really stupid happened, please report if you know what caused this.`);
}
}
getPermissionbit(b:number,big:bigint) : boolean{
@ -22,7 +22,7 @@ class Permissions{
}
static map:{
[key:number|string]:{"name":string,"readableName":string,"description":string}|number,
}
};
static info:{"name":string,"readableName":string,"description":string}[];
static makeMap(){
Permissions.info=[//for people in the future, do not reorder these, the creation of the map realize on the order
@ -292,7 +292,9 @@ class Permissions{
}
}
hasPermission(name:string):boolean{
if(this.deny){console.warn("This function may of been used in error, think about using getPermision instead")}
if(this.deny){
console.warn("This function may of been used in error, think about using getPermision instead");
}
if(this.getPermissionbit(Permissions.map[name] as number,this.allow))return true;
if(name != "ADMINISTRATOR")return this.hasPermission("ADMINISTRATOR");
return false;
@ -307,11 +309,9 @@ class Permissions{
this.deny=this.setPermissionbit(bit,false,this.deny);
this.allow=this.setPermissionbit(bit,false,this.allow);
}else if(setto===1){
this.deny=this.setPermissionbit(bit,false,this.deny);
this.allow=this.setPermissionbit(bit,true,this.allow);
}else if(setto===-1){
this.deny=this.setPermissionbit(bit,true,this.deny);
this.allow=this.setPermissionbit(bit,false,this.allow);
}else{

View file

@ -3,12 +3,12 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Jank Client</title>
<meta content="Jank Client" property="og:title" />
<meta content="A spacebar client that has DMs, replying and more" property="og:description" />
<meta content="/logo.webp" property="og:image" />
<meta content="#4b458c" data-react-helmet="true" name="theme-color" />
<link href="/style.css" rel="stylesheet" type="text/css" />
<link href="/themes.css" rel="stylesheet" type="text/css" id="lightcss"/>
<meta content="Jank Client" property="og:title">
<meta content="A spacebar client that has DMs, replying and more" property="og:description">
<meta content="/logo.webp" property="og:image">
<meta content="#4b458c" data-react-helmet="true" name="theme-color">
<link href="/style.css" rel="stylesheet">
<link href="/themes.css" rel="stylesheet" id="lightcss">
</head>
<div id="logindiv">
<h1>Create an account</h1><br>
@ -39,12 +39,12 @@
<div>
<label for="date"><b>Date of birth:</b></label><br>
<input type="date" id="date" name="date"/>
<input type="date" id="date" name="date">
</div>
<div>
<b id="TOSbox">I agree to the <a href="" id="TOSa">Terms of Service</a>:</b>
<input type="checkbox" id="TOS" name="TOS"/>
<input type="checkbox" id="TOS" name="TOS">
</div>
<p class="wrongred" id="wrong"></p>

View file

@ -3,7 +3,6 @@ if(document.getElementById("register")){
document.getElementById("register").addEventListener("submit", registertry);
}
async function registertry(e){
e.preventDefault();
const elements=e.srcElement;
const email=elements[1].value;
@ -14,14 +13,14 @@ async function registertry(e){
}
const password=elements[3].value;
const dateofbirth=elements[5].value;
const apiurl=new URL(JSON.parse(localStorage.getItem("instanceinfo")).api)
const apiurl=new URL(JSON.parse(localStorage.getItem("instanceinfo")).api);
await fetch(apiurl+"/auth/register",{
body: JSON.stringify({
date_of_birth: dateofbirth,
email:email,
username:username,
password:password,
email,
username,
password,
consent: elements[6].checked,
captcha_key: elements[7]?.value
}),
@ -63,17 +62,17 @@ async function registertry(e){
document.getElementById("wrong").textContent=e.errors[Object.keys(e.errors)[0]]._errors[0].message;
}
}else{
adduser({serverurls:JSON.parse(localStorage.getItem("instanceinfo")),email:email,token:e.token}).username=username;
adduser({serverurls: JSON.parse(localStorage.getItem("instanceinfo")),email,token: e.token}).username=username;
localStorage.setItem("token",e.token);
const redir=new URLSearchParams(window.location.search).get("goback");
if(redir){
window.location.href = redir;
}else{
window.location.href = '/channels/@me';
window.location.href = "/channels/@me";
}
}
})
})
});
});
//document.getElementById("wrong").textContent=h;
// console.log(h);
}
@ -87,13 +86,15 @@ function error(e:HTMLFormElement,message:string){
element=div;
}else{
element.classList.remove("suberror");
setTimeout(_=>{element.classList.add("suberror")},100);
setTimeout(_=>{
element.classList.add("suberror");
},100);
}
element.textContent=message;
}
let TOSa=document.getElementById("TOSa");
async function tosLogic(){
const apiurl=new URL(JSON.parse(localStorage.getItem("instanceinfo")).api)
const apiurl=new URL(JSON.parse(localStorage.getItem("instanceinfo")).api);
const tosPage=(await (await fetch(apiurl.toString()+"/ping")).json()).instance.tosPage;
if(tosPage){
document.getElementById("TOSbox").innerHTML="I agree to the <a href=\"\" id=\"TOSa\">Terms of Service</a>:";

View file

@ -39,7 +39,9 @@ class Role{
return this.guild.localuser;
}
getColor():string|null{
if(this.color===0){return null};
if(this.color===0){
return null;
}
return`#${this.color.toString(16)}`;
}
}
@ -55,7 +57,7 @@ class PermissionToggle implements OptionsElement<number>{
this.permissions=permissions;
this.owner=owner;
}
watchForChange(){};
watchForChange(){}
generateHTML():HTMLElement{
const div=document.createElement("div");
div.classList.add("setting");
@ -80,31 +82,37 @@ class PermissionToggle implements OptionsElement<number>{
on.type="radio";
on.name=this.rolejson.name;
div.append(on);
if(state===1){on.checked=true;};
if(state===1){
on.checked=true;
}
on.onclick=_=>{
this.permissions.setPermission(this.rolejson.name,1);
this.owner.changed();
}
};
const no=document.createElement("input");
no.type="radio";
no.name=this.rolejson.name;
div.append(no);
if(state===0){no.checked=true;};
if(state===0){
no.checked=true;
}
no.onclick=_=>{
this.permissions.setPermission(this.rolejson.name,0);
this.owner.changed();
}
};
if(this.permissions.hasDeny){
const off=document.createElement("input");
off.type="radio";
off.name=this.rolejson.name;
div.append(off);
if(state===-1){off.checked=true;};
if(state===-1){
off.checked=true;
}
off.onclick=_=>{
this.permissions.setPermission(this.rolejson.name,-1);
this.owner.changed();
}
};
}
return div;
}
@ -139,7 +147,7 @@ class RoleList extends Buttons{
}
for(const i of permissions){
console.log(i);
this.buttons.push([i[0].getObject().name,i[0].id])//
this.buttons.push([i[0].getObject().name,i[0].id]);//
}
this.options=options;
}
@ -159,4 +167,4 @@ class RoleList extends Buttons{
this.onchange(this.curid,this.permission);
}
}
export {RoleList}
export{RoleList};

View file

@ -1,25 +1,25 @@
function deleteoldcache(){
caches.delete("cache");
console.log("this ran :P")
console.log("this ran :P");
}
async function putInCache(request, response){
console.log(request,response);
const cache = await caches.open('cache');
console.log("Grabbed")
const cache = await caches.open("cache");
console.log("Grabbed");
try{
console.log(await cache.put(request, response));
}catch(error){
console.error(error);
}
};
}
console.log("test");
let lastcache
self.addEventListener("activate", async (event) => {
let lastcache;
self.addEventListener("activate", async event=>{
console.log("test2");
checkCache();
})
});
async function checkCache(){
if(checkedrecently){
return;
@ -31,14 +31,16 @@ async function checkCache(){
console.log(lastcache);
fetch("/getupdates").then(async data=>{
const text=await data.clone().text();
console.log(text,lastcache)
console.log(text,lastcache);
if(lastcache!==text){
deleteoldcache();
putInCache("/getupdates",data.clone());
}
checkedrecently=true;
setTimeout(_=>{checkedrecently=false},1000*60*30);
})
setTimeout(_=>{
checkedrecently=false;
},1000*60*30);
});
}
var checkedrecently=false;
function samedomain(url){
@ -59,14 +61,14 @@ async function getfile(event){
const responseFromCache = await caches.match(event.request.url);
console.log(responseFromCache,caches);
if(responseFromCache){
console.log("cache hit")
console.log("cache hit");
return responseFromCache;
}
if(isindexhtml(event.request.url)){
console.log("is index.html")
console.log("is index.html");
const responseFromCache = await caches.match("/index.html");
if(responseFromCache){
console.log("cache hit")
console.log("cache hit");
return responseFromCache;
}
const responseFromNetwork = await fetch("/index.html");
@ -78,10 +80,14 @@ async function getfile(event){
await putInCache(event.request.clone(),responseFromNetwork.clone());
try{
return responseFromNetwork;
}catch(e){console.error(e)}
}catch(e){
console.error(e);
}
self.addEventListener('fetch', (event:any) => {
}
self.addEventListener("fetch", (event:any)=>{
try{
event.respondWith(getfile(event));
}catch(e){console.error(e)}
})
}catch(e){
console.error(e);
}
});

View file

@ -16,8 +16,10 @@ class Buttons implements OptionsElement<unknown>{
this.buttons=[];
this.name=name;
}
add(name:string,thing:Options|undefined=undefined){
if(!thing){thing=new Options(name,this)}
add(name:string,thing?:Options|undefined){
if(!thing){
thing=new Options(name,this);
}
this.buttons.push([name,thing]);
return thing;
}
@ -39,7 +41,7 @@ class Buttons implements OptionsElement<unknown>{
if(this.warndiv){
this.warndiv.remove();
}
}
};
buttonTable.append(button);
}
this.generateHTMLArea(this.buttons[0][1],htmlarea);
@ -123,7 +125,7 @@ class TextInput implements OptionsElement<string>{
class SettingsText implements OptionsElement<void>{
readonly onSubmit:(str:string)=>void;
value:void;
readonly text:string
readonly text:string;
constructor(text:string){
this.text=text;
}
@ -138,7 +140,7 @@ class SettingsText implements OptionsElement<void>{
class SettingsTitle implements OptionsElement<void>{
readonly onSubmit:(str:string)=>void;
value:void;
readonly text:string
readonly text:string;
constructor(text:string){
this.text=text;
}
@ -274,7 +276,7 @@ class SelectInput implements OptionsElement<number>{
readonly onSubmit:(str:number)=>void;
options:string[];
index:number;
select:WeakRef<HTMLSelectElement>
select:WeakRef<HTMLSelectElement>;
get value(){
return this.index;
}
@ -325,7 +327,7 @@ class MDInput implements OptionsElement<string>{
readonly owner:Options;
readonly onSubmit:(str:string)=>void;
value:string;
input:WeakRef<HTMLTextAreaElement>
input:WeakRef<HTMLTextAreaElement>;
constructor(label:string,onSubmit:(str:string)=>void,owner:Options,{initText=""}={}){
this.label=label;
this.value=initText;
@ -366,7 +368,7 @@ class FileInput implements OptionsElement<FileList|null>{
readonly label:string;
readonly owner:Options;
readonly onSubmit:(str:FileList|null)=>void;
input:WeakRef<HTMLInputElement>
input:WeakRef<HTMLInputElement>;
value:FileList|null;
clear:boolean;
constructor(label:string,onSubmit:(str:FileList)=>void,owner:Options,{clear=false}={}){
@ -389,10 +391,12 @@ class FileInput implements OptionsElement<FileList|null>{
const button=document.createElement("button");
button.textContent="Clear";
button.onclick=_=>{
if(this.onchange){this.onchange(null)};
if(this.onchange){
this.onchange(null);
}
this.value=null;
this.owner.changed();
}
};
div.append(button);
}
return div;
@ -432,7 +436,7 @@ class HtmlArea implements OptionsElement<void>{
return this.html;
}
}
watchForChange(){};
watchForChange(){}
}
class Options implements OptionsElement<void>{
name:string;
@ -458,7 +462,7 @@ class Options implements OptionsElement<void>{
container.innerHTML="";
}
}
watchForChange(){};
watchForChange(){}
addOptions(name:string,{ltr=false}={}){
const options=new Options(name,this,{ltr});
this.options.push(options);
@ -473,7 +477,7 @@ class Options implements OptionsElement<void>{
if(container){
this.generateContainter();
}else{
throw Error("Tried to make a subOptions when the options weren't rendered");
throw new Error("Tried to make a subOptions when the options weren't rendered");
}
return options;
}
@ -484,7 +488,7 @@ class Options implements OptionsElement<void>{
if(container){
this.generateContainter();
}else{
throw Error("Tried to make a subForm when the options weren't rendered");
throw new Error("Tried to make a subForm when the options weren't rendered");
}
return options;
}
@ -557,7 +561,7 @@ class Options implements OptionsElement<void>{
if(container){
const div=document.createElement("div");
if(!(elm instanceof Options)){
div.classList.add("optionElement")
div.classList.add("optionElement");
}
const html=elm.generateHTML();
div.append(html);
@ -595,8 +599,8 @@ class Options implements OptionsElement<void>{
name.classList.add("clickable");
name.onclick=()=>{
this.returnFromSub();
}
title.append(name," > ",this.subOptions.name)
};
title.append(name," > ",this.subOptions.name);
}
}else{
for(const thing of this.options){
@ -611,7 +615,6 @@ class Options implements OptionsElement<void>{
}else if(title){
title.classList.remove("settingstitle");
}
}else{
console.warn("tried to generate container, but it did not exist");
}
@ -639,7 +642,7 @@ class Options implements OptionsElement<void>{
}
div.remove();
this.submit();
}
};
}
}
submit(){
@ -753,16 +756,16 @@ class Form implements OptionsElement<object>{
const button=document.createElement("button");
button.onclick=_=>{
this.submit();
}
};
button.textContent=this.submitText;
div.append(button)
div.append(button);
}
return div;
}
onSubmit:((arg1:object)=>void);
watchForChange(func:(arg1:object)=>void){
this.onSubmit=func;
};
}
changed(){
if(this.traditionalSubmit){
this.owner.changed();
@ -808,21 +811,23 @@ class Form implements OptionsElement<object>{
}).then(_=>_.json()).then(json=>{
if(json.errors&&this.errors(json.errors))return;
this.onSubmit(json);
})
});
}else{
this.onSubmit(build);
}
console.warn("needs to be implemented")
console.warn("needs to be implemented");
}
errors(errors:{code:number,message:string,errors:{[key:string]:{_errors:{message:string,code:string}}}}){
if(!(errors instanceof Object)){return};
if(!(errors instanceof Object)){
return;
}
for(const error of Object.keys(errors)){
const elm=this.names.get(error);
if(elm){
const ref=this.options.html.get(elm);
if(ref&&ref.deref()){
const html=ref.deref() as HTMLDivElement;
this.makeError(html,errors[error]._errors[0].message)
this.makeError(html,errors[error]._errors[0].message);
return true;
}
}
@ -840,7 +845,7 @@ class Form implements OptionsElement<object>{
}
}
}else{
console.warn(formElm+" is not a valid form property")
console.warn(formElm+" is not a valid form property");
}
}
makeError(e:HTMLDivElement,message:string){
@ -852,7 +857,9 @@ class Form implements OptionsElement<object>{
element=div;
}else{
element.classList.remove("suberror");
setTimeout(_=>{element.classList.add("suberror")},100);
setTimeout(_=>{
element.classList.add("suberror");
},100);
}
element.textContent=message;
}
@ -875,7 +882,7 @@ class Settings extends Buttons{
const title=document.createElement("h2");
title.textContent=this.name;
title.classList.add("settingstitle")
title.classList.add("settingstitle");
background.append(title);
background.append(this.generateHTML());
@ -886,7 +893,9 @@ class Settings extends Buttons{
exit.textContent="✖";
exit.classList.add("exitsettings");
background.append(exit);
exit.onclick=_=>{this.hide();};
exit.onclick=_=>{
this.hide();
};
document.body.append(background);
this.html=background;
}
@ -898,5 +907,5 @@ class Settings extends Buttons{
}
}
export {Settings,OptionsElement,Buttons,Options}
export{Settings,OptionsElement,Buttons,Options};

View file

@ -81,7 +81,7 @@ class SnowFlake<x extends WeakKey>{
try{
return Number((BigInt(this.id)>>22n)+1420070400000n);
}catch{
console.error(`The ID is corrupted, it's ${this.id} when it should be some number.`)
console.error(`The ID is corrupted, it's ${this.id} when it should be some number.`);
return 0;
}
}

View file

@ -45,7 +45,7 @@ class User{
theme_colors: this.theme_colors,
pronouns: this.pronouns,
badge_ids: this.badge_ids
},this.owner)
},this.owner);
}
public getPresence(presence:presencejson|undefined){
if(presence){
@ -75,20 +75,20 @@ class User{
this.contextmenu.addbutton("Message user",function(this:User){
fetch(this.info.api+"/users/@me/channels",
{method: "POST",
body:JSON.stringify({"recipients":[this.id]}),
body: JSON.stringify({recipients: [this.id]}),
headers: this.localuser.headers
});
});
this.contextmenu.addbutton("Block user",function(this:User){
this.block();
},null,function(){
return this.relationshipType!==2
return this.relationshipType!==2;
});
this.contextmenu.addbutton("Unblock user",function(this:User){
this.unblock();
},null,function(){
return this.relationshipType===2
return this.relationshipType===2;
});
this.contextmenu.addbutton("Friend request",function(this:User){
fetch(`${this.info.api}/users/@me/relationships/${this.id}`,{
@ -97,11 +97,11 @@ class User{
body: JSON.stringify({
type: 1
})
})
});
});
this.contextmenu.addbutton("Kick member",function(this:User,member:Member){
member.kick();
},null,function(member){
},null,member=>{
if(!member)return false;
const us=member.guild.member;
if(member.id===us.id){
@ -114,7 +114,7 @@ class User{
});
this.contextmenu.addbutton("Ban member",function(this:User,member:Member){
member.ban();
},null,function(member){
},null,member=>{
if(!member)return false;
const us=member.guild.member;
if(member.id===us.id){
@ -130,7 +130,7 @@ class User{
if(owner.userMap.has(user.id)){
return owner.userMap.get(user.id) as User;
}else{
const tempuser=new User(user as userjson,owner,true)
const tempuser=new User(user as userjson,owner,true);
owner.userMap.set(user.id,tempuser);
return tempuser;
}
@ -143,7 +143,9 @@ class User{
}
constructor(userjson:userjson,owner:Localuser,dontclone=false){
this.owner=owner;
if(!owner){console.error("missing localuser")}
if(!owner){
console.error("missing localuser");
}
if(dontclone){
for(const thing of Object.keys(userjson)){
if(thing==="bio"){
@ -168,15 +170,14 @@ class User{
async getUserProfile(){
return(await fetch(`${this.info.api}/users/${this.id.replace("#clone","")}/profile?with_mutual_guilds=true&with_mutual_friends=true`,{
headers: this.localuser.headers
})).json()
})).json();
}
resolving:false|Promise<any>=false;
async getBadge(id:string){
if(this.localuser.badges.has(id)){
return this.localuser.badges.get(id);
}else{
if(this.resolving)
{
if(this.resolving){
await this.resolving;
return this.localuser.badges.get(id);
}
@ -192,7 +193,7 @@ class User{
}
}
buildpfp(){
const pfp=document.createElement('img');
const pfp=document.createElement("img");
pfp.loading="lazy";
pfp.src=this.getpfpsrc();
pfp.classList.add("pfp");
@ -222,7 +223,7 @@ class User{
}
userupdate(json:userjson){
if(json.avatar!==this.avatar){
console.log
console.log;
this.changepfp(json.avatar);
}
}
@ -241,7 +242,7 @@ class User{
_.bind(html);
}
}).catch(_=>{
console.log(_)
console.log(_);
});
}
if(guild){
@ -260,7 +261,7 @@ class User{
this.avatar=update;
this.hypotheticalpfp=false;
const src=this.getpfpsrc();
console.log(src)
console.log(src);
for(const thing of document.getElementsByClassName("userid:"+this.id)){
(thing as HTMLImageElement).src=src;
}
@ -272,7 +273,7 @@ class User{
body: JSON.stringify({
type: 2
})
})
});
this.relationshipType=2;
const channel=this.localuser.channelfocus;
if(channel){
@ -285,7 +286,7 @@ class User{
fetch(`${this.info.api}/users/@me/relationships/${this.id}`,{
method: "DELETE",
headers: this.owner.headers,
})
});
this.relationshipType=0;
const channel=this.localuser.channelfocus;
if(channel){
@ -306,7 +307,7 @@ class User{
}
}
createjankpromises(){
new Promise(_=>{})
new Promise(_=>{});
}
async buildprofile(x:number,y:number,guild:Guild|null=null){
if(Contextmenu.currentmenu!=""){
@ -322,7 +323,7 @@ class User{
div.style.setProperty("--accent_color","transparent");
}
if(this.banner){
const banner=document.createElement("img")
const banner=document.createElement("img");
let src:string;
if(!this.hypotheticalbanner){
src=this.info.cdn+"/avatars/"+this.id.replace("#clone","")+"/"+this.banner+".png";
@ -350,7 +351,7 @@ class User{
const badgejson=await this.getBadge(id);
if(badgejson){
const badge=document.createElement(badgejson.link?"a":"div");
badge.classList.add("badge")
badge.classList.add("badge");
const img=document.createElement("img");
img.src=badgejson.icon;
badge.append(img);
@ -363,7 +364,7 @@ class User{
badgediv.append(badge);
}
}
})()
})();
{
const pfp=await this.buildstatuspfp();
div.appendChild(pfp);
@ -379,12 +380,12 @@ class User{
const discrimatorhtml=document.createElement("h3");
discrimatorhtml.classList.add("tag");
discrimatorhtml.textContent=this.username+"#"+this.discriminator;
userbody.appendChild(discrimatorhtml)
userbody.appendChild(discrimatorhtml);
const pronounshtml=document.createElement("p");
pronounshtml.textContent=this.pronouns;
pronounshtml.classList.add("pronouns");
userbody.appendChild(pronounshtml)
userbody.appendChild(pronounshtml);
const rule=document.createElement("hr");
userbody.appendChild(rule);
@ -400,7 +401,7 @@ class User{
div.classList.add("rolediv");
const color=document.createElement("div");
div.append(color);
color.style.setProperty("--role-color","#"+role.color.toString(16).padStart(6,"0"))
color.style.setProperty("--role-color","#"+role.color.toString(16).padStart(6,"0"));
color.classList.add("colorrolediv");
const span=document.createElement("span");
div.append(span);
@ -415,16 +416,16 @@ class User{
if(x!==-1){
Contextmenu.currentmenu=div;
document.body.appendChild(div)
document.body.appendChild(div);
Contextmenu.keepOnScreen(div);
}
return div;
}
profileclick(obj:HTMLElement,guild:Guild|undefined=undefined){
profileclick(obj:HTMLElement,guild?:Guild|undefined){
obj.onclick=e=>{
this.buildprofile(e.clientX,e.clientY,guild);
e.stopPropagation();
}
};
}
}
User.setUpContextMenu();