Skip to content

Foundry Menu

R edited this page Sep 25, 2026 · 3 revisions

Foundry.Menu

Part of the Foundry API reference.

New to WoW addons? Start here →

Foundry.Menu requires Foundry 1.0. Require it in your TOC:

## Dependencies: Foundry-1.0

Then access the module:

local F = _G.Foundry_1_0
local m = F.Menu:New({ builder = myFn })

API_VERSION = 1 · F:RequireModule("Menu", 1)


1. Mission

Every addon that opens context menus or attaches persistent dropdowns repeats the same two callsites by hand: MenuUtil.CreateContextMenu(owner, fn) for one-shot context menus and button:SetupMenu(fn) for persistent dropdown generators. Both are simple to get wrong over time — the generator fires every open, the builder must be rebuilt from scratch each time, and cleanup requires a flag check because neither entry point offers a public removal API. Foundry.Menu encapsulates that pattern into a single factory: one :New call produces a controller that owns the entry-point dispatch, the named-registration duplicate-refusal, and the in-place destroy wrapper.

Foundry.Menu is present on all supported WoW clients: Retail 11.0+, Classic Era 1.15.x, Pandaria Classic 5.5.x, and TBC Classic 2.5.x. Blizzard_Menu and MenuUtil ship on all of these flavors; there is no fallback path and no UIDropDownMenu bridge. If MenuUtil is absent on a given client, :New calls F:RaiseDevError and returns without registering anything — Foundry does not silently no-op.

What the module does: entry-point dispatch via MenuUtil.CreateContextMenu and button:SetupMenu, the duplicate-refusal registry, the generatorWrapper closure that carries the in-place destroy flag, and the standard escape-hatch :GetNativeHandles() for reaching raw Blizzard objects.

What the module does not do: wrap rootDescription:Create* methods, provide a Menu.ModifyMenu bridge, offer UIDropDownMenu or EasyMenu compatibility, alias MenuResponse, support programmatic menu dismissal, or provide secure or protected menu behavior. The consumer owns all menu content and calls Blizzard's Create* methods directly on the raw rootDescription object.


2. F.Menu:New(config) — the factory

local F = _G.Foundry_1_0

local menu = F.Menu:New({
    name    = "HS.ContextMenu",   -- optional: duplicate-refusal key
    builder = function(owner, rootDescription, ...)
        rootDescription:CreateTitle("Homestead")
        rootDescription:CreateCheckbox("Show Map Pins", getter, setter)
        local pinColor = rootDescription:CreateButton("Pin Color")  -- no callback = submenu
        pinColor:CreateRadio("Gold", isGold, setGold)
        rootDescription:CreateDivider()
        local btn = rootDescription:CreateButton("Open Settings", openSettings)
        btn:SetEnabled(canOpen)
        btn:SetTooltip(function(tip, el)
            GameTooltip_SetTitle(tip, "Requires open panel")
        end)
    end,
})

:New returns a controller object. The controller owns the generatorWrapper closure used by both entry-point methods and the name key in Foundry's live registry. No event frame is created; Menu registers no WoW engine events.

Config fields

Field Type Required Default Meaning
builder function yes — function(owner, rootDescription, ...) — called every time the menu opens. Receives the same owner and raw Blizzard rootDescription that Blizzard passes to inline generators. Extra args forwarded from :CreateContextMenu.
name non-empty string no "F.Menu.anon.N" (N = incrementing module counter, never reused in a session) The duplicate-refusal key stored in Foundry's module-level live registry. Two live controllers with the same name are refused. Freed when the controller is :Destroy()-ed.

Atomic validation

Validation is atomic. :New inspects every field before constructing the generatorWrapper closure or touching any Blizzard API. If any field is invalid, Foundry calls F:RaiseDevError(...) with a "Menu:New: ..." prefix and returns without registering anything. Prior registrations by other controllers are never touched.

