TeaWeb/js/contextMenu.ts

102 lines
2.5 KiB
TypeScript
Raw Normal View History

2018-02-27 17:20:49 +01:00
// If the document is clicked somewhere
$(document).bind("mousedown", function (e) {
// If the clicked element is not the menu
if ($(e.target).parents(".contextMenu").length == 0) {
// Hide it
despawnContextMenu();
}
});
let contextMenuCloseFn = undefined;
function despawnContextMenu() {
2018-03-07 19:06:52 +01:00
let menue = $(".contextMenu");
if(!menue.is(":visible")) return;
menue.hide(100);
2018-02-27 17:20:49 +01:00
if(contextMenuCloseFn) contextMenuCloseFn();
}
enum MenuEntryType {
CLOSE,
ENTRY,
HR,
EMPTY
}
class MenuEntry {
static HR() {
return {
callback: () => {},
type: MenuEntryType.HR,
name: "",
icon: ""
};
};
static EMPTY() {
return {
callback: () => {},
type: MenuEntryType.EMPTY,
name: "",
icon: ""
};
};
static CLOSE(callback: () => void) {
return {
callback: callback,
type: MenuEntryType.EMPTY,
name: "",
icon: ""
};
}
2018-04-11 17:56:09 +02:00
}
2018-02-27 17:20:49 +01:00
function spawnMenu(x, y, ...entries: {
callback: () => void;
type: MenuEntryType;
name: (() => string) | string;
icon: (() => string) | string;
2018-04-11 17:56:09 +02:00
disabled?: boolean;
2018-04-16 20:38:35 +02:00
invalidPermission?: boolean;
2018-02-27 17:20:49 +01:00
}[]) {
2018-04-11 17:56:09 +02:00
const menu = $("#contextMenu");
2018-02-27 17:20:49 +01:00
menu.empty();
menu.hide();
contextMenuCloseFn = undefined;
let index = 0;
for(let entry of entries){
if(entry.type == MenuEntryType.HR) {
menu.append("<hr>");
} else if(entry.type == MenuEntryType.CLOSE) {
contextMenuCloseFn = entry.callback;
} else if(entry.type == MenuEntryType.ENTRY) {
let icon = $.isFunction(entry.icon) ? entry.icon() : entry.icon;
if(icon.length == 0) icon = "icon_empty";
else icon = "icon " + icon;
let tag = $.spawn("li");
tag.append("<div class='" + icon + "'></div>");
tag.append("<div>" + ($.isFunction(entry.name) ? entry.name() : entry.name) + "</div>");
2018-04-11 17:56:09 +02:00
2018-02-27 17:20:49 +01:00
menu.append(tag);
2018-04-16 20:38:35 +02:00
if(entry.disabled || entry.invalidPermission) tag.addClass("disabled");
2018-04-11 17:56:09 +02:00
else {
tag.click(function () {
if($.isFunction(entry.callback)) entry.callback();
despawnContextMenu();
});
}
2018-02-27 17:20:49 +01:00
}
}
menu.show(100);
// In the right position (the mouse)
menu.css({
"top": y + "px",
"left": x + "px"
});
}