#!/bin/bash
# EWW workspace widget for niri (literal/listen mode).
# Outputs an eww Yuck literal widget, updates on workspace changes.

render() {
    local ws_json
    ws_json=$(niri msg -j workspaces 2>/dev/null) || ws_json="[]"

    local out="(box :class \"workspaces\" :space-evenly false"
    while IFS= read -r ws; do
        local idx is_active
        idx=$(echo "$ws" | jq -r '.idx')
        is_active=$(echo "$ws" | jq -r '.is_focused')
        local id
        id=$(echo "$ws" | jq -r '.id')
        local class="workspace-button"
        [ "$is_active" = "true" ] && class="workspace-button workspace-active"
        out+=" (button :class \"$class\" :width 20 :onclick \"niri msg action focus-workspace $idx\" \"$idx\")"
    done < <(echo "$ws_json" | jq -c '.[]')
    out+=")"
    echo "$out"
}

render

# Watch for workspace changes via event-stream
niri msg event-stream 2>/dev/null | while IFS= read -r line; do
    echo "$line" | grep -qE '"WorkspacesChanged"|"WorkspaceActivated"' && render
done