Validation order:

  1. config — must be a table.
  2. config.builder — must be a function.
  3. config.name — must be nil or a non-empty string; if nil, resolved to "F.Menu.anon.N" where N is an incrementing module-level counter, never reused within a session.
  4. Duplicate-key check — if the resolved name already belongs to a live controller, the call is refused.
  5. Feature detection — hasMenuUtil() is checked last, after all field validation passes. This ensures config errors surface as config errors rather than as client-incompatibility errors.

Duplicate-refusal registry

Foundry keeps a module-level liveKeys table mapping every active name string to true. A second :New with a key already in that table is refused and leaves existing registrations untouched. The key is freed only when :Destroy() is called on the controller that owns it.

Anonymous controllers (those without an explicit name) receive a generated key that is also tracked in liveKeys. These accumulate for the lifetime of the controller; calling :New inside a per-click handler or event callback creates a new anonymous controller on every invocation and leaks entries. Create controllers once — typically in OnInitialize or at module-level setup — and store them as fields on the module table.

Builder receives Blizzard's raw objects

The builder signature — function(owner, rootDescription, ...) — matches Blizzard's own inline-generator convention exactly. rootDescription is the live Blizzard object; your builder calls :CreateTitle, :CreateButton, :CreateCheckbox, :CreateRadio, and :CreateDivider directly on it. Foundry does not proxy or intercept those calls. For :SetupDropdown, owner is the DropdownButton frame itself.


3. Feature detection

Foundry detects MenuUtil by value inspection, not by version check:

local function hasMenuUtil()
    return type(_G.MenuUtil) == "table"
        and type(_G.MenuUtil.CreateContextMenu) == "function"
end

This check runs at :New time, not at file scope. Foundry does not probe the global at load; it waits until a registration is actually requested. The module loads cleanly on all clients, but :New fails loud on any client where MenuUtil is absent.

Blizzard_Menu ships on all currently supported WoW flavors — Retail 11.0+, Classic Era 1.15.x, Pandaria Classic 5.5.x, and TBC Classic 2.5.x — so this check passes everywhere on the supported matrix. The guard exists as house-style defense against any future client that removes or renames the API. There is no legacy path, no UIDropDownMenu bridge, and no LibUIDropDownMenu dependency. Foundry does not silently no-op; if hasMenuUtil() returns false, :New calls F:RaiseDevError and returns nil.


4. Controller methods

Every method refuses on a destroyed controller with F:RaiseDevError("Menu:<Method> called on a destroyed controller").

:CreateContextMenu(owner, ...)

Opens a one-shot context menu anchored near owner. Calls MenuUtil.CreateContextMenu(owner, generatorWrapper, ...), forwarding any extra args after owner to your builder after rootDescription. The generatorWrapper closure checks _destroyed before calling your builder; if the controller has been destroyed, the wrapper returns immediately and no menu appears.

Calling :CreateContextMenu on a destroyed controller raises a dev error via refuseIfDestroyed — this is the direct-call loud path, distinct from the silent no-op that fires when Blizzard re-invokes an already-installed wrapper after :Destroy().

:SetupDropdown(button)

Installs a persistent generator on a Blizzard DropdownButton frame by calling button:SetupMenu(generatorWrapper). The same generatorWrapper closure is reused; it fires on every open and rebuilds the menu from scratch each time. Your builder receives the DropdownButton as owner and the fresh rootDescription.

:SetupDropdown is called once per button — typically from OnInitialize or module setup — not on every open. Calling :SetupDropdown on a destroyed controller raises a dev error via refuseIfDestroyed (the direct-call loud path). If the controller is later destroyed while the DropdownButton still exists, Blizzard firing the installed wrapper on a player-click is a silent no-op: the wrapper checks _destroyed and returns early without populating rootDescription. This is the designed teardown path — identical to Tooltip's pattern — because button:SetupMenu has no public removal API.

:Destroy()

Marks the controller destroyed, frees the name key from Foundry's liveKeys table, and releases internal references. Idempotent: a second :Destroy() is a silent no-op.

