repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

quickshell/nuguland/Notifications.qml

Raw
import QtQuick
import Quickshell
import Quickshell.Services.Notifications

Item {
    id: root

    property int attentionCount: 0
    property bool dnd: false
    property bool popupInhibition: false
    property int unreadCount: 0
    property var notifications: []
    property var nativeNotifications: ({
    })
    property var expandedGroups: []
    property var pointerTrace: []
    property var lastAction: ({
    })
    readonly property bool nativeActionRoute: true
    readonly property bool usesNativeNotificationServer: true
    readonly property bool groupedByAppLatestFirst: true
    readonly property bool horizontalActionRows: true
    readonly property real dismissThresholdRatio: 0.35
    readonly property int groupPreviewCount: 1
    readonly property bool removalLifecycleLock: true
    readonly property var dragDismissContract: ({
        "source": "Nuguland NotifGroupList.qml",
        "axis": "x",
        "dismissThresholdRatio": dismissThresholdRatio,
        "snapBackTransition": "drag-snap-back",
        "commitTransition": "drag-dismiss-commit",
        "removalLifecycleLock": removalLifecycleLock,
        "modelLock": "lock-until-remove-animation-finished"
    })
    readonly property var persistenceShape: ["id", "appName", "summary", "body", "time", "urgency", "actions"]

    function activeRole() {
        return "ui.focus";
    }

    function attentionRole() {
        return "warning";
    }

    function borderRole(attention, active) {
        if (attention)
            return attentionRole();

        if (active)
            return activeRole();

        return "ui.accent";
    }

    function fillRole(active) {
        return active ? activeRole() : "transparent";
    }

    function widgetState(attention, active) {
        return JSON.stringify({
            "attention": attention,
            "active": active,
            "attentionRole": attentionRole(),
            "activeRole": activeRole(),
            "borderRole": borderRole(attention, active),
            "fillRole": fillRole(active)
        });
    }

    function urgencyName(value) {
        if (value === NotificationUrgency.Critical)
            return "critical";

        if (value === NotificationUrgency.Low)
            return "low";

        if (String(value).toLowerCase().indexOf("critical") >= 0)
            return "critical";

        if (String(value).toLowerCase().indexOf("low") >= 0)
            return "low";

        return "normal";
    }

    function actionList(record) {
        const source = record && record.actions ? record.actions : [];
        const rows = [];
        for (let i = 0; i < source.length; i++) {
            const action = source[i];
            rows.push({
                "id": action.id || action.identifier || `action-${i}`,
                "label": action.label || action.text || "Action"
            });
        }
        return rows;
    }

    function normalize(input) {
        const record = input || ({
        });
        const id = String(record.id || record.notificationId || `notif-${notifications.length + 1}`);
        const actions = actionList(record);
        return {
            "id": id,
            "nativeId": record.nativeId || record.notificationId || "",
            "appName": record.appName || "unknown",
            "appIcon": record.appIcon || "",
            "image": record.image || "",
            "summary": record.summary || "",
            "body": record.body || "",
            "time": Number(record.time || Date.now()),
            "urgency": urgencyName(record.urgency || "normal"),
            "actions": actions,
            "popup": !(dnd || popupInhibition),
            "closed": false,
            "read": false,
            "removalLifecycleLock": false
        };
    }

    function acceptNativeNotification(notification) {
        if (!notification)
            return ;

        notification.tracked = true;
        const id = String(notification.id);
        const map = Object.assign({
        }, nativeNotifications);
        map[id] = notification;
        nativeNotifications = map;
        const row = normalize({
            "id": id,
            "nativeId": id,
            "appName": notification.appName,
            "appIcon": notification.appIcon,
            "image": notification.image,
            "summary": notification.summary,
            "body": notification.body,
            "time": Date.now(),
            "urgency": notification.urgency,
            "actions": notification.actions || []
        });
        notifications = notifications.concat([row]);
        unreadCount += 1;
        lastAction = {
            "kind": "native-notification",
            "id": id,
            "nativeActionRoute": nativeActionRoute
        };
    }

    function actionRows(notification) {
        const rows = [{
            "id": "close",
            "kind": "close",
            "label": "Close",
            "route": "Notifications.qml"
        }];
        const serverActions = notification.actions || [];
        for (let i = 0; i < serverActions.length; i++) {
            rows.push({
                "id": serverActions[i].id || serverActions[i].identifier || `action-${i}`,
                "kind": "server-action",
                "label": serverActions[i].label || serverActions[i].text || "Action",
                "route": "Notifications.qml"
            });
        }
        rows.push({
            "id": "copy-body",
            "kind": "copy-body",
            "label": "Copy body",
            "route": "Notifications.qml"
        });
        return rows;
    }

    function highestUrgency(rows) {
        for (let i = 0; i < rows.length; i++) if (rows[i].urgency === "critical") {
            return "critical";
        }
        for (let j = 0; j < rows.length; j++) if (rows[j].urgency === "normal") {
            return "normal";
        }
        return "low";
    }

    function groups() {
        const byApp = ({
        });
        for (let i = 0; i < notifications.length; i++) {
            const n = notifications[i];
            if (n.closed)
                continue;

            if (!byApp[n.appName])
                byApp[n.appName] = {
                "appName": n.appName,
                "latestTime": 0,
                "notifications": [],
                "expanded": expandedGroups.indexOf(n.appName) >= 0
            };

            byApp[n.appName].notifications.push(Object.assign({
            }, n, {
                "actionRows": actionRows(n)
            }));
            byApp[n.appName].latestTime = Math.max(byApp[n.appName].latestTime, n.time);
        }
        const result = [];
        for (const app in byApp) {
            byApp[app].notifications.sort((a, b) => {
                return b.time - a.time;
            });
            byApp[app].count = byApp[app].notifications.length;
            byApp[app].urgency = highestUrgency(byApp[app].notifications);
            byApp[app].previewCount = groupPreviewCount;
            byApp[app].visibleNotifications = byApp[app].expanded ? byApp[app].notifications : byApp[app].notifications.slice(0, groupPreviewCount);
            byApp[app].expandCollapseState = byApp[app].expanded ? "expanded" : "collapsed";
            byApp[app].animatedExpandHeight = true;
            result.push(byApp[app]);
        }
        result.sort((a, b) => {
            return b.latestTime - a.latestTime;
        });
        return result;
    }

    function notificationPanelContract() {
        return {
            "source": "Nuguland NotifGroup.qml NotifGroupList.qml NotifActionList.qml",
            "ownedBy": "PopoutHost.qml inline NotificationGroup",
            "groupedCardPanel": true,
            "appMediaSlot": true,
            "expandPill": true,
            "animatedExpandHeight": true,
            "maskedHorizontalActionRail": true,
            "visiblePreviewCount": groupPreviewCount,
            "actionRailKinds": ["close", "server-action", "copy-body"],
            "pointerParity": ["left-toggle-expand", "middle-close", "horizontal-drag-dismiss"],
            "keyboardParity": ["Return", "Space", "Escape"],
            "dismissThresholdRatio": dismissThresholdRatio,
            "realNotificationServer": true,
            "noSyntheticNotifications": true
        };
    }

    function scrollableListChrome(rowCount) {
        const count = Math.max(0, Number(rowCount));
        const scrollable = count > 1;
        return {
            "source": "Nuguland ScrollEdgeFade.qml plus Nuguland FlickMonitor.qml",
            "scrollEdgeFade": true,
            "topEdgeFade": false,
            "bottomEdgeFade": scrollable,
            "fadeSize": 32,
            "scrollHint": {
                "visible": scrollable,
                "icon": "notifications",
                "side": "right",
                "tooltip": "scroll notifications"
            },
            "flickMonitor": {
                "enabled": true,
                "velocitySamples": 6,
                "events": ["pressed", "positionChanged", "released"]
            }
        };
    }

    function recordPointerEvent(kind, notificationId, x, y, deltaX) {
        const rows = pointerTrace.slice(Math.max(0, pointerTrace.length - 15));
        rows.push({
            "kind": kind,
            "notificationId": notificationId,
            "x": x,
            "y": y,
            "deltaX": deltaX
        });
        pointerTrace = rows;
    }

    function stateObject() {
        const active = notifications.filter((n) => {
            return !n.closed;
        });
        const grouped = groups();
        return {
            "backend": "Notifications.qml",
            "usesNativeNotificationServer": usesNativeNotificationServer,
            "nativeActionRoute": nativeActionRoute,
            "syntheticNotifications": false,
            "trackedNativeCount": Object.keys(nativeNotifications).length,
            "groupedByAppLatestFirst": groupedByAppLatestFirst,
            "horizontalActionRows": horizontalActionRows,
            "expandedGroups": expandedGroups.slice(0),
            "groupPreviewCount": groupPreviewCount,
            "dismissThresholdRatio": dismissThresholdRatio,
            "dragDismissContract": dragDismissContract,
            "notificationPanelContract": notificationPanelContract(),
            "dnd": dnd,
            "popupInhibition": dnd || popupInhibition,
            "toastAnchor": {
                "barId": "notifications",
                "edge": "top",
                "source": "NotificationServer",
                "suppressedWhenDnd": true,
                "popupVisible": !(dnd || popupInhibition) && active.length > 0
            },
            "unreadCount": unreadCount,
            "activeCount": active.length,
            "groups": grouped,
            "scrollableListChrome": scrollableListChrome(grouped.length),
            "actionKinds": ["close", "server-action", "copy-body"],
            "persistenceShape": persistenceShape,
            "discardAll": true,
            "removalLifecycleLock": removalLifecycleLock,
            "pointerTrace": pointerTrace,
            "lastAction": lastAction
        };
    }

    function stateJson() {
        return JSON.stringify(stateObject());
    }

    function toggleDnd() {
        dnd = !dnd;
        lastAction = {
            "kind": "toggle-dnd",
            "enabled": dnd
        };
        return stateJson();
    }

    function closeNotification(row) {
        if (!row || row.closed)
            return ;

        row.closed = true;
        row.removalLifecycleLock = removalLifecycleLock;
        unreadCount = Math.max(0, unreadCount - 1);
        const nativeNotification = nativeNotifications[String(row.nativeId || row.id)];
        if (nativeActionRoute && nativeNotification && nativeNotification.dismiss)
            nativeNotification.dismiss();

    }

    function runAction(notificationId, actionId) {
        const id = String(notificationId);
        const action = String(actionId);
        for (let i = 0; i < notifications.length; i++) {
            const n = notifications[i];
            if (n.id !== id)
                continue;

            if (action === "close") {
                closeNotification(n);
                lastAction = {
                    "kind": "close",
                    "id": id,
                    "route": "Notifications.qml",
                    "nativeActionRoute": nativeActionRoute
                };
            } else if (action === "copy-body") {
                if (n.body.length > 0)
                    Quickshell.execDetached(["wl-copy", n.body]);

                lastAction = {
                    "kind": "copy-body",
                    "id": id,
                    "bodyCopied": n.body.length > 0,
                    "route": "Notifications.qml",
                    "clipboardRoute": "wl-copy"
                };
            } else {
                let invoked = false;
                if (nativeActionRoute) {
                    const nativeNotification = nativeNotifications[String(n.nativeId || n.id)];
                    const nativeActions = nativeNotification && nativeNotification.actions ? nativeNotification.actions : [];
                    for (let j = 0; j < nativeActions.length; j++) {
                        if (nativeActions[j].identifier === action && nativeActions[j].invoke) {
                            nativeActions[j].invoke();
                            invoked = true;
                        }
                    }
                }
                lastAction = {
                    "kind": "server-action",
                    "id": id,
                    "actionId": action,
                    "invoked": invoked,
                    "route": "Notifications.qml",
                    "nativeActionRoute": nativeActionRoute
                };
            }
            notifications = notifications.slice(0);
            return stateJson();
        }
        lastAction = {
            "kind": "missing",
            "id": id,
            "actionId": action,
            "route": "Notifications.qml"
        };
        return stateJson();
    }

    function toggleGroup(appName) {
        const app = String(appName);
        const expanded = expandedGroups.indexOf(app) < 0;
        expandedGroups = expanded ? expandedGroups.concat([app]) : expandedGroups.filter((row) => {
            return row !== app;
        });
        lastAction = {
            "kind": "toggleGroup",
            "appName": app,
            "expanded": expanded
        };
        return stateJson();
    }

    function dragNotification(notificationId, deltaX, width) {
        const id = String(notificationId);
        const x = Number(deltaX);
        const rowWidth = Math.max(1, Number(width));
        const ratio = Math.abs(x) / rowWidth;
        const committed = ratio >= dismissThresholdRatio;
        const transition = committed ? "drag-dismiss-commit" : "drag-snap-back";
        for (let i = 0; i < notifications.length; i++) {
            const n = notifications[i];
            if (n.id !== id)
                continue;

            if (committed)
                closeNotification(n);

            lastAction = {
                "kind": "dragDismiss",
                "id": id,
                "deltaX": x,
                "width": rowWidth,
                "ratio": Math.round(ratio * 1000) / 1000,
                "committed": committed,
                "transition": transition,
                "removalLifecycleLock": committed ? removalLifecycleLock : false
            };
            notifications = notifications.slice(0);
            return stateJson();
        }
        lastAction = {
            "kind": "dragDismiss",
            "id": id,
            "deltaX": x,
            "width": rowWidth,
            "ratio": Math.round(ratio * 1000) / 1000,
            "committed": false,
            "transition": "missing",
            "removalLifecycleLock": false
        };
        return stateJson();
    }

    function discardAllNotifications() {
        notifications = [];
        unreadCount = 0;
        lastAction = {
            "kind": "discardAll",
            "route": "Notifications.qml"
        };
        return stateJson();
    }

    Loader {
        active: true

        sourceComponent: NotificationServer {
            keepOnReload: false
            persistenceSupported: true
            bodySupported: true
            bodyMarkupSupported: true
            bodyHyperlinksSupported: true
            bodyImagesSupported: true
            actionsSupported: true
            actionIconsSupported: true
            imageSupported: true
            inlineReplySupported: false
            onNotification: (notification) => {
                return root.acceptNativeNotification(notification);
            }
        }

    }

}