Fix context menu implementation and add clipboard utils

This commit is contained in:
SrGooglo 2025-04-10 18:20:41 +00:00
parent b54f3192b3
commit e6fa958350
4 changed files with 276 additions and 218 deletions

View File

@ -1,41 +1,43 @@
import copyToClipboard from "@utils/copyToClipboard"
import pasteFromClipboard from "@utils/pasteFromClipboard"
export default { export default {
"default-context": (items) => { "default-context": (items) => {
const text = window.getSelection().toString() const text = window.getSelection().toString()
if (text) { if (text) {
items.push({ items.push({
label: "Copy", label: "Copy",
icon: "FiCopy", icon: "FiCopy",
action: (clickedItem, ctx) => { action: (clickedItem, ctx) => {
copyToClipboard(text) copyToClipboard(text)
ctx.close() ctx.close()
} },
}) })
} }
items.push({ items.push({
label: "Paste", label: "Paste",
icon: "FiClipboard", icon: "FiClipboard",
action: (clickedItem, ctx) => { action: (clickedItem, ctx) => {
app.message.error("This action is not supported by your browser") pasteFromClipboard(clickedItem)
ctx.close()
},
})
ctx.close() items.push({
} label: "Report a bug",
}) icon: "FiAlertTriangle",
action: (clickedItem, ctx) => {
app.eventBus.emit("app.reportBug", {
clickedItem,
})
items.push({ ctx.close()
label: "Report a bug", },
icon: "FiAlertTriangle", })
action: (clickedItem, ctx) => {
app.eventBus.emit("app.reportBug", {
clickedItem,
})
ctx.close() return items
} },
}) }
return items
}
}

View File

@ -2,69 +2,73 @@ import copyToClipboard from "@utils/copyToClipboard"
import download from "@utils/download" import download from "@utils/download"
export default { export default {
"post-card": (items, parent, element, control) => { "post-card": (items, parent, element, control) => {
items.push({ if (!parent.id) {
label: "Copy ID", parent = parent.parentNode
icon: "FiCopy", }
action: () => {
copyToClipboard(parent.id)
control.close()
}
})
items.push({ items.push({
label: "Copy Link", label: "Copy ID",
icon: "FiLink", icon: "FiCopy",
action: () => { action: () => {
copyToClipboard(`${window.location.origin}/post/${parent.id}`) copyToClipboard(parent.id)
control.close() control.close()
} },
}) })
let media = null items.push({
label: "Copy Link",
icon: "FiLink",
action: () => {
copyToClipboard(`${window.location.origin}/post/${parent.id}`)
control.close()
},
})
if (parent.querySelector(".attachment")) { let media = null
media = parent.querySelector(".attachment")
media = media.querySelector("video, img")
if (media.querySelector("source")) { if (parent.querySelector(".attachment")) {
media = media.querySelector("source") media = parent.querySelector(".attachment")
} media = media.querySelector("video, img")
}
if (media) { if (media.querySelector("source")) {
items.push({ media = media.querySelector("source")
type: "separator", }
}) }
items.push({ if (media) {
label: "Copy media URL", items.push({
icon: "FiCopy", type: "separator",
action: () => { })
copyToClipboard(media.src)
control.close()
}
})
items.push({ items.push({
label: "Open media in new tab", label: "Copy media URL",
icon: "FiExternalLink", icon: "FiCopy",
action: () => { action: () => {
window.open(media.src, "_blank") copyToClipboard(media.src)
control.close() control.close()
} },
}) })
items.push({ items.push({
label: "Download media", label: "Open media in new tab",
icon: "FiDownload", icon: "FiExternalLink",
action: () => { action: () => {
download(media.src) window.open(media.src, "_blank")
control.close() control.close()
} },
}) })
}
return items items.push({
} label: "Download media",
} icon: "FiDownload",
action: () => {
download(media.src)
control.close()
},
})
}
return items
},
}

View File