liveKeys[name] is cleared first, before _destroyed is set and before _name is nilled, so the key is freed while it is still readable. After :Destroy():

  • A direct :CreateContextMenu or :SetupDropdown call raises a dev error (loud refusal via refuseIfDestroyed).
  • A DropdownButton whose generator was installed via :SetupDropdown may still be on screen and clickable. If the player opens it, Blizzard fires the wrapper; the wrapper checks _destroyed and returns immediately without populating rootDescription. This silent exit is by design — the generator cannot be unregistered from Blizzard's frame.
  • The same name key becomes available for a new :New call.

What :Destroy() does not do: it does not unregister generatorWrapper from any Blizzard frame. The wrapper remains installed on any DropdownButton that received :SetupDropdown, but it exits in one branch after the flag check and adds no further cost.

:GetNativeHandles()

Returns the raw Blizzard objects this controller was built against. A fresh table is returned on every call; mutating the returned table does not corrupt controller state.

Key Value
menuUtil _G.MenuUtil as read at call time.
menu _G.Menu as read at call time. May be nil on clients where _G.Menu is not exposed.

Both values are read at call time, not snapshotted at :New time. Called on a destroyed controller, the method raises a dev error and returns nil.


5. MenuResponse

MenuResponse is a global table set by Blizzard_Menu. Foundry.Menu does not alias or re-export it — consumers access it directly at runtime, exactly as they access any other Blizzard global. Do not capture MenuResponse in a file-scope upvalue; access it at runtime in your builder or callback.

The most common field in addon code is MenuResponse.Refresh: returning it from a button callback keeps the menu open and re-renders all frames in place, allowing fast multi-click interactions without reopening the menu each time. MenuResponse.Open, .Close, and .CloseAll are also available.

local menu = F.Menu:New({
    name    = "NS.PauseSurface",
    builder = function(owner, rootDescription, ...)
        rootDescription:CreateTitle("Pause Surfaces")
        rootDescription:CreateButton("Cycle Forward", function()
            NS.PauseState.CycleSurface(key, "forward")
            return MenuResponse.Refresh   -- keeps menu open, re-renders in place
        end)
        rootDescription:CreateButton("Cycle Back", function()
            NS.PauseState.CycleSurface(key, "back")
            return MenuResponse.Refresh
        end)
        rootDescription:CreateDivider()
        rootDescription:CreateButton("Open Settings", openSettings)
    end,
})

MenuResponse.Refresh returning from a callback is confirmed addon-accessible and working in production. The remaining field values are accessible from Blizzard's global; verify specific values with /run DevTools_Dump(MenuResponse) if you need the raw numbers.


6. rootDescription — Blizzard's menu content API

Your builder receives Blizzard's raw rootDescription object. Call Create* methods on it directly — Foundry does not proxy, wrap, or intercept them. The root and every returned elementDescription (including submenu entries) share the same Create* interface.

Item-type methods (v1)

Method Description
:CreateTitle(text) Non-interactive title label. Returns an elementDescription.
:CreateButton(text, callback, ...) Clickable button. callback is optional — omitting it (or passing nil) produces a flyout submenu: the returned elementDescription accepts the same Create* calls as the root.
:CreateCheckbox(text, getter, setter, data) Checkbox item. getter is called each time the menu renders to determine check state; setter is called on click. data is passed through to both.
:CreateRadio(text, isSelectedFn, setterFn, data) Radio item. isSelectedFn determines the selection highlight; setterFn is called on click. data is passed through to both.
:CreateDivider() Visual separator line. Returns an elementDescription.

Per-item configuration

Each Create* call returns an elementDescription on which you can call:

Method Description
:SetEnabled(bool) Pass false to grey the item and prevent its callback from firing.
:SetTooltip(function(tooltip, elementDesc) ... end) Attaches a tooltip shown on hover. The function receives the tooltip frame and the element descriptor; call GameTooltip_SetTitle or equivalent inside it.

Submenus

A CreateButton call that receives no callback (or an explicit nil) acts as a flyout submenu parent. The returned elementDescription exposes the same Create* interface:

local colorMenu = rootDescription:CreateButton("Pin Color")  -- no callback
colorMenu:CreateRadio("Gold",  isGold,  setGold)
colorMenu:CreateRadio("White", isWhite, setWhite)
colorMenu:CreateRadio("Red",   isRed,   setRed)

