feat(locale): locale hotloading

This commit is contained in:
Linden
2024-04-01 19:16:53 +11:00
parent 09ca963f26
commit 1e3b2cb567
4 changed files with 49 additions and 10 deletions

View File

@@ -38,10 +38,12 @@ function lib.getLocales()
end end
---Loads the ox_lib locale module. Prefer using fxmanifest instead (see [docs](https://overextended.dev/ox_lib#usage)). ---Loads the ox_lib locale module. Prefer using fxmanifest instead (see [docs](https://overextended.dev/ox_lib#usage)).
function lib.locale() function lib.locale(key)
local lang = GetConvar('ox:locale', 'en') local lang = key or lib.getLocaleKey()
local locales = json.decode(LoadResourceFile(cache.resource, ('locales/%s.json'):format(lang))) local locales = json.decode(LoadResourceFile(cache.resource, ('locales/%s.json'):format(lang)))
table.wipe(dict)
if not locales then if not locales then
local warning = "could not load 'locales/%s.json'" local warning = "could not load 'locales/%s.json'"
warn(warning:format(lang)) warn(warning:format(lang))
@@ -104,4 +106,8 @@ exports('getLocale', function(key)
return dict[key] return dict[key]
end) end)
AddEventHandler('ox_lib:setLocale', function(key)
lib.locale(key)
end)
return lib.locale return lib.locale

View File

@@ -1,15 +1,33 @@
local settings = require 'resource.settings'
local function loadLocaleFile(key)
local file = LoadResourceFile(cache.resource, ('locales/%s.json'):format(key))
or LoadResourceFile(cache.resource, 'locales/en.json')
return file and json.decode(file) or {}
end
function lib.getLocaleKey() return settings.locale end
---@param key string
function lib.setLocale(key)
settings.locale = key
SetResourceKvp('locale', key)
TriggerEvent('ox_lib:setLocale', key)
SendNUIMessage({
action = 'setLocale',
data = loadLocaleFile(key)
})
end
RegisterNUICallback('init', function(_, cb) RegisterNUICallback('init', function(_, cb)
cb(1) cb(1)
SendNUIMessage({
action = 'loadLocales',
data = {}
})
local JSON = LoadResourceFile(cache.resource, ('locales/%s.json'):format(GetConvar('ox:locale', 'en'))) or LoadResourceFile(cache.resource, 'locales/en.json')
SendNUIMessage({ SendNUIMessage({
action = 'setLocale', action = 'setLocale',
data = JSON and json.decode(JSON) or {} data = loadLocaleFile(settings.locale)
}) })
end) end)
lib.locale(settings.locale)

View File

@@ -0,0 +1 @@
function lib.getLocaleKey() return GetConvar('ox:locale', 'en') end

14
resource/server.lua Normal file
View File

@@ -0,0 +1,14 @@
local locales, localesN = lib.getFilesInDirectory('locales', '%.json')
for i = 1, localesN do
local key = locales[i]
local value = key:gsub('%.json', '')
local label = (json.decode(LoadResourceFile(lib.name, ('locales/%s'):format(key)) or '') or '').language or value
locales[i] = { label = label, value = value }
end
table.sort(locales, function(a, b)
return a.label < b.label
end)
GlobalState['ox_lib:locales'] = locales