@ -9,13 +9,12 @@ const ContextMenu = (props) => {
const [visible, setVisible] = React.useState(true) const [visible, setVisible] = React.useState(true)
const { items = [], cords, clickedComponent, ctx } = props const { items = [], cords, clickedComponent, ctx } = props
async function onClose() {
setVisible(false)
props.unregisterOnClose(onClose)
}
React.useEffect(() => { React.useEffect(() => {
props.registerOnClose(onClose) if (props.fireWhenClosing) {
props.fireWhenClosing(() => {
setVisible(false)
})
}
}, []) }, [])
const handleItemClick = async (item) => { const handleItemClick = async (item) => {

View File

@ -1,158 +1,211 @@
import React from "react" import React from "react"
import { Core, EventBus } from "@ragestudio/vessel" import { Core, EventBus } from "@ragestudio/vessel"
import ContextMenu from "./components/contextMenu" import ContextMenu from "./components/contextMenu"
import DefaultContext from "@config/context-menu/default"
import DefaultContenxt from "@config/context-menu/default"
import PostCardContext from "@config/context-menu/post" import PostCardContext from "@config/context-menu/post"
export default class ContextMenuCore extends Core { export default class ContextMenuCore extends Core {
static namespace = "contextMenu" static namespace = "contextMenu"
contexts = { contexts = {
...DefaultContenxt, ...DefaultContext,
...PostCardContext, ...PostCardContext,
} }
eventBus = new EventBus() eventBus = new EventBus()
isMenuOpen = false
fireWhenClosing = null
async onInitialize() { async onInitialize() {
if (app.isMobile) { if (app.isMobile) {
this.console.warn("Context menu is not available on mobile") this.console.warn("Context menu is not available on mobile")
return false return false
} }
document.addEventListener("contextmenu", this.handleEvent.bind(this)) document.addEventListener("contextmenu", this.handleEvent)
} }
async handleEvent(event) { handleEvent = async (event) => {
event.preventDefault() event.preventDefault()
// get the cords of the mouse // obtain cord of mouse
const x = event.clientX const x = event.clientX
const y = event.clientY const y = event.clientY
// get the component that was clicked // get clicked component
const component = document.elementFromPoint(x, y) const component = document.elementFromPoint(x, y)
// check if is clicking inside a context menu or a children inside a context menu // check if right-clicked inside a context menu
if (component.classList.contains("contextMenu") || component.closest(".contextMenu")) { if (
return component.classList.contains("contextMenu") ||
} component.closest(".contextMenu")
) {
return
}
const items = await this.generateItems(component) // gen items
const items = await this.generateItems(component)
if (!items) { // if no items, abort
this.console.warn("No context menu items found, aborting") if (!items || items.length === 0) {
return false this.console.error("No context menu items found, aborting")
} return false
}
this.show({ // render menu
registerOnClose: (cb) => { this.eventBus.on("close", cb) }, this.show({
unregisterOnClose: (cb) => { this.eventBus.off("close", cb) }, cords: { x, y },
cords: { clickedComponent: component,
x, items: items,
y, fireWhenClosing: (fn) => {
}, this.fireWhenClosing = fn
clickedComponent: component, },
items: items, ctx: {
ctx: { close: this.close,
close: this.onClose, },
} })
}) }
}
registerContext = async (element, context) => { registerContext = (element, context) => {
this.contexts[element] = context this.contexts[element] = context
} }
generateItems = async (element) => { generateItems = async (element) => {
let items = [] let contextNames = []
let finalItems = []
// find the closest context with attribute (context-menu) // search parent element with context-menu attribute
// if not found, use default context const parentElement = element.closest("[context-menu]")
const parentElement = element.closest("[context-menu]")
let contexts = [] // if parent element exists, get context names from attribute
if (parentElement) {
const contextAttr = parentElement.getAttribute("context-menu") || ""
contextNames = contextAttr
.split(",")
.map((context) => context.trim())
if (parentElement) { // if context includes "ignore", no show context menu
contexts = parentElement.getAttribute("context-menu") ?? [] if (contextNames.includes("ignore")) {
return null
}
}
if (typeof contexts === "string") { // if context includes "no-default", no add default context
contexts = contexts.split(",").map((context) => context.trim()) if (!contextNames.includes("no-default")) {
} contextNames.push("default-context")
} } else {
// remove "no-default" from context names
contextNames = contextNames.filter(
(context) => context !== "no-default",
)
}
// if context includes ignore, return null // process each context sequentially
if (contexts.includes("ignore")) { for (let i = 0; i < contextNames.length; i++) {
return null const contextName = contextNames[i]
}
// check if context includes no-default, if not, push default context and remove no-default // obtain contexted items
if (contexts.includes("no-default")) { const contextItems = await this.getContextItems(
contexts = contexts.filter((context) => context !== "no-default") contextName,
} else { parentElement,
contexts.push("default-context") element,
} )
for await (const [index, context] of contexts.entries()) { // if any contexted items exist, add them to the final items
let contextObject = this.contexts[context] if (contextItems && contextItems.length > 0) {
finalItems = finalItems.concat(contextItems)
if (!contextObject) { // if is not the last context, add a separator
this.console.warn(`Context ${context} not found`) if (i < contextNames.length - 1) {
continue finalItems.push({
} type: "separator",
})
}
}
}
if (typeof contextObject === "function") { // assign indices
contextObject = await contextObject(items, parentElement, element, { finalItems = finalItems.map((item, index) => {
close: this.onClose, if (!item.index) {
}) item.index = index
} }
return item
})
// push divider // sort items by index
if (contexts.length > 0 && index !== contexts.length - 1) { finalItems.sort((a, b) => a.index - b.index)
items.push({
type: "separator"
})
}
}
// fullfill each item with a correspondent index if missing declared // remove undefined items
items = items.map((item, index) => { finalItems = finalItems.filter((item) => item !== undefined)
if (!item.index) {
item.index = index
}
return item return finalItems
}) }
// short items (if has declared index) getContextItems = async (contextName, parentElement, element) => {
items = items.sort((a, b) => a.index - b.index) const contextObject = this.contexts[contextName]
// remove undefined items if (!contextObject) {
items = items.filter((item) => item !== undefined) this.console.warn(`Context ${contextName} not found`)
return []
}
return items // if is a function, execute it to get the elements
} if (typeof contextObject === "function") {
try {
const newItems = []
show = async (payload) => { // call the function
app.cores.window_mng.render( const result = await contextObject(
"context-menu-portal", newItems,
React.createElement(ContextMenu, payload), parentElement,
{ element,
onClose: this.onClose, { close: this.close },
createOrUpdate: true, )
closeOnClickOutside: true,
},
)
}
onClose = async (delay = 200) => { return result || newItems
this.eventBus.emit("close", delay) } catch (error) {
this.console.error(
`Error processing context [${contextName}] >`,
error,
)
return []
}
}
await new Promise((resolve) => { // if it is an object (array), return it directly
setTimeout(resolve, delay) return Array.isArray(contextObject) ? contextObject : []
}) }
}
} show = async (props) => {
app.cores.window_mng.render(
"context-menu-portal",
React.createElement(ContextMenu, props),
{
useFrame: false,
createOrUpdate: true,
closeOnClickOutside: true, // sets default click outside behavior
onClose: this.onClose, // triggered when the menu is closing
},
)
this.isMenuOpen = true
}
// triggered when the menu is closing
onClose = async (delay = 200) => {
if (typeof this.fireWhenClosing === "function") {
await this.fireWhenClosing()
}
if (delay > 0) {
await new Promise((resolve) => setTimeout(resolve, delay))
}
this.isMenuOpen = false
}
// close the menu
close = async () => {
app.cores.window_mng.close("context-menu-portal")
}
}