Hovering the parent item opens a flyout; child items are navigable and interactive.

Out-of-v1-scope methods

Methods such as :SetGridMode, :SetOnEnter, :SetOnLeave, :SetData, :SetResponse, and :SetSoundKit are available raw on the Blizzard elementDescription objects your builder receives. Foundry does not expose them through any wrapper; access them directly on the returned elementDescription if you need them.


7. Worked examples

Example 1 — Context menu with submenus, disabled item, and tooltip

Register the controller once from your module's initialization, not inside a click handler. Call :CreateContextMenu on every click or right-click event.

local F = _G.Foundry_1_0

local MapPanel = {}

function MapPanel:Initialize()
    self.contextMenu = F.Menu:New({
        name    = "HS.ContextMenu",
        builder = function(owner, rootDescription, isPoppedOut)
            rootDescription:CreateTitle("Homestead")

            -- Checkbox that reads and writes live state
            rootDescription:CreateCheckbox(
                "Show Map Pins",
                function() return HA.Addon.db.global.showMapPins end,
                function() HA.Addon.db.global.showMapPins = not HA.Addon.db.global.showMapPins end
            )

            -- Submenu via CreateButton with no callback
            local pinColor = rootDescription:CreateButton("Pin Color")
            pinColor:CreateRadio("Gold",  function() return MapPanel:GetColor() == "gold"  end, function() MapPanel:SetColor("gold")  end)
            pinColor:CreateRadio("White", function() return MapPanel:GetColor() == "white" end, function() MapPanel:SetColor("white") end)
            pinColor:CreateRadio("Blue",  function() return MapPanel:GetColor() == "blue"  end, function() MapPanel:SetColor("blue")  end)

            -- Nested submenu
            local pinSize = rootDescription:CreateButton("Pin Size")
            pinSize:CreateRadio("Small",  function() return MapPanel:GetSize() == "small"  end, function() MapPanel:SetSize("small")  end)
            pinSize:CreateRadio("Medium", function() return MapPanel:GetSize() == "medium" end, function() MapPanel:SetSize("medium") end)
            pinSize:CreateRadio("Large",  function() return MapPanel:GetSize() == "large"  end, function() MapPanel:SetSize("large")  end)

            -- Conditional item (disabled with tooltip)
            rootDescription:CreateDivider()
            local settingsBtn = rootDescription:CreateButton("Open Settings", function()
                HA.OptionsFrame:Show()
            end)
            if isPoppedOut then
                settingsBtn:SetEnabled(false)
                settingsBtn:SetTooltip(function(tip, el)
                    GameTooltip_SetTitle(tip, "Close the popped-out panel first")
                end)
            end
        end,
    })
end

function MapPanel:ShowContextMenu(owner, isPoppedOut)
    -- Extra args after owner are forwarded to builder after rootDescription
    self.contextMenu:CreateContextMenu(owner, isPoppedOut)
end

Call MapPanel:Initialize() from your lifecycle OnEnable or equivalent. Do not call it at file scope — Blizzard globals must be accessed at runtime.

Example 2 — Persistent dropdown

:SetupDropdown installs a generator on a Blizzard DropdownButton frame. The generator fires on every open and rebuilds the menu from scratch using current runtime state each time. Call :SetupDropdown once at setup, not on every open.

local F = _G.Foundry_1_0

local Controls = {}

-- Call once per dropdown row at initialization time.
-- row.key, row.label, row.values, and row.set are provided by the caller.
function Controls.CreateDropdown(parent, row)
    local button = CreateFrame("DropdownButton", nil, parent, "WowStyle1DropdownTemplate")
    -- ... position the button ...

    local dropController = F.Menu:New({
        name    = "HS.Options." .. row.key,
        builder = function(dropdown, rootDescription)
            rootDescription:CreateTitle(row.label)
            for _, entry in ipairs(row.values) do
                rootDescription:CreateRadio(
                    entry.label,
                    function() return row.get() == entry.key end,
                    function() row.set(entry.key) end
                )
            end
        end,
    })

    -- Install the persistent generator on the button.
    -- Every time the player clicks the button, the builder runs fresh.
    dropController:SetupDropdown(button)

    return button, dropController
