promotional bannermobile promotional banner

Nsk

Shared core library for Nosink addons: client detection, event bus, database, localization, settings panel, slash commands, windows and minimap button.

Nsk (lib)

Shared core library for Nosink's World of Warcraft addons: client detection, event bus, layered SavedVariables database, addon lifecycle, localization, read-only enums, chat output, slash commands, a settings store, a vertical settings panel, movable windows and a minimap button.

Nsk is a library registered with LibStub as Nsk-1.0. It works both as a standalone addon and as a copy embedded inside each addon (libs/Nsk/): LibStub keeps the highest revision loaded, so an addon works even when the standalone Nsk is not installed.

Supports every flavor listed in Nsk.toc (## Interface).

Features

  • Event bus for native WoW events and internal addon events, with safe (pcall) handlers and duplicate-safe secure hooks.
  • Layered SavedVariables database with per-character and account-wide defaults.
  • Lifecycle that loads the database and announces when the addon is ready and enters the world, in the right order.
  • Localization that falls back to the key when a translation is missing.
  • Client detection: flavor (Retail, Classic Era, Forever, the Classic expansions), expansion, interface version and game mode (Hardcore, Season of Discovery, fresh realms, Timerunning…), with one call to check them all.
  • Read-only enums, preloaded with class IDs, unit reactions, expansion levels, flavors and game modes.
  • Chat output prefixed with the addon name.
  • Slash commands with the standard settings, version, minimap and help commands built in.
  • Combat queue that holds protected changes until combat ends.
  • Settings store that writes settings and notifies every change.
  • Vertical settings panel on Blizzard's modern Settings API: sections, check boxes, sliders, drop downs, dependent options and custom rows. Opening it during combat waits until combat ends.
  • Movable windows that remember their position and close with Escape.
  • Minimap button for any minimap shape, with AddOn Compartment entry and Broker launcher.
  • Works standalone or embedded in each addon; LibStub keeps the highest revision loaded.

Usage

<Addon>.toc:

## OptionalDeps: Nsk
## X-Embeds: Nsk

# Nsk
addon/nsk.lua
addon/defaults.lua
...
addon.lua
  • ## OptionalDeps: Nsk loads the standalone Nsk first when it is installed, without making the addon depend on it.
  • ## X-Embeds: Nsk tells build.ps1 to copy Nsk into <Addon>/libs/Nsk/ inside the zip. The copy only exists in the package, never in the addon's repository.
  • # Nsk marks where the embedded copy loads. build.ps1 inserts libs/Nsk/Nsk.xml after it in the packaged .toc only; never write that line in the repository. During development the folder does not exist and the junctioned standalone Nsk is used instead, with no missing-file warning.

addon/nsk.lua must be the first file of the addon:

local name, ns = ...

LibStub("Nsk-1.0"):Embed(name, ns)

addon.lua, the last file, starts the lifecycle:

local _, ns = ...

ns.lifecycle.Start()

On VARIABLES_LOADED it loads the database (ns.db) and fires name .. "_VARIABLES_LOADED". Every PLAYER_ENTERING_WORLD fires name .. "_PLAYER_ENTERING_WORLD" with isInitialLogin, never before name .. "_VARIABLES_LOADED".

After Embed the namespace exposes:

Field Module
ns.client The running client: flavor, expansion, interfaceVersion, GetGameMode(), Matches(criteria) (see Client)
ns.expansion Same as ns.client.expansion, kept for addons built with older Nsk
ns.enums, ns.RegisterEnum(name, values) Read-only enums, preloaded with classID, reaction, expansion, flavor, gameMode
ns.bus RegisterEvent(event, fn) (returns an unsubscribe function), RegisterEventOnce(event, fn), TriggerEvent(event, ...), Forward(sourceEvent, targetEvent) (relays the payload), for native and internal events
ns.HookSecureFunc, ns.HookScript Duplicate-safe hooks
ns.database.Register, ns.database.Load, ns.database.RemoveKeys, ns.db SavedVariables <Addon>DB / <Addon>PCDB with defaults cascade; RemoveKeys(keys) deletes obsolete keys from both
ns.lifecycle Start(): loads the database and fires the addon's lifecycle events
ns.L, ns.locale Translations, falling back to the key
ns.chat Print(message) with the addon name as prefix, PrintDetail(message) indented, Colorize(color, text)
ns.slashCommands Register(definition): slash commands with the standard ones built in
ns.settingsStore Get, Set (write and notify), Toggle, Write, GetDefault, Watch(keys, handler) (handler(value, key) on every change of a key or a list of keys, returns an unsubscribe function), CHANGED_EVENT
ns.combatQueue Run(key, action): runs action now, or after combat when in combat (the latest action per key wins)
ns.settingsPanel Create(title): vertical layout settings panel on the modern Settings API, with sub-pages through AddSubpage(title); Open(): opens the addon's settings; SetValue(key, value): changes a setting so the open page shows it
ns.settingsCategory Set when a panel registers
ns.window Create(options), SetTitle, RestorePosition, ResetPosition, SetMoveTarget: movable windows
ns.minimapButton Create(options): minimap button (any minimap shape, draggable), plus AddOn Compartment entry and Broker launcher when available

Client

ns.client tells which game client the addon runs on. No single API is enough: GetExpansionLevel() reports the Classic expansion on both Classic Era and Forever, and on Retail it depends on the expansions the account owns. So Nsk combines the interface version from GetBuildInfo(), WOW_PROJECT_ID and the expansion level:

  • Every client is told apart by WOW_PROJECT_ID (Forever reports 16 in game, not the 18 the wiki lists). Titan Reforged shares Wrath Classic's and is told apart by its 3.80 interface version.
  • An unknown project with a 1.x interface falls back to the interface version: Classic Era below 1.60, Forever from 1.60. Any other unknown project is UNKNOWN.
  • Retail takes the expansion from the interface version; every other client from GetExpansionLevel(), which there is the expansion of the client.
Field Value
flavor ns.enums.flavor: RETAIL, CLASSIC_ERA, FOREVER, BURNING_CRUSADE_CLASSIC, WRATH_CLASSIC, TITAN_REFORGED, CATACLYSM_CLASSIC, MISTS_CLASSIC, or UNKNOWN for a project Nsk does not know yet
expansion ns.enums.expansion whose game rules the client runs
interfaceVersion The client's ## Interface number, e.g. 11509
GetGameMode() ns.enums.gameMode of the current realm and character: STANDARD, HARDCORE, SEASON_OF_MASTERY, SEASON_OF_DISCOVERY, FRESH, FRESH_HARDCORE or TIMERUNNING, read from C_Seasons, C_GameRules.IsHardcoreActive and PlayerIsTimerunning on every call
Matches(criteria) true when the client meets every criterion given
Flavor Interface Expansion
RETAIL 120105 MIDNIGHT
MISTS_CLASSIC 50504 MISTS_OF_PANDARIA
CATACLYSM_CLASSIC 40402 CATACLYSM
TITAN_REFORGED 38002 WRATH_OF_THE_LICH_KING
WRATH_CLASSIC 30405 WRATH_OF_THE_LICH_KING
BURNING_CRUSADE_CLASSIC 20506 BURNING_CRUSADE
FOREVER 16001 CLASSIC
CLASSIC_ERA 11509 CLASSIC
local flavor, gameMode, expansion = ns.enums.flavor, ns.enums.gameMode, ns.enums.expansion

local isVanillaHardcore = ns.client.Matches({
    flavors = { flavor.CLASSIC_ERA, flavor.FOREVER },
    gameModes = { gameMode.HARDCORE, gameMode.FRESH_HARDCORE },
})

local hasRangedSlot = ns.client.Matches({ expansion = { max = expansion.CATACLYSM } })

Every criterion is optional: flavors and gameModes accept any value of their list, and expansion and interfaceVersion take a range with min, max or both. Matches({}) is always true. It is the building block for loading different code per client.

Slash commands

ns.slashCommands.Register({
    commands = { "/myaddon", "/ma" },
    minimapButtonKey = "showMinimapButton",
    actions = {
        { argument = "reset", run = resetWindows, help = L["COMMAND_RESET_HELP"] },
        { argument = "debug", run = toggleDebug },
    },
})

Every command in commands runs the same handler (SLASH_<ADDON>1, SLASH_<ADDON>2…). No argument or config, options, settings opens the settings; v or version prints the version; minimap toggles the boolean setting minimapButtonKey, when given. Each action runs run for its argument; actions with help are listed in the help, which any other argument prints, using the shortest command.

Vertical settings panel

local panel = ns.settingsPanel.Create(L["NAME"])

panel:AddSection(L["SECTION"])
panel:AddCheckBox(L["ENABLED"], "enabled", L["ENABLED_TOOLTIP"])
panel:AddSlider(L["SCALE"], "scale", L["SCALE_TOOLTIP"], { min = 0.5, max = 2, step = 0.1 }, ns.settingsPanel.FormatRatioAsPercent)
panel:DependsOn("enabled")
panel:AddDropDown(L["MODE"], "mode", L["MODE_TOOLTIP"], { { value = "A", text = L["MODE_A"] } })
panel:DependsOn("enabled")

panel:Register()

Every key needs a registered default. AddSlider(label, key, tooltip, range, formatter) takes { min, max, step } and an optional label formatter: ns.settingsPanel.FormatRatioAsPercent (0.5 → 50%), FormatPercent (50 → 50%), FormatPixels, FormatWholeNumber or FormatSeconds, or any function. DependsOn(parentKey) applies to the setting added just before it: it is indented under the boolean setting parentKey (added earlier) and disabled while that setting is off. DependsOn(parentKey, false) (Nsk 1.7.0+) inverts it: the control is disabled while the setting is on. Register() returns the category, or nil when the client has no modern Settings API.

AddColorPicker(label, key, tooltip) (Nsk 1.7.0+) adds a color swatch that opens Blizzard's color picker, without opacity (use a slider for it). The setting is an opaque "ffRRGGBB" hex string (default such as "ffffffff"); read it with CreateColorFromHexString(ns.db[key]):GetRGB(). The setting changes while the player drags in the picker, and Cancel restores the color it had when the picker opened. Unlike Blizzard's own swatch, it does not open while DependsOn disables it. Above the hex box, a Class color button picks the player's class color; it shows only in pickers Nsk opened.

AddPosition(label, xKey, yKey, tooltip, options) (Nsk 1.7.0+) adds a taller row with an X and a Y box on one line and four arrow buttons. Typing a number and pressing Enter (or leaving the box) writes it; Escape restores the stored value. An arrow moves 1 px, Shift-click 10 px. Values are written with ns.settingsStore.Set as whole numbers, so the addon applies them by watching xKey and yKey. They are not registered as Blizzard settings, so Defaults leaves them alone and their defaults may be any value, such as false for "not placed yet". While either value is not a number, the row shows and moves from options.readCurrent() (returns x, y) when given, and is empty otherwise. DependsOn works on it like on any control.

panel:AddCheckBox(L["CUSTOM_POSITION"], "customPosition", L["CUSTOM_POSITION_TOOLTIP"])
panel:AddPosition(L["POSITION"], "x", "y", L["POSITION_TOOLTIP"], { readCurrent = readFramePosition })
panel:DependsOn("customPosition")

On clients without the Settings color swatch or the color picker, the setting is registered without a control.

For controls the list does not offer, register the settings without a control and add your own row (Nsk 1.3.0+):

panel:AddSetting(L["SHOW_BAGS"], "showBags")
panel:AddInitializer(function(category)
    return Settings.CreateElementInitializer("MyAddonRowTemplate", { name = L["ROW"] })
end)

AddSetting(label, key) registers the setting in the category, so the page's Defaults button resets it, but draws nothing. AddInitializer(createInitializer) calls createInitializer(category) while the panel registers and adds the returned initializer to the page at that position; returning nil skips it. The row's frame template must be defined in XML.

panel:AddSubpage(title) (Nsk 1.7.0+) adds a sub-page under the panel: the AddOns list shows it under the addon's [+]. The sub-page has the same AddSection, AddCheckBox, AddSlider, AddDropDown, AddColorPicker, AddPosition, AddSetting, AddInitializer, DependsOn and AddSubpage methods, and the panel's Register() registers it, so a sub-page has no Register(). DependsOn links settings on the same page only. Sub-pages appear in the order they were added.

local panel = ns.settingsPanel.Create(L["NAME"])
panel:AddCheckBox(L["ENABLED"], "enabled", L["ENABLED_TOOLTIP"])

local tooltipPage = panel:AddSubpage(L["TOOLTIP"])
tooltipPage:AddCheckBox(L["SHOW_PRICE"], "showPrice", L["SHOW_PRICE_TOOLTIP"])

panel:Register()

ns.settingsPanel.Open() opens ns.settingsCategory. During combat it waits until combat ends. It returns false when there is nothing to open.

ns.settingsPanel.SetValue(key, value) (Nsk 1.7.0+) sets a setting through its registered control, so the open page shows the new value and dependent controls are enabled or disabled; it fires name .. "_SETTINGS_CHANGED" like ns.settingsStore.Set. Use it when one action changes several settings at once, such as a preset button. Without a registered control (or before the panel registers) it falls back to ns.settingsStore.Set.

LibStub("Nsk-1.0") returns the library and its revision. It errors when Nsk is not loaded; LibStub("Nsk-1.0", true) returns nil instead.

Windows

local window = ns.window.Create({
    name = "MyAddonWindow",
    positionKey = "windowPosition",
    width = 400,
    height = 300,
    strata = "DIALOG",
    portraitIcon = "Interface\\Icons\\inv_misc_questionmark",
})
ns.window.SetTitle(window, L["NAME"])

A hidden ButtonFrameTemplate window without its button bar, closed by its close button and by Escape (name is its global name, listed in UISpecialFrames). Dragging it saves its position in the ns.db key positionKey (register a default, e.g. false). strata and portraitIcon are optional; without portraitIcon the portrait is hidden. ResetPosition(window) forgets the saved position and centers it; SetMoveTarget(window, target) makes dragging move target instead (nil restores the window's own position).

Minimap button

ns.minimapButton.Create({
    name = "MyAddonMinimapButton",
    title = "MyAddon",
    angleKey = "minimapButtonAngle",
    shownKey = "showMinimapButton",
    clickHint = L["LAUNCHER_HINT_LEFT"],
    onClick = function(mouseButton, owner) end,
    onTooltip = function(tooltip) end,
})

It can be called at any time: the button is created once the database is loaded. angleKey is an ns.db key (register a default such as 225) where the dragged position is saved. name is the button's global name, so minimap button collectors can find it. icon defaults to the addon's ## IconTexture, iconSize (Nsk 1.6.0+) to 17 pixels (the icon stays centered in the ring at any size), and titleColor to gold.

Right-click opens the settings. With shownKey, a boolean setting, the button follows it and Shift-click turns it off. Any other click calls onClick with the mouse button and the frame that was clicked, to anchor a menu to. The tooltip, also shown on the AddOn Compartment entry and the Broker launcher, has the title and version, the lines added by onTooltip, clickHint and the right-click and Shift-click hints. The returned handle has SetShown(isShown) for buttons without shownKey. The button supports round, square and every other GetMinimapShape shape.

Nsk Team

profile avatar
Owner
  • 8
    Projects
  • 31.4K
    Downloads
Donate

More from NosinkDView all