end

The generator receives (dropdown, rootDescription) where dropdown is the DropdownButton frame. Because the generator runs on every open, it always reflects the latest values of any runtime state it reads — no manual refresh call is needed.


8. What Foundry.Menu does not do

  • Menu.ModifyMenu (hook existing Blizzard menus). No public unregister API exists for Menu.ModifyMenu; registration is session-permanent. _G.Menu is reachable via :GetNativeHandles().menu for consumers who need this.
  • Wrapper over rootDescription:Create* API. The consumer calls Blizzard's methods directly on the raw rootDescription. A parallel Foundry-flavored Create* surface would duplicate Blizzard's API, require ongoing maintenance against Blizzard changes, and silently drop methods (:SetGridMode, :CreateColorSwatch, and others) the raw object provides for free.
  • UIDropDownMenu / EasyMenu compatibility. Foundry.Menu does not wrap or bridge the deprecated system. Consumers migrating from EasyMenu or UIDropDownMenuTemplate frames replace the old callsite with :New + :CreateContextMenu; the old frame and its template name are not carried forward.
  • Programmatic menu dismissal. No consumer requires this; no reliable public API exists for it.
  • F.Menu.Response alias. MenuResponse is a Blizzard global; consumers access it directly at runtime as MenuResponse.Refresh. Aliasing it at file scope would violate the no-upvalue-at-file-scope rule without a confirmed load-order guarantee for Blizzard_Menu.
  • Secure / protected menu behavior. Out of scope per Charter §3.3.
  • Widget or options framework. Out of scope per Charter §3.3. Foundry.Menu is a thin dispatch bridge, not a general UI system.

9. Escape hatch: GetNativeHandles()

When you need a Blizzard object that Foundry.Menu does not expose through its own API, drop to the native surface without removing the controller:

local handles = menu:GetNativeHandles()
-- handles.menuUtil  == _G.MenuUtil   (always present on supported clients)
-- handles.menu      == _G.Menu       (may be nil if _G.Menu is absent)

The returned table is a fresh table on every call. Mutating it does not affect the controller. The objects inside are live references; reading or calling methods on them reaches the live Blizzard state directly.

Common reasons to use this:

  • You need to call Menu.ModifyMenu to hook an existing Blizzard menu (the only Foundry.Menu v1 out-of-scope operation that is reachable this way).
  • You want to inspect handles.menuUtil during debugging — for example to verify the global is still the object you expect.
  • A Blizzard API you are calling expects the raw MenuUtil object rather than going through a Foundry wrapper.

If you find yourself reaching into native handles to work around a missing controller method, that is a signal the missing method belongs in Foundry.Menu. File a feature request instead of building a permanent workaround on top of the escape hatch.

Called on a destroyed controller, :GetNativeHandles raises a dev error and returns nil — the same refusal as every other post-Destroy method call.


10. Extending Blizzard-owned tagged menus

Foundry.Menu's controller API (:CreateContextMenu, :SetupDropdown) is for menus your addon owns and builds from scratch. To extend a menu Blizzard owns instead, such as a world map filter dropdown, use the raw Menu.ModifyMenu(tag, callback) global directly; a controller's :GetNativeHandles() hands back the raw Menu table for exactly this case, and Foundry.Menu has no separate wrapper for it.

Two disciplines apply.

First, register once per tag from your own idempotent init path: a second registration for the same tag adds an independent duplicate callback rather than replacing the first, and if that tag's menu was already built this session, the duplicate's section appears immediately, appended after the first.

Second, read live state from inside the callback body: Blizzard fires the callback every time it builds that tagged menu's description (every open, plus some dropdown refreshes), and also once immediately at registration if the tag was already built this session.

Tag names are addon-facing string identifiers; Blizzard documents the UnitPopup convention (MENU_UNIT_<UNIT_TYPE>) in its own implementation guide, and any tag can be discovered at runtime via the EventTrace Menu.OpenMenuTag event or Menu.PrintOpenMenuTags().

Clone this wiki locally