TGUI v3.0

This ports TGUI, and makes the old nano crew monitor and the disposal
bins use it as first examples.
This commit is contained in:
ShadowLarkens
2020-07-02 15:40:21 -07:00
parent a1aada03f1
commit c06a2d2cef
187 changed files with 22079 additions and 79 deletions
+1
View File
@@ -100,6 +100,7 @@ var/global/list/runlevel_flags = list(RUNLEVEL_LOBBY, RUNLEVEL_SETUP, RUNLEVEL_G
#define FIRE_PRIORITY_TICKER 60
#define FIRE_PRIORITY_PLANETS 75
#define FIRE_PRIORITY_MACHINES 100
#define FIRE_PRIORITY_TGUI 110
#define FIRE_PRIORITY_PROJECTILES 150
#define FIRE_PRIORITY_CHAT 400
#define FIRE_PRIORITY_OVERLAYS 500
+3
View File
@@ -155,6 +155,9 @@
/proc/log_unit_test(text)
to_world_log("## UNIT_TEST: [text]")
/proc/log_tgui(text)
diary << "\[[time_stamp()]]TGUI: [text][log_end]"
/proc/report_progress(var/progress_message)
admin_notice("<span class='boldannounce'>[progress_message]</span>", R_DEBUG)
to_world_log(progress_message)
+285
View File
@@ -0,0 +1,285 @@
/**
* tgui subsystem
*
* Contains all tgui state and subsystem code.
**/
SUBSYSTEM_DEF(tgui)
name = "TGUI"
wait = 9
flags = SS_NO_INIT
priority = FIRE_PRIORITY_TGUI
runlevels = RUNLEVEL_LOBBY | RUNLEVELS_DEFAULT
var/list/currentrun = list()
var/list/open_uis = list() // A list of open UIs, grouped by src_object and ui_key.
var/list/processing_uis = list() // A list of processing UIs, ungrouped.
var/basehtml // The HTML base used for all UIs.
/datum/controller/subsystem/tgui/PreInit()
basehtml = file2text('tgui/packages/tgui/public/tgui.html')
/datum/controller/subsystem/tgui/Shutdown()
close_all_uis()
/datum/controller/subsystem/tgui/stat_entry()
..("P:[processing_uis.len]")
/datum/controller/subsystem/tgui/fire(resumed = 0)
if (!resumed)
src.currentrun = processing_uis.Copy()
//cache for sanic speed (lists are references anyways)
var/list/currentrun = src.currentrun
while(currentrun.len)
var/datum/tgui/ui = currentrun[currentrun.len]
currentrun.len--
if(ui && ui.user && ui.src_object)
ui.process()
else
processing_uis.Remove(ui)
if (MC_TICK_CHECK)
return
/**
* public
*
* Get a open UI given a user, src_object, and ui_key and try to update it with data.
*
* required user mob The mob who opened/is using the UI.
* required src_object datum The object/datum which owns the UI.
* required ui_key string The ui_key of the UI.
* optional ui datum/tgui The UI to be updated, if it exists.
* optional force_open bool If the UI should be re-opened instead of updated.
*
* return datum/tgui The found UI.
**/
/datum/controller/subsystem/tgui/proc/try_update_ui(mob/user, datum/src_object, ui_key, datum/tgui/ui, force_open = FALSE)
if(isnull(ui)) // No UI was passed, so look for one.
ui = get_open_ui(user, src_object, ui_key)
if(!isnull(ui))
var/data = src_object.tgui_data(user) // Get data from the src_object.
if(!force_open) // UI is already open; update it.
ui.push_data(data)
else // Re-open it anyways.
ui.reinitialize(null, data)
return ui // We found the UI, return it.
else
return null // We couldn't find a UI.
/**
* private
*
* Get a open UI given a user, src_object, and ui_key.
*
* required user mob The mob who opened/is using the UI.
* required src_object datum The object/datum which owns the UI.
* required ui_key string The ui_key of the UI.
*
* return datum/tgui The found UI.
**/
/datum/controller/subsystem/tgui/proc/get_open_ui(mob/user, datum/src_object, ui_key)
var/src_object_key = "\ref[src_object]"
if(isnull(open_uis[src_object_key]) || !istype(open_uis[src_object_key], /list))
return null // No UIs open.
else if(isnull(open_uis[src_object_key][ui_key]) || !istype(open_uis[src_object_key][ui_key], /list))
return null // No UIs open for this object.
for(var/datum/tgui/ui in open_uis[src_object_key][ui_key]) // Find UIs for this object.
if(ui.user == user) // Make sure we have the right user
return ui
return null // Couldn't find a UI!
/**
* private
*
* Update all UIs attached to src_object.
*
* required src_object datum The object/datum which owns the UIs.
*
* return int The number of UIs updated.
**/
/datum/controller/subsystem/tgui/proc/update_uis(datum/src_object)
var/src_object_key = "\ref[src_object]"
if(isnull(open_uis[src_object_key]) || !istype(open_uis[src_object_key], /list))
return 0 // Couldn't find any UIs for this object.
var/update_count = 0
for(var/ui_key in open_uis[src_object_key])
for(var/datum/tgui/ui in open_uis[src_object_key][ui_key])
if(ui && ui.src_object && ui.user && ui.src_object.tgui_host(ui.user)) // Check the UI is valid.
ui.process(force = 1) // Update the UI.
update_count++ // Count each UI we update.
return update_count
/**
* private
*
* Close all UIs attached to src_object.
*
* required src_object datum The object/datum which owns the UIs.
*
* return int The number of UIs closed.
**/
/datum/controller/subsystem/tgui/proc/close_uis(datum/src_object)
var/src_object_key = "\ref[src_object]"
if(isnull(open_uis[src_object_key]) || !istype(open_uis[src_object_key], /list))
return 0 // Couldn't find any UIs for this object.
var/close_count = 0
for(var/ui_key in open_uis[src_object_key])
for(var/datum/tgui/ui in open_uis[src_object_key][ui_key])
if(ui && ui.src_object && ui.user && ui.src_object.tgui_host(ui.user)) // Check the UI is valid.
ui.close() // Close the UI.
close_count++ // Count each UI we close.
return close_count
/**
* private
*
* Close *ALL* UIs
*
* return int The number of UIs closed.
**/
/datum/controller/subsystem/tgui/proc/close_all_uis()
var/close_count = 0
for(var/src_object_key in open_uis)
for(var/ui_key in open_uis[src_object_key])
for(var/datum/tgui/ui in open_uis[src_object_key][ui_key])
if(ui && ui.src_object && ui.user && ui.src_object.tgui_host(ui.user)) // Check the UI is valid.
ui.close() // Close the UI.
close_count++ // Count each UI we close.
return close_count
/**
* private
*
* Update all UIs belonging to a user.
*
* required user mob The mob who opened/is using the UI.
* optional src_object datum If provided, only update UIs belonging this src_object.
* optional ui_key string If provided, only update UIs with this UI key.
*
* return int The number of UIs updated.
**/
/datum/controller/subsystem/tgui/proc/update_user_uis(mob/user, datum/src_object = null, ui_key = null)
if(isnull(user.open_tguis) || !istype(user.open_tguis, /list) || open_uis.len == 0)
return 0 // Couldn't find any UIs for this user.
var/update_count = 0
for(var/datum/tgui/ui in user.open_tguis)
if((isnull(src_object) || !isnull(src_object) && ui.src_object == src_object) && (isnull(ui_key) || !isnull(ui_key) && ui.ui_key == ui_key))
ui.process(force = 1) // Update the UI.
update_count++ // Count each UI we upadte.
return update_count
/**
* private
*
* Close all UIs belonging to a user.
*
* required user mob The mob who opened/is using the UI.
* optional src_object datum If provided, only close UIs belonging this src_object.
* optional ui_key string If provided, only close UIs with this UI key.
*
* return int The number of UIs closed.
**/
/datum/controller/subsystem/tgui/proc/close_user_uis(mob/user, datum/src_object = null, ui_key = null)
if(isnull(user.open_tguis) || !istype(user.open_tguis, /list) || open_uis.len == 0)
return 0 // Couldn't find any UIs for this user.
var/close_count = 0
for(var/datum/tgui/ui in user.open_tguis)
if((isnull(src_object) || !isnull(src_object) && ui.src_object == src_object) && (isnull(ui_key) || !isnull(ui_key) && ui.ui_key == ui_key))
ui.close() // Close the UI.
close_count++ // Count each UI we close.
return close_count
/**
* private
*
* Add a UI to the list of open UIs.
*
* required ui datum/tgui The UI to be added.
**/
/datum/controller/subsystem/tgui/proc/on_open(datum/tgui/ui)
var/src_object_key = "\ref[ui.src_object]"
if(isnull(open_uis[src_object_key]) || !istype(open_uis[src_object_key], /list))
open_uis[src_object_key] = list(ui.ui_key = list()) // Make a list for the ui_key and src_object.
else if(isnull(open_uis[src_object_key][ui.ui_key]) || !istype(open_uis[src_object_key][ui.ui_key], /list))
open_uis[src_object_key][ui.ui_key] = list() // Make a list for the ui_key.
// Append the UI to all the lists.
ui.user.open_tguis |= ui
var/list/uis = open_uis[src_object_key][ui.ui_key]
uis |= ui
processing_uis |= ui
/**
* private
*
* Remove a UI from the list of open UIs.
*
* required ui datum/tgui The UI to be removed.
*
* return bool If the UI was removed or not.
**/
/datum/controller/subsystem/tgui/proc/on_close(datum/tgui/ui)
var/src_object_key = "\ref[ui.src_object]"
if(isnull(open_uis[src_object_key]) || !istype(open_uis[src_object_key], /list))
return FALSE // It wasn't open.
else if(isnull(open_uis[src_object_key][ui.ui_key]) || !istype(open_uis[src_object_key][ui.ui_key], /list))
return FALSE // It wasn't open.
processing_uis.Remove(ui) // Remove it from the list of processing UIs.
if(ui.user) // If the user exists, remove it from them too.
ui.user.open_tguis.Remove(ui)
var/Ukey = ui.ui_key
var/list/uis = open_uis[src_object_key][Ukey] // Remove it from the list of open UIs.
uis.Remove(ui)
if(!uis.len)
var/list/uiobj = open_uis[src_object_key]
uiobj.Remove(Ukey)
if(!uiobj.len)
open_uis.Remove(src_object_key)
return TRUE // Let the caller know we did it.
/**
* private
*
* Handle client logout, by closing all their UIs.
*
* required user mob The mob which logged out.
*
* return int The number of UIs closed.
**/
/datum/controller/subsystem/tgui/proc/on_logout(mob/user)
return close_user_uis(user)
/**
* private
*
* Handle clients switching mobs, by transferring their UIs.
*
* required user source The client's original mob.
* required user target The client's new mob.
*
* return bool If the UIs were transferred.
**/
/datum/controller/subsystem/tgui/proc/on_transfer(mob/source, mob/target)
if(!source || isnull(source.open_tguis) || !istype(source.open_tguis, /list) || open_uis.len == 0)
return FALSE // The old mob had no open UIs.
if(isnull(target.open_tguis) || !istype(target.open_tguis, /list))
target.open_tguis = list() // Create a list for the new mob if needed.
for(var/datum/tgui/ui in source.open_tguis)
ui.user = target // Inform the UIs of their new owner.
target.open_tguis.Add(ui) // Transfer all the UIs.
source.open_tguis.Cut() // Clear the old list.
return TRUE // Let the caller know we did it.
+1
View File
@@ -51,6 +51,7 @@ var/global/datum/repository/crew/crew_repository = new()
crewmemberData["area"] = sanitize(A.get_name())
crewmemberData["x"] = pos.x
crewmemberData["y"] = pos.y
crewmemberData["realZ"] = pos.z
crewmemberData["z"] = using_map.get_zlevel_name(pos.z)
crewmembers[++crewmembers.len] = crewmemberData
+6 -6
View File
@@ -8,7 +8,7 @@
idle_power_usage = 250
active_power_usage = 500
circuit = /obj/item/weapon/circuitboard/crew
var/datum/nano_module/crew_monitor/crew_monitor
var/datum/tgui_module/crew_monitor/crew_monitor
/obj/machinery/computer/crew/New()
crew_monitor = new(src)
@@ -20,16 +20,16 @@
..()
/obj/machinery/computer/crew/attack_ai(mob/user)
ui_interact(user)
attack_hand(user)
/obj/machinery/computer/crew/attack_hand(mob/user)
add_fingerprint(user)
if(stat & (BROKEN|NOPOWER))
return
ui_interact(user)
tgui_interact(user)
/obj/machinery/computer/crew/ui_interact(mob/user, ui_key = "main", var/datum/nanoui/ui = null, var/force_open = 1)
crew_monitor.ui_interact(user, ui_key, ui, force_open)
/obj/machinery/computer/crew/tgui_interact(mob/user, ui_key = "main", datum/tgui/ui = null, force_open = 0, datum/tgui/master_ui = null, datum/tgui_state/state = GLOB.tgui_default_state)
crew_monitor.tgui_interact(user, ui_key, ui, force_open)
/obj/machinery/computer/crew/interact(mob/user)
crew_monitor.ui_interact(user)
crew_monitor.tgui_interact(user)
+8
View File
@@ -119,3 +119,11 @@ NOTE: It checks usr by default. Supply the "user" argument if you wish to check
holder.disassociate()
//qdel(holder)
return 1
//This proc checks whether subject has at least ONE of the rights specified in rights_required.
/proc/check_rights_for(client/subject, rights_required)
if(subject && subject.holder)
if(rights_required && !(rights_required & subject.holder.rights))
return 0
return 1
return 0
+18
View File
@@ -162,6 +162,12 @@ You can set verify to TRUE if you want send() to sleep until the client has the
/datum/asset/simple/send(client)
send_asset_list(client,assets,verify)
/datum/asset/simple/tgui
assets = list(
"tgui.bundle.js" = 'tgui/packages/tgui/public/tgui.bundle.js',
"tgui.bundle.css" = 'tgui/packages/tgui/public/tgui.bundle.css'
)
//
// iconsheet Assets - For making lots of icon states available at once without sending a thousand tiny files.
//
@@ -292,3 +298,15 @@ You can set verify to TRUE if you want send() to sleep until the client has the
send_asset_list(client, uncommon)
send_asset_list(client, common)
// Fontawesome
/datum/asset/simple/fontawesome
verify = FALSE
assets = list(
"fa-regular-400.eot" = 'html/font-awesome/webfonts/fa-regular-400.eot',
"fa-regular-400.woff" = 'html/font-awesome/webfonts/fa-regular-400.woff',
"fa-solid-900.eot" = 'html/font-awesome/webfonts/fa-solid-900.eot',
"fa-solid-900.woff" = 'html/font-awesome/webfonts/fa-solid-900.woff',
"font-awesome.css" = 'html/font-awesome/css/all.min.css',
"v4shim.css" = 'html/font-awesome/css/v4-shims.min.css'
)
+2 -2
View File
@@ -2,7 +2,7 @@
var/register_alarms = 1
var/datum/nano_module/alarm_monitor/all/alarm_monitor
var/datum/nano_module/atmos_control/atmos_control
var/datum/nano_module/crew_monitor/crew_monitor
var/datum/tgui_module/crew_monitor/crew_monitor
var/datum/nano_module/law_manager/law_manager
var/datum/nano_module/power_monitor/power_monitor
var/datum/nano_module/rcon/rcon
@@ -67,7 +67,7 @@
set category = "Subystems"
set name = "Crew Monitor"
crew_monitor.ui_interact(usr, state = self_state)
crew_monitor.tgui_interact(usr, state = GLOB.tgui_self_state)
/****************
* Law Manager *
+1
View File
@@ -1,5 +1,6 @@
/mob/Logout()
SSnanoui.user_logout(src) // this is used to clean up (remove) this user's Nano UIs
SStgui.on_logout(src) // Cleanup any TGUIs the user has open
player_list -= src
update_client_z(null)
log_access_out(src)
@@ -67,12 +67,3 @@
// should make the UI auto-update; doesn't seem to?
ui.set_auto_update(1)
/*/datum/nano_module/crew_monitor/proc/scan()
for(var/mob/living/carbon/human/H in mob_list)
if(istype(H.w_uniform, /obj/item/clothing/under))
var/obj/item/clothing/under/C = H.w_uniform
if (C.has_sensor)
tracked |= C
return 1
*/
+117 -62
View File
@@ -212,7 +212,6 @@
// leave the disposal
/obj/machinery/disposal/proc/go_out(mob/user)
if (user.client)
user.client.eye = user.client.mob
user.client.perspective = MOB_PERSPECTIVE
@@ -222,11 +221,11 @@
// ai as human but can't flush
/obj/machinery/disposal/attack_ai(mob/user as mob)
interact(user, 1)
add_hiddenprint(user)
tgui_interact(user)
// human interact with machine
/obj/machinery/disposal/attack_hand(mob/user as mob)
if(stat & BROKEN)
return
@@ -236,91 +235,147 @@
// Clumsy folks can only flush it.
if(user.IsAdvancedToolUser(1))
interact(user, 0)
tgui_interact(user)
else
flush = !flush
update()
return
// user interaction
/obj/machinery/disposal/interact(mob/user, var/ai=0)
/obj/machinery/disposal/tgui_interact(mob/user, ui_key = "main", datum/tgui/ui = null, force_open = 0, datum/tgui/master_ui = null, datum/tgui_state/state = GLOB.tgui_default_state)
ui = SStgui.try_update_ui(user, src, ui_key, ui, force_open)
if(!ui)
ui = new(user, src, ui_key, "DisposalBin", name, 300, 250, master_ui, state)
ui.open()
src.add_fingerprint(user)
if(stat & BROKEN)
user.unset_machine()
/obj/machinery/disposal/tgui_data(mob/user)
var/list/data = list()
data["isAI"] = isAI(user)
data["flushing"] = flush
data["mode"] = mode
data["pressure"] = round(clamp(100* air_contents.return_pressure() / (SEND_PRESSURE), 0, 100),1)
return data
/obj/machinery/disposal/tgui_act(action, list/params, datum/tgui/ui, datum/tgui_state/state)
if(..())
return
if(usr.loc == src)
to_chat(usr, "<span class='warning'>You cannot reach the controls from inside.</span>")
return
var/dat = "<head><title>Waste Disposal Unit</title></head><body><TT><B>Waste Disposal Unit</B><HR>"
if(mode==-1 && action != "eject") // If the mode is -1, only allow ejection
to_chat(usr, "<span class='warning'>The disposal units power is disabled.</span>")
return
if(stat & BROKEN)
return
add_fingerprint(usr)
if(!ai) // AI can't pull flush handle
if(flush)
dat += "Disposal handle: <A href='?src=\ref[src];handle=0'>Disengage</A> <B>Engaged</B>"
else
dat += "Disposal handle: <B>Disengaged</B> <A href='?src=\ref[src];handle=1'>Engage</A>"
if(usr.stat || usr.restrained() || flushing)
return
if(isturf(loc))
if(action == "pumpOn")
mode = 1
update()
if(action == "pumpOff")
mode = 0
update()
dat += "<BR><HR><A href='?src=\ref[src];eject=1'>Eject contents</A><HR>"
if(!issilicon(usr))
if(action == "engageHandle")
flush = 1
update()
if(action == "disengageHandle")
flush = 0
update()
if(mode <= 0)
dat += "Pump: <B>Off</B> <A href='?src=\ref[src];pump=1'>On</A><BR>"
else if(mode == 1)
dat += "Pump: <A href='?src=\ref[src];pump=0'>Off</A> <B>On</B> (pressurizing)<BR>"
else
dat += "Pump: <A href='?src=\ref[src];pump=0'>Off</A> <B>On</B> (idle)<BR>"
if(action == "eject")
eject()
return TRUE
var/per = 100* air_contents.return_pressure() / (SEND_PRESSURE)
// src.add_fingerprint(user)
// if(stat & BROKEN)
// user.unset_machine()
// return
dat += "Pressure: [round(per, 1)]%<BR></body>"
// var/dat = "<head><title>Waste Disposal Unit</title></head><body><TT><B>Waste Disposal Unit</B><HR>"
// if(!ai) // AI can't pull flush handle
// if(flush)
// dat += "Disposal handle: <A href='?src=\ref[src];handle=0'>Disengage</A> <B>Engaged</B>"
// else
// dat += "Disposal handle: <B>Disengaged</B> <A href='?src=\ref[src];handle=1'>Engage</A>"
// dat += "<BR><HR><A href='?src=\ref[src];eject=1'>Eject contents</A><HR>"
// if(mode <= 0)
// dat += "Pump: <B>Off</B> <A href='?src=\ref[src];pump=1'>On</A><BR>"
// else if(mode == 1)
// dat += "Pump: <A href='?src=\ref[src];pump=0'>Off</A> <B>On</B> (pressurizing)<BR>"
// else
// dat += "Pump: <A href='?src=\ref[src];pump=0'>Off</A> <B>On</B> (idle)<BR>"
// var/per = 100* air_contents.return_pressure() / (SEND_PRESSURE)
// dat += "Pressure: [round(per, 1)]%<BR></body>"
user.set_machine(src)
user << browse(dat, "window=disposal;size=360x170")
onclose(user, "disposal")
// user.set_machine(src)
// user << browse(dat, "window=disposal;size=360x170")
// onclose(user, "disposal")
// handle machine interaction
/obj/machinery/disposal/Topic(href, href_list)
if(usr.loc == src)
to_chat(usr, "<font color='red'>You cannot reach the controls from inside.</font>")
return
// /obj/machinery/disposal/Topic(href, href_list)
// if(usr.loc == src)
// to_chat(usr, "<font color='red'>You cannot reach the controls from inside.</font>")
// return
if(mode==-1 && !href_list["eject"]) // only allow ejecting if mode is -1
to_chat(usr, "<font color='red'>The disposal units power is disabled.</font>")
return
if(..())
return
// if(mode==-1 && !href_list["eject"]) // only allow ejecting if mode is -1
// to_chat(usr, "<font color='red'>The disposal units power is disabled.</font>")
// return
// if(..())
// return
if(stat & BROKEN)
return
if(usr.stat || usr.restrained() || src.flushing)
return
// if(stat & BROKEN)
// return
// if(usr.stat || usr.restrained() || src.flushing)
// return
if(istype(src.loc, /turf))
usr.set_machine(src)
// if(istype(src.loc, /turf))
// usr.set_machine(src)
if(href_list["close"])
usr.unset_machine()
usr << browse(null, "window=disposal")
return
// if(href_list["close"])
// usr.unset_machine()
// usr << browse(null, "window=disposal")
// return
if(href_list["pump"])
if(text2num(href_list["pump"]))
mode = 1
else
mode = 0
update()
// if(href_list["pump"])
// if(text2num(href_list["pump"]))
// mode = 1
// else
// mode = 0
// update()
if(!isAI(usr))
if(href_list["handle"])
flush = text2num(href_list["handle"])
update()
// if(!isAI(usr))
// if(href_list["handle"])
// flush = text2num(href_list["handle"])
// update()
if(href_list["eject"])
eject()
else
usr << browse(null, "window=disposal")
usr.unset_machine()
return
return
// if(href_list["eject"])
// eject()
// else
// usr << browse(null, "window=disposal")
// usr.unset_machine()
// return
// return
// eject the contents of the disposal unit
/obj/machinery/disposal/proc/eject()
+155
View File
@@ -0,0 +1,155 @@
/**
* tgui external
*
* Contains all external tgui declarations.
*/
/**
* public
*
* Used to open and update UIs.
* If this proc is not implemented properly, the UI will not update correctly.
*
* required user mob The mob who opened/is using the UI.
* optional ui_key string The ui_key of the UI.
* optional ui datum/tgui The UI to be updated, if it exists.
* optional force_open bool If the UI should be re-opened instead of updated.
* optional master_ui datum/tgui The parent UI.
* optional state datum/ui_state The state used to determine status.
*/
/datum/proc/tgui_interact(mob/user, ui_key = "main", datum/tgui/ui = null, force_open = FALSE, datum/tgui/master_ui = null, datum/tgui_state/state = GLOB.tgui_default_state)
return FALSE // Not implemented.
/**
* public
*
* Data to be sent to the UI.
* This must be implemented for a UI to work.
*
* required user mob The mob interacting with the UI.
*
* return list Data to be sent to the UI.
*/
/datum/proc/tgui_data(mob/user)
return list() // Not implemented.
/**
* public
*
* Static Data to be sent to the UI.
* Static data differs from normal data in that it's large data that should be sent infrequently
* This is implemented optionally for heavy uis that would be sending a lot of redundant data
* frequently.
* Gets squished into one object on the frontend side, but the static part is cached.
*
* required user mob The mob interacting with the UI.
*
* return list Statuic Data to be sent to the UI.
*/
/datum/proc/tgui_static_data(mob/user)
return list()
/**
* public
*
* Forces an update on static data. Should be done manually whenever something happens to change static data.
*
* required user the mob currently interacting with the ui
* optional ui ui to be updated
* optional ui_key ui key of ui to be updated
*/
/datum/proc/update_tgui_static_data(mob/user, datum/tgui/ui, ui_key = "main")
ui = SStgui.try_update_ui(user, src, ui_key, ui)
// If there was no ui to update, there's no static data to update either.
if(!ui)
return
ui.push_data(null, tgui_static_data(), TRUE)
/**
* public
*
* Called on a UI when the UI receieves a href.
* Think of this as Topic().
*
* required action string The action/button that has been invoked by the user.
* required params list A list of parameters attached to the button.
*
* return bool If the UI should be updated or not.
*/
/datum/proc/tgui_act(action, list/params, datum/tgui/ui, datum/tgui_state/state)
// If UI is not interactive or usr calling Topic is not the UI user, bail.
if(!ui || ui.status != STATUS_INTERACTIVE)
return TRUE
/**
* public
*
* Called on an object when a tgui object is being created, allowing you to
* customise the html
* For example: inserting a custom stylesheet that you need in the head
*
* For this purpose, some tags are available in the html, to be parsed out
^ with replacetext
* (customheadhtml) - Additions to the head tag
*
* required html the html base text
*/
/datum/proc/tgui_base_html(html)
return html
/**
* private
*
* The UI's host object (usually src_object).
* This allows modules/datums to have the UI attached to them,
* and be a part of another object.
*/
/datum/proc/tgui_host(mob/user)
return src // Default src.
/**
* global
*
* Associative list of JSON-encoded shared states that were set by
* tgui clients.
*/
/datum/var/list/tgui_shared_states
/**
* global
*
* Used to track UIs for a mob.
*/
/mob/var/list/open_tguis = list()
/**
* public
*
* Called on a UI's object when the UI is closed, not to be confused with
* client/verb/uiclose(), which closes the ui window
*/
/datum/proc/tgui_close(mob/user)
/**
* verb
*
* Called by UIs when they are closed.
* Must be a verb so winset() can call it.
*
* required uiref ref The UI that was closed.
*/
/client/verb/tguiclose(ref as text)
// Name the verb, and hide it from the user panel.
set name = "uiclose"
set hidden = TRUE
// Get the UI based on the ref.
var/datum/tgui/ui = locate(ref)
// If we found the UI, close it.
if(istype(ui))
ui.close()
// Unset machine just to be sure.
if(src && src.mob)
src.mob.unset_machine()
+21
View File
@@ -0,0 +1,21 @@
/*
TGUI MODULES
This allows for datum-based TGUIs that can be hooked into objects.
This is useful for things such as the power monitor, which needs to exist on a physical console in the world, but also as a virtual device the AI can use
Code is pretty much ripped verbatim from nano modules, but with un-needed stuff removed
*/
/datum/tgui_module
var/name
var/datum/host
/datum/tgui_module/New(var/host)
src.host = host
/datum/tgui_module/tgui_host()
return host ? host : src
/datum/tgui_module/tgui_close(mob/user)
if(host)
host.tgui_close(user)
+54
View File
@@ -0,0 +1,54 @@
/datum/tgui_module/crew_monitor
name = "Crew monitor"
/datum/tgui_module/crew_monitor/tgui_act(action, params)
if(..())
return TRUE
var/turf/T = get_turf(tgui_host())
if(!T || !(T.z in using_map.player_levels))
to_chat(usr, "<span class='warning'><b>Unable to establish a connection</b>: You're too far away from the station!</span>")
return FALSE
switch(action)
if("track")
if(isAI(usr))
var/mob/living/silicon/ai/AI = usr
var/mob/living/carbon/human/H = locate(params["track"]) in mob_list
if(hassensorlevel(H, SUIT_SENSOR_TRACKING))
AI.ai_actual_track(H)
return TRUE
/datum/tgui_module/crew_monitor/tgui_interact(mob/user, ui_key = "main", datum/tgui/ui = null, force_open = 0, datum/tgui/master_ui = null, datum/tgui_state/state = GLOB.tgui_default_state)
var/z = get_z(tgui_host())
var/list/map_levels = using_map.get_map_levels(z, TRUE)
if(!map_levels.len)
to_chat(user, "<span class='warning'>The crew monitor doesn't seem like it'll work here.</span>")
if(ui)
ui.close()
return null
ui = SStgui.try_update_ui(user, src, ui_key, ui, force_open)
if(!ui)
// The 557 may seem random, but its the perfectsize for margins on the nanomap
ui = new(user, src, ui_key, "CrewMonitor", name, 1400, 557, master_ui, state)
ui.autoupdate = TRUE
ui.open()
/datum/tgui_module/crew_monitor/tgui_data(mob/user, ui_key = "main", datum/topic_state/state = GLOB.tgui_default_state)
var/data[0]
data["isAI"] = isAI(user)
var/z = get_z(tgui_host())
var/list/map_levels = uniquelist(using_map.get_map_levels(z, TRUE))
data["map_levels"] = map_levels
data["crewmembers"] = list()
for(var/zlevel in map_levels)
data["crewmembers"] += crew_repository.health_data(zlevel)
return data
+117
View File
@@ -0,0 +1,117 @@
/**
* tgui states
*
* Base state and helpers for states. Just does some sanity checks, implement a state for in-depth checks.
*/
/**
* public
*
* Checks the UI state for a mob.
*
* required user mob The mob who opened/is using the UI.
* required state datum/ui_state The state to check.
*
* return UI_state The state of the UI.
*/
/datum/proc/tgui_status(mob/user, datum/tgui_state/state)
var/src_object = tgui_host(user)
. = STATUS_CLOSE
if(!state)
return
if(isobserver(user))
// // If they turn on ghost AI control, admins can always interact.
// if(user.client.advanced_admin_interaction)
// . = max(., STATUS_INTERACTIVE)
// Regular ghosts can always at least view if in range.
var/clientviewlist = getviewsize(user.client.view)
if(get_dist(src_object, user) < max(clientviewlist[1],clientviewlist[2]))
. = max(., STATUS_UPDATE)
// Check if the state allows interaction
var/result = state.can_use_topic(src_object, user)
. = max(., result)
/**
* private
*
* Checks if a user can use src_object's UI, and returns the state.
* Can call a mob proc, which allows overrides for each mob.
*
* required src_object datum The object/datum which owns the UI.
* required user mob The mob who opened/is using the UI.
*
* return UI_state The state of the UI.
*/
/datum/tgui_state/proc/can_use_topic(src_object, mob/user)
return STATUS_CLOSE // Don't allow interaction by default.
/**
* public
*
* Standard interaction/sanity checks. Different mob types may have overrides.
*
* return UI_state The state of the UI.
*/
/mob/proc/shared_tgui_interaction(src_object)
if(!client) // Close UIs if mindless.
return STATUS_CLOSE
else if(stat) // Disable UIs if unconcious.
return STATUS_DISABLED
else if(incapacitated()) // Update UIs if incapicitated but concious.
return STATUS_UPDATE
return STATUS_INTERACTIVE
/mob/living/silicon/ai/shared_tgui_interaction(src_object)
if(lacks_power()) // Disable UIs if the AI is unpowered.
return STATUS_DISABLED
return ..()
/mob/living/silicon/robot/shared_tgui_interaction(src_object)
if(!cell || cell.charge <= 0 || lockcharge) // Disable UIs if the Borg is unpowered or locked.
return STATUS_DISABLED
return ..()
/**
* public
*
* Check the distance for a living mob.
* Really only used for checks outside the context of a mob.
* Otherwise, use shared_living_ui_distance().
*
* required src_object The object which owns the UI.
* required user mob The mob who opened/is using the UI.
*
* return UI_state The state of the UI.
*/
/atom/proc/contents_tgui_distance(src_object, mob/living/user)
return user.shared_living_tgui_distance(src_object) // Just call this mob's check.
/**
* public
*
* Distance versus interaction check.
*
* required src_object atom/movable The object which owns the UI.
*
* return UI_state The state of the UI.
*/
/mob/living/proc/shared_living_tgui_distance(atom/movable/src_object, viewcheck = TRUE)
if(viewcheck && !(src_object in view(src))) // If the object is obscured, close it.
return STATUS_CLOSE
var/dist = get_dist(src_object, src)
if(dist <= 1) // Open and interact if 1-0 tiles away.
return STATUS_INTERACTIVE
else if(dist <= 2) // View only if 2-3 tiles away.
return STATUS_UPDATE
else if(dist <= 5) // Disable if 5 tiles away.
return STATUS_DISABLED
return STATUS_CLOSE // Otherwise, we got nothing.
/mob/living/carbon/human/shared_living_tgui_distance(atom/movable/src_object)
if((TK in mutations) && (get_dist(src, src_object) <= 2))
return STATUS_INTERACTIVE
return ..()
+12
View File
@@ -0,0 +1,12 @@
/**
* tgui state: admin_state
*
* Checks that the user is an admin, end-of-story.
**/
GLOBAL_DATUM_INIT(tgui_admin_state, /datum/tgui_state/admin_state, new)
/datum/tgui_state/admin_state/can_use_topic(src_object, mob/user)
if(check_rights_for(user.client, R_ADMIN))
return STATUS_INTERACTIVE
return STATUS_CLOSE
+11
View File
@@ -0,0 +1,11 @@
/**
* tgui state: always_state
*
* Always grants the user UI_INTERACTIVE. Period.
**/
GLOBAL_DATUM_INIT(tgui_always_state, /datum/tgui_state/always_state, new)
/datum/tgui_state/always_state/can_use_topic(src_object, mob/user)
return STATUS_INTERACTIVE
+12
View File
@@ -0,0 +1,12 @@
/**
* tgui state: conscious_state
*
* Only checks if the user is conscious.
**/
GLOBAL_DATUM_INIT(tgui_conscious_state, /datum/tgui_state/conscious_state, new)
/datum/tgui_state/conscious_state/can_use_topic(src_object, mob/user)
if(user.stat == CONSCIOUS)
return STATUS_INTERACTIVE
return STATUS_CLOSE
+12
View File
@@ -0,0 +1,12 @@
/**
* tgui state: contained_state
*
* Checks that the user is inside the src_object.
**/
GLOBAL_DATUM_INIT(tgui_contained_state, /datum/tgui_state/contained_state, new)
/datum/tgui_state/contained_state/can_use_topic(atom/src_object, mob/user)
if(!src_object.contains(user))
return STATUS_CLOSE
return user.shared_tgui_interaction(src_object)
@@ -0,0 +1,12 @@
/**
* tgui state: deep_inventory_state
*
* Checks that the src_object is in the user's deep (backpack, box, toolbox, etc) inventory.
**/
GLOBAL_DATUM_INIT(tgui_deep_inventory_state, /datum/tgui_state/deep_inventory_state, new)
/datum/tgui_state/deep_inventory_state/can_use_topic(src_object, mob/user)
if(!user.contains(src_object))
return STATUS_CLOSE
return user.shared_tgui_interaction(src_object)
+63
View File
@@ -0,0 +1,63 @@
/**
* tgui state: default_state
*
* Checks a number of things -- mostly physical distance for humans and view for robots.
**/
GLOBAL_DATUM_INIT(tgui_default_state, /datum/tgui_state/default, new)
/datum/tgui_state/default/can_use_topic(src_object, mob/user)
return user.default_can_use_tgui_topic(src_object) // Call the individual mob-overridden procs.
/mob/proc/default_can_use_tgui_topic(src_object)
return STATUS_CLOSE // Don't allow interaction by default.
/mob/living/default_can_use_tgui_topic(src_object)
. = shared_tgui_interaction(src_object)
if(. > STATUS_CLOSE && loc)
. = min(., loc.contents_tgui_distance(src_object, src)) // Check the distance...
if(. == STATUS_INTERACTIVE) // Non-human living mobs can only look, not touch.
return STATUS_UPDATE
/mob/living/carbon/human/default_can_use_tgui_topic(src_object)
. = shared_tgui_interaction(src_object)
if(. > STATUS_CLOSE)
. = min(., shared_living_tgui_distance(src_object)) // Check the distance...
/mob/living/silicon/robot/default_can_use_tgui_topic(src_object)
. = shared_tgui_interaction(src_object)
if(. <= STATUS_DISABLED)
return
// Robots can interact with anything they can see.
var/list/clientviewlist = getviewsize(client.view)
if((src_object in view(src)) && (get_dist(src, src_object) <= min(clientviewlist[1],clientviewlist[2])))
return STATUS_INTERACTIVE
return STATUS_DISABLED // Otherwise they can keep the UI open.
/mob/living/silicon/ai/default_can_use_tgui_topic(src_object)
. = shared_tgui_interaction(src_object)
if(. < STATUS_INTERACTIVE)
return
// The AI can interact with anything it can see nearby, or with cameras while wireless control is enabled.
if(!control_disabled && can_see(src_object))
return STATUS_INTERACTIVE
return STATUS_CLOSE
/mob/living/simple_animal/default_can_use_tgui_topic(src_object)
. = shared_tgui_interaction(src_object)
if(. > STATUS_CLOSE)
. = min(., shared_living_tgui_distance(src_object)) //simple animals can only use things they're near.
/mob/living/silicon/pai/default_can_use_tgui_topic(src_object)
// pAIs can only use themselves and the owner's radio.
if((src_object == src || src_object == radio) && !stat)
return STATUS_INTERACTIVE
else
return ..()
/mob/observer/dead/default_can_use_tgui_topic()
if(check_rights(R_ADMIN, 0, src))
return STATUS_INTERACTIVE // Admins are more equal
return STATUS_UPDATE // Ghosts can view updates
+25
View File
@@ -0,0 +1,25 @@
/**
* tgui state: hands_state
*
* Checks that the src_object is in the user's hands.
**/
GLOBAL_DATUM_INIT(tgui_hands_state, /datum/tgui_state/hands_state, new)
/datum/tgui_state/hands_state/can_use_topic(src_object, mob/user)
. = user.shared_tgui_interaction(src_object)
if(. > STATUS_CLOSE)
return min(., user.hands_can_use_tgui_topic(src_object))
/mob/proc/hands_can_use_tgui_topic(src_object)
return STATUS_CLOSE
/mob/living/hands_can_use_tgui_topic(src_object)
if(src_object in get_all_held_items())
return STATUS_INTERACTIVE
return STATUS_CLOSE
/mob/living/silicon/robot/hands_can_use_tgui_topic(src_object)
if(activated(src_object))
return STATUS_INTERACTIVE
return STATUS_CLOSE
@@ -0,0 +1,17 @@
/**
* tgui state: human_adjacent_state
*
* In addition to default checks, only allows interaction for a
* human adjacent user.
**/
GLOBAL_DATUM_INIT(tgui_human_adjacent_state, /datum/tgui_state/human_adjacent_state, new)
/datum/tgui_state/human_adjacent_state/can_use_topic(src_object, mob/user)
. = user.default_can_use_tgui_topic(src_object)
var/dist = get_dist(src_object, user)
if((dist > 1) || (!ishuman(user)))
// Can't be used unless adjacent and human, even with TK
. = min(., STATUS_UPDATE)
+12
View File
@@ -0,0 +1,12 @@
/**
* tgui state: inventory_state
*
* Checks that the src_object is in the user's top-level (hand, ear, pocket, belt, etc) inventory.
**/
GLOBAL_DATUM_INIT(tgui_inventory_state, /datum/tgui_state/inventory_state, new)
/datum/tgui_state/inventory_state/can_use_topic(src_object, mob/user)
if(!(src_object in user))
return STATUS_CLOSE
return user.shared_tgui_interaction(src_object)
@@ -0,0 +1,29 @@
/**
* tgui state: not_incapacitated_state
*
* Checks that the user isn't incapacitated
**/
GLOBAL_DATUM_INIT(tgui_not_incapacitated_state, /datum/tgui_state/not_incapacitated_state, new)
/**
* tgui state: not_incapacitated_turf_state
*
* Checks that the user isn't incapacitated and that their loc is a turf
**/
GLOBAL_DATUM_INIT(tgui_not_incapacitated_turf_state, /datum/tgui_state/not_incapacitated_state, new(no_turfs = TRUE))
/datum/tgui_state/not_incapacitated_state
var/turf_check = FALSE
/datum/tgui_state/not_incapacitated_state/New(loc, no_turfs = FALSE)
..()
turf_check = no_turfs
/datum/tgui_state/not_incapacitated_state/can_use_topic(src_object, mob/user)
if(user.stat)
return STATUS_CLOSE
if(user.incapacitated() || (turf_check && !isturf(user.loc)))
return STATUS_DISABLED
return STATUS_INTERACTIVE
+26
View File
@@ -0,0 +1,26 @@
/**
* tgui state: notcontained_state
*
* Checks that the user is not inside src_object, and then makes the default checks.
**/
GLOBAL_DATUM_INIT(tgui_notcontained_state, /datum/tgui_state/notcontained_state, new)
/datum/tgui_state/notcontained_state/can_use_topic(atom/src_object, mob/user)
. = user.shared_tgui_interaction(src_object)
if(. > STATUS_CLOSE)
return min(., user.notcontained_can_use_tgui_topic(src_object))
/mob/proc/notcontained_can_use_tgui_topic(src_object)
return STATUS_CLOSE
/mob/living/notcontained_can_use_tgui_topic(atom/src_object)
if(src_object.contains(src))
return STATUS_CLOSE // Close if we're inside it.
return default_can_use_tgui_topic(src_object)
/mob/living/silicon/notcontained_can_use_tgui_topic(src_object)
return default_can_use_tgui_topic(src_object) // Silicons use default bevhavior.
/mob/living/simple_animal/drone/notcontained_can_use_tgui_topic(src_object)
return default_can_use_tgui_topic(src_object) // Drones use default bevhavior.
+15
View File
@@ -0,0 +1,15 @@
/**
* tgui state: observer_state
*
* Checks that the user is an observer/ghost.
**/
GLOBAL_DATUM_INIT(tgui_observer_state, /datum/tgui_state/observer_state, new)
/datum/tgui_state/observer_state/can_use_topic(src_object, mob/user)
if(isobserver(user))
return STATUS_INTERACTIVE
if(check_rights(R_ADMIN, 0, src))
return STATUS_INTERACTIVE
return STATUS_CLOSE
+24
View File
@@ -0,0 +1,24 @@
/**
* tgui state: physical_state
*
* Short-circuits the default state to only check physical distance.
**/
GLOBAL_DATUM_INIT(tgui_physical_state, /datum/tgui_state/physical, new)
/datum/tgui_state/physical/can_use_topic(src_object, mob/user)
. = user.shared_tgui_interaction(src_object)
if(. > STATUS_CLOSE)
return min(., user.physical_can_use_tgui_topic(src_object))
/mob/proc/physical_can_use_tgui_topic(src_object)
return STATUS_CLOSE
/mob/living/physical_can_use_tgui_topic(src_object)
return shared_living_tgui_distance(src_object)
/mob/living/silicon/physical_can_use_tgui_topic(src_object)
return max(STATUS_UPDATE, shared_living_tgui_distance(src_object)) // Silicons can always see.
/mob/living/silicon/ai/physical_can_use_tgui_topic(src_object)
return STATUS_UPDATE // AIs are not physical.
+12
View File
@@ -0,0 +1,12 @@
/**
* tgui state: self_state
*
* Only checks that the user and src_object are the same.
**/
GLOBAL_DATUM_INIT(tgui_self_state, /datum/tgui_state/self_state, new)
/datum/tgui_state/self_state/can_use_topic(src_object, mob/user)
if(src_object != user)
return STATUS_CLOSE
return user.shared_tgui_interaction(src_object)
+14
View File
@@ -0,0 +1,14 @@
/**
* tgui state: z_state
*
* Only checks that the Z-level of the user and src_object are the same.
**/
GLOBAL_DATUM_INIT(tgui_z_state, /datum/tgui_state/z_state, new)
/datum/tgui_state/z_state/can_use_topic(src_object, mob/user)
var/turf/turf_obj = get_turf(src_object)
var/turf/turf_usr = get_turf(user)
if(turf_obj && turf_usr && turf_obj.z == turf_usr.z)
return STATUS_INTERACTIVE
return STATUS_CLOSE
+373
View File
@@ -0,0 +1,373 @@
/**
* tgui
*
* /tg/station user interface library
*/
/**
* tgui datum (represents a UI).
*/
/datum/tgui
/// The mob who opened/is using the UI.
var/mob/user
/// The object which owns the UI.
var/datum/src_object
/// The title of te UI.
var/title
/// The ui_key of the UI. This allows multiple UIs for one src_object.
var/ui_key
/// The window_id for browse() and onclose().
var/window_id
/// The window width.
var/width = 0
/// The window height
var/height = 0
/// The interface (template) to be used for this UI.
var/interface
/// Update the UI every MC tick.
var/autoupdate = TRUE
/// If the UI has been initialized yet.
var/initialized = FALSE
/// The data (and datastructure) used to initialize the UI.
var/list/initial_data
/// The static data used to initialize the UI.
var/list/initial_static_data
/// Holder for the json string, that is sent during the initial update
var/_initial_update
/// The status/visibility of the UI.
var/status = STATUS_INTERACTIVE
/// Topic state used to determine status/interactability.
var/datum/tgui_state/state = null
/// The parent UI.
var/datum/tgui/master_ui
/// Children of this UI.
var/list/datum/tgui/children = list()
// The map z-level to display.
var/map_z_level = 1
/**
* public
*
* Create a new UI.
*
* required user mob The mob who opened/is using the UI.
* required src_object datum The object or datum which owns the UI.
* required ui_key string The ui_key of the UI.
* required interface string The interface used to render the UI.
* optional title string The title of the UI.
* optional width int The window width.
* optional height int The window height.
* optional master_ui datum/tgui The parent UI.
* optional state datum/ui_state The state used to determine status.
*
* return datum/tgui The requested UI.
*/
/datum/tgui/New(mob/user, datum/src_object, ui_key, interface, title, width = 0, height = 0, datum/tgui/master_ui = null, datum/tgui_state/state = GLOB.tgui_default_state)
src.user = user
src.src_object = src_object
src.ui_key = ui_key
src.window_id = "\ref[src_object]-[ui_key]"
src.interface = interface
if(title)
src.title = sanitize(title)
if(width)
src.width = width
if(height)
src.height = height
src.master_ui = master_ui
if(master_ui)
master_ui.children += src
src.state = state
var/datum/asset/tgui_assets = get_asset_datum(/datum/asset/simple/tgui)
var/datum/asset/fa = get_asset_datum(/datum/asset/simple/fontawesome)
tgui_assets.send(user)
fa.send(user)
/**
* public
*
* Open this UI (and initialize it with data).
*/
/datum/tgui/proc/open()
if(!user.client)
return // Bail if there is no client.
update_status(push = FALSE) // Update the window status.
if(status < STATUS_UPDATE)
return // Bail if we're not supposed to open.
// Build window options
var/window_options = "can_minimize=0;auto_format=0;"
// If we have a width and height, use them.
if(width && height)
window_options += "size=[width]x[height];"
// Remove titlebar and resize handles for a fancy window
// if(user.client.prefs.nanoui_fancy)
// window_options += "titlebar=0;can_resize=0;"
// else
window_options += "titlebar=1;can_resize=1;"
// Generate page html
var/html
html = SStgui.basehtml
// Allow the src object to override the html if needed
html = src_object.tgui_base_html(html)
// Replace template tokens with important UI data
html = replacetextEx(html, "\[tgui:ref]", "\ref[src]")
// Open the window.
user << browse(html, "window=[window_id];[window_options]")
// Instruct the client to signal UI when the window is closed.
// NOTE: Intentional \ref usage; tgui datums can't/shouldn't
// be tagged, so this is an effective unwrap
winset(user, window_id, "on-close=\"uiclose \ref[src]\"")
// Pre-fetch initial state while browser is still loading in
// another thread
if(!initial_data)
initial_data = src_object.tgui_data(user)
if(!initial_static_data)
initial_static_data = src_object.tgui_static_data(user)
_initial_update = url_encode(get_json(initial_data, initial_static_data))
SStgui.on_open(src)
/**
* public
*
* Reinitialize the UI.
* (Possibly with a new interface and/or data).
*
* optional template string The name of the new interface.
* optional data list The new initial data.
*/
/datum/tgui/proc/reinitialize(interface, list/data, list/static_data)
if(interface)
src.interface = interface
if(data)
initial_data = data
if(static_data)
initial_static_data = static_data
open()
/**
* public
*
* Close the UI, and all its children.
*/
/datum/tgui/proc/close()
user << browse(null, "window=[window_id]") // Close the window.
src_object.tgui_close(user)
SStgui.on_close(src)
for(var/datum/tgui/child in children) // Loop through and close all children.
child.close()
children.Cut()
state = null
master_ui = null
qdel(src)
/**
* public
*
* Enable/disable auto-updating of the UI.
*
* required state bool Enable/disable auto-updating.
*/
/datum/tgui/proc/set_autoupdate(state = TRUE)
autoupdate = state
/**
* private
*
* Package the data to send to the UI, as JSON.
* This includes the UI data and config_data.
*
* return string The packaged JSON.
*/
/datum/tgui/proc/get_json(list/data, list/static_data)
var/list/json_data = list()
json_data["config"] = list(
"title" = title,
"status" = status,
"interface" = interface,
// "fancy" = user.client.prefs.nanoui_fancy,
"observer" = isobserver(user),
"window" = window_id,
"map" = (using_map && using_map.path) ? using_map.path : "Unknown",
"mapZLevel" = map_z_level,
"ref" = "\ref[src]"
)
if(!isnull(data))
json_data["data"] = data
if(!isnull(static_data))
json_data["static_data"] = static_data
// Send shared states
if(src_object.tgui_shared_states)
json_data["shared"] = src_object.tgui_shared_states
// Generate the JSON.
var/json = json_encode(json_data)
// Strip #255/improper.
json = replacetext(json, "\proper", "")
json = replacetext(json, "\improper", "")
return json
/**
* private
*
* Handle clicks from the UI.
* Call the src_object's ui_act() if status is UI_INTERACTIVE.
* If the src_object's ui_act() returns 1, update all UIs attacked to it.
*/
/datum/tgui/Topic(href, href_list)
if(user != usr)
return // Something is not right here.
var/action = href_list["action"]
var/params = href_list; params -= "action"
switch(action)
if("tgui:initialize")
user << output(_initial_update, "[window_id].browser:update")
initialized = TRUE
if("tgui:setSharedState")
// Update the window state.
update_status(push = FALSE)
// Bail if UI is not interactive or usr calling Topic
// is not the UI user.
if(status != STATUS_INTERACTIVE)
return
var/key = params["key"]
var/value = params["value"]
if(!src_object.tgui_shared_states)
src_object.tgui_shared_states = list()
src_object.tgui_shared_states[key] = value
SStgui.update_uis(src_object)
// if("tgui:setFancy")
// var/value = text2num(params["value"])
// user.client.prefs.nanoui_fancy = value
if("tgui:log")
// Force window to show frills on fatal errors
if(params["fatal"])
winset(user, window_id, "titlebar=1;can-resize=1;size=600x600")
log_message(params["log"])
if("tgui:link")
user << link(params["url"])
if("tgui:setZLevel")
set_map_z_level(params["mapZLevel"])
// Update the window state.
update_status(push = FALSE)
else
// Update the window state.
update_status(push = FALSE)
// Call tgui_act() on the src_object.
if(src_object.tgui_act(action, params, src, state))
// Update if the object requested it.
SStgui.update_uis(src_object)
/**
* private
*
* Update the UI.
* Only updates the data if update is true, otherwise only updates the status.
*
* optional force bool If the UI should be forced to update.
*/
/datum/tgui/process(force = FALSE)
var/datum/host = src_object.tgui_host(user)
if(!src_object || !host || !user) // If the object or user died (or something else), abort.
close()
return
if(status && (force || autoupdate))
update() // Update the UI if the status and update settings allow it.
else
update_status(push = TRUE) // Otherwise only update status.
/**
* private
*
* Push data to an already open UI.
*
* required data list The data to send.
* optional force bool If the update should be sent regardless of state.
*/
/datum/tgui/proc/push_data(data, static_data, force = FALSE)
// Update the window state.
update_status(push = FALSE)
// Cannot update UI if it is not set up yet.
if(!initialized)
return
// Cannot update UI, we have no visibility.
if(status <= STATUS_DISABLED && !force)
return
// Send the new JSON to the update() Javascript function.
user << output(
url_encode(get_json(data, static_data)),
"[window_id].browser:update")
/**
* private
*
* Updates the UI by interacting with the src_object again, which will hopefully
* call try_ui_update on it.
*
* optional force_open bool If force_open should be passed to ui_interact.
*/
/datum/tgui/proc/update(force_open = FALSE)
src_object.tgui_interact(user, ui_key, src, force_open, master_ui, state)
/**
* private
*
* Update the status/visibility of the UI for its user.
*
* optional push bool Push an update to the UI (an update is always sent for UI_DISABLED).
*/
/datum/tgui/proc/update_status(push = FALSE)
var/status = src_object.tgui_status(user, state)
if(master_ui)
status = min(status, master_ui.status)
set_status(status, push)
if(status == STATUS_CLOSE)
close()
/**
* private
*
* Set the status/visibility of the UI.
*
* required status int The status to set (UI_CLOSE/UI_DISABLED/UI_UPDATE/UI_INTERACTIVE).
* optional push bool Push an update to the UI (an update is always sent for UI_DISABLED).
*/
/datum/tgui/proc/set_status(status, push = FALSE)
// Only update if status has changed.
if(src.status != status)
if(src.status == STATUS_DISABLED)
src.status = status
if(push)
update()
else
src.status = status
// Update if the UI just because disabled, or a push is requested.
if(status == STATUS_DISABLED || push)
push_data(null, force = TRUE)
/datum/tgui/proc/log_message(message)
log_tgui("[user] ([user.ckey]) using \"[title]\":\n[message]")
/datum/tgui/proc/set_map_z_level(nz)
map_z_level = nz
+6
View File
@@ -0,0 +1,6 @@
Due to the fact browse_rsc can't create subdirectories, every time you update font-awesome you'll need to change relative webfont references in all.min.css
eg ../webfonts/fa-regular-400.ttf => fa-regular-400.ttf (or whatever you call it in asset datum)
Second change is ripping out file types other than woff and eot(ie8) from the css
Finally, removing brand related css.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 261 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 561 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 236 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

+21
View File
@@ -229,6 +229,7 @@
#include "code\controllers\subsystems\sqlite.dm"
#include "code\controllers\subsystems\sun.dm"
#include "code\controllers\subsystems\supply.dm"
#include "code\controllers\subsystems\tgui.dm"
#include "code\controllers\subsystems\ticker.dm"
#include "code\controllers\subsystems\time_track.dm"
#include "code\controllers\subsystems\timer.dm"
@@ -2830,6 +2831,26 @@
#include "code\modules\tables\tables.dm"
#include "code\modules\tables\update_triggers.dm"
#include "code\modules\tension\tension.dm"
#include "code\modules\tgui\external.dm"
#include "code\modules\tgui\states.dm"
#include "code\modules\tgui\tgui.dm"
#include "code\modules\tgui\modules\_base.dm"
#include "code\modules\tgui\modules\crew_monitor.dm"
#include "code\modules\tgui\states\admin.dm"
#include "code\modules\tgui\states\always.dm"
#include "code\modules\tgui\states\conscious.dm"
#include "code\modules\tgui\states\contained.dm"
#include "code\modules\tgui\states\deep_inventory.dm"
#include "code\modules\tgui\states\default.dm"
#include "code\modules\tgui\states\hands.dm"
#include "code\modules\tgui\states\human_adjacent.dm"
#include "code\modules\tgui\states\inventory.dm"
#include "code\modules\tgui\states\not_incapacitated.dm"
#include "code\modules\tgui\states\notcontained.dm"
#include "code\modules\tgui\states\observer.dm"
#include "code\modules\tgui\states\physical.dm"
#include "code\modules\tgui\states\self.dm"
#include "code\modules\tgui\states\zlevel.dm"
#include "code\modules\tooltip\tooltip.dm"
#include "code\modules\turbolift\_turbolift.dm"
#include "code\modules\turbolift\turbolift.dm"
+13
View File
@@ -0,0 +1,13 @@
# http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
max_line_length = 80
+6
View File
@@ -0,0 +1,6 @@
/**/node_modules
/**/*.bundle.*
/**/*.chunk.*
/**/*.hot-update.*
/packages/inferno/**
/packages/tgui/public/shim-*.js
+14
View File
@@ -0,0 +1,14 @@
rules:
## Enforce a maximum cyclomatic complexity allowed in a program
complexity: [error, { max: 25 }]
## Enforce consistent brace style for blocks
brace-style: [error, stroustrup, { allowSingleLine: false }]
## Enforce the consistent use of either backticks, double, or single quotes
quotes: [error, single, {
avoidEscape: true,
allowTemplateLiterals: true,
}]
react/jsx-closing-bracket-location: [error, {
selfClosing: after-props,
nonEmpty: after-props,
}]
+755
View File
@@ -0,0 +1,755 @@
parser: babel-eslint
parserOptions:
ecmaVersion: 2019
sourceType: module
ecmaFeatures:
jsx: true
env:
es6: true
browser: true
node: true
plugins:
- react
settings:
react:
version: '16.10'
rules:
## Possible Errors
## ----------------------------------------
## Enforce “for” loop update clause moving the counter in the right
## direction.
# for-direction: error
## Enforce return statements in getters
# getter-return: error
## Disallow using an async function as a Promise executor
no-async-promise-executor: error
## Disallow await inside of loops
# no-await-in-loop: error
## Disallow comparing against -0
# no-compare-neg-zero: error
## Disallow assignment operators in conditional expressions
no-cond-assign: error
## Disallow the use of console
# no-console: error
## Disallow constant expressions in conditions
# no-constant-condition: error
## Disallow control characters in regular expressions
# no-control-regex: error
## Disallow the use of debugger
no-debugger: error
## Disallow duplicate arguments in function definitions
no-dupe-args: error
## Disallow duplicate keys in object literals
no-dupe-keys: error
## Disallow duplicate case labels
no-duplicate-case: error
## Disallow empty block statements
# no-empty: error
## Disallow empty character classes in regular expressions
no-empty-character-class: error
## Disallow reassigning exceptions in catch clauses
no-ex-assign: error
## Disallow unnecessary boolean casts
no-extra-boolean-cast: error
## Disallow unnecessary parentheses
# no-extra-parens: warn
## Disallow unnecessary semicolons
no-extra-semi: error
## Disallow reassigning function declarations
no-func-assign: error
## Disallow assigning to imported bindings
no-import-assign: error
## Disallow variable or function declarations in nested blocks
no-inner-declarations: error
## Disallow invalid regular expression strings in RegExp constructors
no-invalid-regexp: error
## Disallow irregular whitespace
no-irregular-whitespace: error
## Disallow characters which are made with multiple code points in character
## class syntax
no-misleading-character-class: error
## Disallow calling global object properties as functions
no-obj-calls: error
## Disallow calling some Object.prototype methods directly on objects
no-prototype-builtins: error
## Disallow multiple spaces in regular expressions
no-regex-spaces: error
## Disallow sparse arrays
no-sparse-arrays: error
## Disallow template literal placeholder syntax in regular strings
no-template-curly-in-string: error
## Disallow confusing multiline expressions
no-unexpected-multiline: error
## Disallow unreachable code after return, throw, continue, and break
## statements
# no-unreachable: warn
## Disallow control flow statements in finally blocks
no-unsafe-finally: error
## Disallow negating the left operand of relational operators
no-unsafe-negation: error
## Disallow assignments that can lead to race conditions due to usage of
## await or yield
# require-atomic-updates: error
## Require calls to isNaN() when checking for NaN
use-isnan: error
## Enforce comparing typeof expressions against valid strings
valid-typeof: error
## Best practices
## ----------------------------------------
## Enforce getter and setter pairs in objects and classes
# accessor-pairs: error
## Enforce return statements in callbacks of array methods
# array-callback-return: error
## Enforce the use of variables within the scope they are defined
# block-scoped-var: error
## Enforce that class methods utilize this
# class-methods-use-this: error
## Enforce a maximum cyclomatic complexity allowed in a program
complexity: [error, { max: 50 }]
## Require return statements to either always or never specify values
# consistent-return: error
## Enforce consistent brace style for all control statements
curly: [error, all]
## Require default cases in switch statements
# default-case: error
## Enforce default parameters to be last
# default-param-last: error
## Enforce consistent newlines before and after dots
dot-location: [error, property]
## Enforce dot notation whenever possible
# dot-notation: error
## Require the use of === and !==
eqeqeq: [error, always]
## Require for-in loops to include an if statement
# guard-for-in: error
## Enforce a maximum number of classes per file
# max-classes-per-file: error
## Disallow the use of alert, confirm, and prompt
# no-alert: error
## Disallow the use of arguments.caller or arguments.callee
# no-caller: error
## Disallow lexical declarations in case clauses
no-case-declarations: error
## Disallow division operators explicitly at the beginning of regular
## expressions
# no-div-regex: error
## Disallow else blocks after return statements in if statements
# no-else-return: error
## Disallow empty functions
# no-empty-function: error
## Disallow empty destructuring patterns
no-empty-pattern: error
## Disallow null comparisons without type-checking operators
# no-eq-null: error
## Disallow the use of eval()
# no-eval: error
## Disallow extending native types
# no-extend-native: error
## Disallow unnecessary calls to .bind()
# no-extra-bind: error
## Disallow unnecessary labels
# no-extra-label: error
## Disallow fallthrough of case statements
no-fallthrough: error
## Disallow leading or trailing decimal points in numeric literals
# no-floating-decimal: error
## Disallow assignments to native objects or read-only global variables
no-global-assign: error
## Disallow shorthand type conversions
# no-implicit-coercion: error
## Disallow variable and function declarations in the global scope
# no-implicit-globals: error
## Disallow the use of eval()-like methods
# no-implied-eval: error
## Disallow this keywords outside of classes or class-like objects
# no-invalid-this: error
## Disallow the use of the __iterator__ property
# no-iterator: error
## Disallow labeled statements
# no-labels: error
## Disallow unnecessary nested blocks
# no-lone-blocks: error
## Disallow function declarations that contain unsafe references inside
## loop statements
# no-loop-func: error
## Disallow magic numbers
# no-magic-numbers: error
## Disallow multiple spaces
no-multi-spaces: warn
## Disallow multiline strings
# no-multi-str: error
## Disallow new operators outside of assignments or comparisons
# no-new: error
## Disallow new operators with the Function object
# no-new-func: error
## Disallow new operators with the String, Number, and Boolean objects
# no-new-wrappers: error
## Disallow octal literals
no-octal: error
## Disallow octal escape sequences in string literals
no-octal-escape: error
## Disallow reassigning function parameters
# no-param-reassign: error
## Disallow the use of the __proto__ property
# no-proto: error
## Disallow variable redeclaration
no-redeclare: error
## Disallow certain properties on certain objects
# no-restricted-properties: error
## Disallow assignment operators in return statements
no-return-assign: error
## Disallow unnecessary return await
# no-return-await: error
## Disallow javascript: urls
# no-script-url: error
## Disallow assignments where both sides are exactly the same
no-self-assign: error
## Disallow comparisons where both sides are exactly the same
# no-self-compare: error
## Disallow comma operators
no-sequences: error
## Disallow throwing literals as exceptions
# no-throw-literal: error
## Disallow unmodified loop conditions
# no-unmodified-loop-condition: error
## Disallow unused expressions
# no-unused-expressions: error
## Disallow unused labels
no-unused-labels: warn
## Disallow unnecessary calls to .call() and .apply()
# no-useless-call: error
## Disallow unnecessary catch clauses
# no-useless-catch: error
## Disallow unnecessary concatenation of literals or template literals
# no-useless-concat: error
## Disallow unnecessary escape characters
no-useless-escape: warn
## Disallow redundant return statements
# no-useless-return: error
## Disallow void operators
# no-void: error
## Disallow specified warning terms in comments
# no-warning-comments: error
## Disallow with statements
no-with: error
## Enforce using named capture group in regular expression
# prefer-named-capture-group: error
## Require using Error objects as Promise rejection reasons
# prefer-promise-reject-errors: error
## Disallow use of the RegExp constructor in favor of regular expression
## literals
# prefer-regex-literals: error
## Enforce the consistent use of the radix argument when using parseInt()
radix: error
## Disallow async functions which have no await expression
# require-await: error
## Enforce the use of u flag on RegExp
# require-unicode-regexp: error
## Require var declarations be placed at the top of their containing scope
# vars-on-top: error
## Require parentheses around immediate function invocations
# wrap-iife: error
## Require or disallow “Yoda” conditions
# yoda: error
## Strict mode
## ----------------------------------------
## Require or disallow strict mode directives
strict: error
## Variables
## ----------------------------------------
## Require or disallow initialization in variable declarations
# init-declarations: error
## Disallow deleting variables
no-delete-var: error
## Disallow labels that share a name with a variable
# no-label-var: error
## Disallow specified global variables
# no-restricted-globals: error
## Disallow variable declarations from shadowing variables declared in
## the outer scope
# no-shadow: error
## Disallow identifiers from shadowing restricted names
no-shadow-restricted-names: error
## Disallow the use of undeclared variables unless mentioned
## in /*global*/ comments
no-undef: error
## Disallow initializing variables to undefined
no-undef-init: error
## Disallow the use of undefined as an identifier
# no-undefined: error
## Disallow unused variables
# no-unused-vars: error
## Disallow the use of variables before they are defined
# no-use-before-define: error
## Code style
## ----------------------------------------
## Enforce linebreaks after opening and before closing array brackets
array-bracket-newline: [error, consistent]
## Enforce consistent spacing inside array brackets
array-bracket-spacing: [error, never]
## Enforce line breaks after each array element
# array-element-newline: error
## Disallow or enforce spaces inside of blocks after opening block and
## before closing block
block-spacing: [error, always]
## Enforce consistent brace style for blocks
# brace-style: [error, stroustrup, { allowSingleLine: false }]
## Enforce camelcase naming convention
# camelcase: error
## Enforce or disallow capitalization of the first letter of a comment
# capitalized-comments: error
## Require or disallow trailing commas
comma-dangle: [error, {
arrays: always-multiline,
objects: always-multiline,
imports: always-multiline,
exports: always-multiline,
functions: only-multiline, ## Optional on functions
}]
## Enforce consistent spacing before and after commas
comma-spacing: [error, { before: false, after: true }]
## Enforce consistent comma style
comma-style: [error, last]
## Enforce consistent spacing inside computed property brackets
computed-property-spacing: [error, never]
## Enforce consistent naming when capturing the current execution context
# consistent-this: error
## Require or disallow newline at the end of files
# eol-last: error
## Require or disallow spacing between function identifiers and their
## invocations
func-call-spacing: [error, never]
## Require function names to match the name of the variable or property
## to which they are assigned
# func-name-matching: error
## Require or disallow named function expressions
# func-names: error
## Enforce the consistent use of either function declarations or expressions
func-style: [error, expression]
## Enforce line breaks between arguments of a function call
# function-call-argument-newline: error
## Enforce consistent line breaks inside function parentheses
## NOTE: This rule does not honor a newline on opening paren.
# function-paren-newline: [error, never]
## Disallow specified identifiers
# id-blacklist: error
## Enforce minimum and maximum identifier lengths
# id-length: error
## Require identifiers to match a specified regular expression
# id-match: error
## Enforce the location of arrow function bodies
# implicit-arrow-linebreak: error
## Enforce consistent indentation
indent: [error, 2, { SwitchCase: 1 }]
## Enforce the consistent use of either double or single quotes in JSX
## attributes
jsx-quotes: [error, prefer-double]
## Enforce consistent spacing between keys and values in object literal
## properties
key-spacing: [error, { beforeColon: false, afterColon: true }]
## Enforce consistent spacing before and after keywords
keyword-spacing: [error, { before: true, after: true }]
## Enforce position of line comments
# line-comment-position: error
## Enforce consistent linebreak style
# linebreak-style: error
## Require empty lines around comments
# lines-around-comment: error
## Require or disallow an empty line between class members
# lines-between-class-members: error
## Enforce a maximum depth that blocks can be nested
# max-depth: error
## Enforce a maximum line length
max-len: [error, {
code: 80,
## Ignore imports
ignorePattern: '^(import\s.+\sfrom\s|.*require\()',
ignoreUrls: true,
ignoreRegExpLiterals: true,
}]
## Enforce a maximum number of lines per file
# max-lines: error
## Enforce a maximum number of line of code in a function
# max-lines-per-function: error
## Enforce a maximum depth that callbacks can be nested
# max-nested-callbacks: error
## Enforce a maximum number of parameters in function definitions
# max-params: error
## Enforce a maximum number of statements allowed in function blocks
# max-statements: error
## Enforce a maximum number of statements allowed per line
# max-statements-per-line: error
## Enforce a particular style for multiline comments
# multiline-comment-style: error
## Enforce newlines between operands of ternary expressions
multiline-ternary: [error, always-multiline]
## Require constructor names to begin with a capital letter
# new-cap: error
## Enforce or disallow parentheses when invoking a constructor with no
## arguments
# new-parens: error
## Require a newline after each call in a method chain
# newline-per-chained-call: error
## Disallow Array constructors
# no-array-constructor: error
## Disallow bitwise operators
# no-bitwise: error
## Disallow continue statements
# no-continue: error
## Disallow inline comments after code
# no-inline-comments: error
## Disallow if statements as the only statement in else blocks
# no-lonely-if: error
## Disallow mixed binary operators
# no-mixed-operators: error
## Disallow mixed spaces and tabs for indentation
no-mixed-spaces-and-tabs: error
## Disallow use of chained assignment expressions
# no-multi-assign: error
## Disallow multiple empty lines
# no-multiple-empty-lines: error
## Disallow negated conditions
# no-negated-condition: error
## Disallow nested ternary expressions
# no-nested-ternary: error
## Disallow Object constructors
# no-new-object: error
## Disallow the unary operators ++ and --
# no-plusplus: error
## Disallow specified syntax
# no-restricted-syntax: error
## Disallow all tabs
# no-tabs: error
## Disallow ternary operators
# no-ternary: error
## Disallow trailing whitespace at the end of lines
# no-trailing-spaces: error
## Disallow dangling underscores in identifiers
# no-underscore-dangle: error
## Disallow ternary operators when simpler alternatives exist
# no-unneeded-ternary: error
## Disallow whitespace before properties
no-whitespace-before-property: error
## Enforce the location of single-line statements
# nonblock-statement-body-position: error
## Enforce consistent line breaks inside braces
# object-curly-newline: [error, { multiline: true }]
## Enforce consistent spacing inside braces
object-curly-spacing: [error, always]
## Enforce placing object properties on separate lines
# object-property-newline: error
## Enforce variables to be declared either together or separately in
## functions
# one-var: error
## Require or disallow newlines around variable declarations
# one-var-declaration-per-line: error
## Require or disallow assignment operator shorthand where possible
# operator-assignment: error
## Enforce consistent linebreak style for operators
operator-linebreak: [error, before]
## Require or disallow padding within blocks
# padded-blocks: error
## Require or disallow padding lines between statements
# padding-line-between-statements: error
## Disallow using Object.assign with an object literal as the first
## argument and prefer the use of object spread instead.
# prefer-object-spread: error
## Require quotes around object literal property names
# quote-props: error
## Enforce the consistent use of either backticks, double, or single quotes
# quotes: [error, single]
## Require or disallow semicolons instead of ASI
semi: error
## Enforce consistent spacing before and after semicolons
semi-spacing: [error, { before: false, after: true }]
## Enforce location of semicolons
semi-style: [error, last]
## Require object keys to be sorted
# sort-keys: error
## Require variables within the same declaration block to be sorted
# sort-vars: error
## Enforce consistent spacing before blocks
space-before-blocks: [error, always]
## Enforce consistent spacing before function definition opening parenthesis
space-before-function-paren: [error, {
anonymous: always,
named: never,
asyncArrow: always,
}]
## Enforce consistent spacing inside parentheses
space-in-parens: [error, never]
## Require spacing around infix operators
# space-infix-ops: error
## Enforce consistent spacing before or after unary operators
# space-unary-ops: error
## Enforce consistent spacing after the // or /* in a comment
spaced-comment: [error, always]
## Enforce spacing around colons of switch statements
switch-colon-spacing: [error, { before: false, after: true }]
## Require or disallow spacing between template tags and their literals
template-tag-spacing: [error, never]
## Require or disallow Unicode byte order mark (BOM)
# unicode-bom: [error, never]
## Require parenthesis around regex literals
# wrap-regex: error
## ES6
## ----------------------------------------
## Require braces around arrow function bodies
# arrow-body-style: error
## Require parentheses around arrow function arguments
arrow-parens: [error, as-needed]
## Enforce consistent spacing before and after the arrow in arrow functions
arrow-spacing: [error, { before: true, after: true }]
## Require super() calls in constructors
# constructor-super: error
## Enforce consistent spacing around * operators in generator functions
generator-star-spacing: [error, { before: false, after: true }]
## Disallow reassigning class members
no-class-assign: error
## Disallow arrow functions where they could be confused with comparisons
# no-confusing-arrow: error
## Disallow reassigning const variables
no-const-assign: error
## Disallow duplicate class members
no-dupe-class-members: error
## Disallow duplicate module imports
# no-duplicate-imports: error
## Disallow new operators with the Symbol object
no-new-symbol: error
## Disallow specified modules when loaded by import
# no-restricted-imports: error
## Disallow this/super before calling super() in constructors
no-this-before-super: error
## Disallow unnecessary computed property keys in object literals
# no-useless-computed-key: error
## Disallow unnecessary constructors
# no-useless-constructor: error
## Disallow renaming import, export, and destructured assignments to the
## same name
# no-useless-rename: error
## Require let or const instead of var
no-var: error
## Require or disallow method and property shorthand syntax for object
## literals
# object-shorthand: error
## Require using arrow functions for callbacks
prefer-arrow-callback: error
## Require const declarations for variables that are never reassigned after
## declared
# prefer-const: error
## Require destructuring from arrays and/or objects
# prefer-destructuring: error
## Disallow parseInt() and Number.parseInt() in favor of binary, octal, and
## hexadecimal literals
# prefer-numeric-literals: error
## Require rest parameters instead of arguments
# prefer-rest-params: error
## Require spread operators instead of .apply()
# prefer-spread: error
## Require template literals instead of string concatenation
# prefer-template: error
## Require generator functions to contain yield
# require-yield: error
## Enforce spacing between rest and spread operators and their expressions
# rest-spread-spacing: error
## Enforce sorted import declarations within modules
# sort-imports: error
## Require symbol descriptions
# symbol-description: error
## Require or disallow spacing around embedded expressions of template
## strings
# template-curly-spacing: error
## Require or disallow spacing around the * in yield* expressions
yield-star-spacing: [error, { before: false, after: true }]
## React
## ----------------------------------------
## Enforces consistent naming for boolean props
react/boolean-prop-naming: error
## Forbid "button" element without an explicit "type" attribute
react/button-has-type: error
## Prevent extraneous defaultProps on components
react/default-props-match-prop-types: error
## Rule enforces consistent usage of destructuring assignment in component
# react/destructuring-assignment: [error, always, { ignoreClassFields: true }]
## Prevent missing displayName in a React component definition
react/display-name: error
## Forbid certain props on Components
# react/forbid-component-props: error
## Forbid certain props on DOM Nodes
# react/forbid-dom-props: error
## Forbid certain elements
# react/forbid-elements: error
## Forbid certain propTypes
# react/forbid-prop-types: error
## Forbid foreign propTypes
# react/forbid-foreign-prop-types: error
## Prevent using this.state inside this.setState
react/no-access-state-in-setstate: error
## Prevent using Array index in key props
# react/no-array-index-key: error
## Prevent passing children as props
react/no-children-prop: error
## Prevent usage of dangerous JSX properties
react/no-danger: error
## Prevent problem with children and props.dangerouslySetInnerHTML
react/no-danger-with-children: error
## Prevent usage of deprecated methods, including component lifecycle
## methods
react/no-deprecated: error
## Prevent usage of setState in componentDidMount
react/no-did-mount-set-state: error
## Prevent usage of setState in componentDidUpdate
react/no-did-update-set-state: error
## Prevent direct mutation of this.state
react/no-direct-mutation-state: error
## Prevent usage of findDOMNode
react/no-find-dom-node: error
## Prevent usage of isMounted
react/no-is-mounted: error
## Prevent multiple component definition per file
# react/no-multi-comp: error
## Prevent usage of shouldComponentUpdate when extending React.PureComponent
react/no-redundant-should-component-update: error
## Prevent usage of the return value of React.render
react/no-render-return-value: error
## Prevent usage of setState
# react/no-set-state: error
## Prevent common casing typos
react/no-typos: error
## Prevent using string references in ref attribute.
react/no-string-refs: error
## Prevent using this in stateless functional components
react/no-this-in-sfc: error
## Prevent invalid characters from appearing in markup
react/no-unescaped-entities: error
## Prevent usage of unknown DOM property (fixable)
# react/no-unknown-property: error
## Prevent usage of unsafe lifecycle methods
react/no-unsafe: error
## Prevent definitions of unused prop types
react/no-unused-prop-types: error
## Prevent definitions of unused state properties
react/no-unused-state: error
## Prevent usage of setState in componentWillUpdate
react/no-will-update-set-state: error
## Enforce ES5 or ES6 class for React Components
react/prefer-es6-class: error
## Enforce that props are read-only
react/prefer-read-only-props: error
## Enforce stateless React Components to be written as a pure function
react/prefer-stateless-function: error
## Prevent missing props validation in a React component definition
# react/prop-types: error
## Prevent missing React when using JSX
# react/react-in-jsx-scope: error
## Enforce a defaultProps definition for every prop that is not a required
## prop
# react/require-default-props: error
## Enforce React components to have a shouldComponentUpdate method
# react/require-optimization: error
## Enforce ES5 or ES6 class for returning value in render function
react/require-render-return: error
## Prevent extra closing tags for components without children (fixable)
react/self-closing-comp: error
## Enforce component methods order (fixable)
# react/sort-comp: error
## Enforce propTypes declarations alphabetical sorting
# react/sort-prop-types: error
## Enforce the state initialization style to be either in a constructor or
## with a class property
react/state-in-constructor: error
## Enforces where React component static properties should be positioned.
# react/static-property-placement: error
## Enforce style prop value being an object
react/style-prop-object: error
## Prevent void DOM elements (e.g. <img />, <br />) from receiving children
react/void-dom-elements-no-children: error
## JSX-specific rules
## ----------------------------------------
## Enforce boolean attributes notation in JSX (fixable)
react/jsx-boolean-value: error
## Enforce or disallow spaces inside of curly braces in JSX attributes and
## expressions.
# react/jsx-child-element-spacing: error
## Validate closing bracket location in JSX (fixable)
react/jsx-closing-bracket-location: [error, {
## NOTE: Not really sure about enforcing this one
selfClosing: false,
nonEmpty: after-props,
}]
## Validate closing tag location in JSX (fixable)
react/jsx-closing-tag-location: error
## Enforce or disallow newlines inside of curly braces in JSX attributes and
## expressions (fixable)
react/jsx-curly-newline: error
## Enforce or disallow spaces inside of curly braces in JSX attributes and
## expressions (fixable)
react/jsx-curly-spacing: error
## Enforce or disallow spaces around equal signs in JSX attributes (fixable)
react/jsx-equals-spacing: error
## Restrict file extensions that may contain JSX
# react/jsx-filename-extension: error
## Enforce position of the first prop in JSX (fixable)
# react/jsx-first-prop-new-line: error
## Enforce event handler naming conventions in JSX
react/jsx-handler-names: error
## Validate JSX indentation (fixable)
react/jsx-indent: [error, 2, {
checkAttributes: true,
}]
## Validate props indentation in JSX (fixable)
react/jsx-indent-props: [error, 2]
## Validate JSX has key prop when in array or iterator
react/jsx-key: error
## Validate JSX maximum depth
react/jsx-max-depth: [error, { max: 10 }] ## Generous
## Limit maximum of props on a single line in JSX (fixable)
# react/jsx-max-props-per-line: error
## Prevent usage of .bind() and arrow functions in JSX props
# react/jsx-no-bind: error
## Prevent comments from being inserted as text nodes
react/jsx-no-comment-textnodes: error
## Prevent duplicate props in JSX
react/jsx-no-duplicate-props: error
## Prevent usage of unwrapped JSX strings
# react/jsx-no-literals: error
## Prevent usage of unsafe target='_blank'
react/jsx-no-target-blank: error
## Disallow undeclared variables in JSX
react/jsx-no-undef: error
## Disallow unnecessary fragments (fixable)
react/jsx-no-useless-fragment: error
## Limit to one expression per line in JSX
# react/jsx-one-expression-per-line: error
## Enforce curly braces or disallow unnecessary curly braces in JSX
# react/jsx-curly-brace-presence: error
## Enforce shorthand or standard form for React fragments
react/jsx-fragments: error
## Enforce PascalCase for user-defined JSX components
react/jsx-pascal-case: error
## Disallow multiple spaces between inline JSX props (fixable)
react/jsx-props-no-multi-spaces: error
## Disallow JSX props spreading
# react/jsx-props-no-spreading: error
## Enforce default props alphabetical sorting
# react/jsx-sort-default-props: error
## Enforce props alphabetical sorting (fixable)
# react/jsx-sort-props: error
## Validate whitespace in and around the JSX opening and closing brackets
## (fixable)
react/jsx-tag-spacing: error
## Prevent React to be incorrectly marked as unused
react/jsx-uses-react: error
## Prevent variables used in JSX to be incorrectly marked as unused
react/jsx-uses-vars: error
## Prevent missing parentheses around multilines JSX (fixable)
react/jsx-wrap-multilines: error
+10
View File
@@ -0,0 +1,10 @@
* text=auto
## Enforce text mode and LF line breaks
*.js text eol=lf
*.css text eol=lf
*.html text eol=lf
*.json text eol=lf
## Treat bundles as binary and ignore them during conflicts
*.bundle.* binary merge=tgui-merge-bundle
+7
View File
@@ -0,0 +1,7 @@
node_modules
*.log
package-lock.json
/packages/tgui/public/.tmp/**/*
/packages/tgui/public/**/*.hot-update.*
/packages/tgui/public/**/*.map
+187
View File
@@ -0,0 +1,187 @@
# tgui
## Introduction
tgui is a robust user interface framework of /tg/station.
tgui is very different from most UIs you will encounter in BYOND programming.
It is heavily reliant on Javascript and web technologies as opposed to DM.
If you are familiar with NanoUI (a library which can be found on almost
every other SS13 codebase), tgui should be fairly easy to pick up.
## Learn tgui
People come to tgui from different backgrounds and with different
learning styles. Whether you prefer a more theoretical or a practical
approach, we hope youll find this section helpful.
### Practical Tutorial
If you are completely new to frontend and prefer to **learn by doing**,
start with our [practical tutorial](docs/tutorial-and-examples.md).
### Guides
This project uses **Inferno** - a very fast UI rendering engine with a similar
API to React. Take your time to read these guides:
- [React guide](https://reactjs.org/docs/hello-world.html)
- [Inferno documentation](https://infernojs.org/docs/guides/components) -
highlights differences with React.
If you were already familiar with an older, Ractive-based tgui, and want
to translate concepts between old and new tgui, read this
[interface conversion guide](docs/converting-old-tgui-interfaces.md).
## Pre-requisites
You will need these programs to start developing in tgui:
- [Node v12.13+](https://nodejs.org/en/download/)
- [Yarn v1.19+](https://yarnpkg.com/en/docs/install)
- [MSys2](https://www.msys2.org/) (optional)
> MSys2 closely replicates a unix-like environment which is necessary for
> the `bin/tgui` script to run. It comes with a robust "mintty" terminal
> emulator which is better than any standard Windows shell, it supports
> "git" out of the box (almost like Git for Windows, but better), has
> a "pacman" package manager, and you can install a text editor like "vim"
> for a full boomer experience.
## Usage
**For MSys2, Git Bash, WSL, Linux or macOS users:**
First and foremost, change your directory to `tgui`.
Run `bin/tgui --install-git-hooks` (optional) to install merge drivers
which will assist you in conflict resolution when rebasing your branches.
Run one of the following:
- `bin/tgui` - build the project in production mode.
- `bin/tgui --dev` - launch a development server.
- tgui development server provides you with incremental compilation,
hot module replacement and logging facilities in all running instances
of tgui. In short, this means that you will instantly see changes in the
game as you code it. Very useful, highly recommended.
- In order to use it, you should start the game server first, connect to it
and wait until the world has been properly loaded and you are no longer
in the lobby. Start tgui dev server. You'll know that it's hooked correctly
if data gets dumped to the log when tgui windows are opened.
- `bin/tgui --dev --reload` - reload byond cache once.
- `bin/tgui --dev --debug` - run server with debug logging enabled.
- `bin/tgui --dev --no-hot` - disable hot module replacement (helps when
doing development on IE8).
- `bin/tgui --lint` - show problems with the code.
- `bin/tgui --lint --fix` - auto-fix problems with the code.
- `bin/tgui --analyze` - run a bundle analyzer.
- `bin/tgui --clean` - clean up project repo.
- `bin/tgui [webpack options]` - build the project with custom webpack
options.
**For everyone else:**
If you haven't opened the console already, you can do that by holding
Shift and right clicking on the `tgui` folder, then pressing
either `Open command window here` or `Open PowerShell window here`.
Run `yarn install` to install npm dependencies, then one of the following:
- `yarn run build` - build the project in production mode.
- `yarn run watch` - launch a development server.
- `yarn run lint` - show problems with the code.
- `yarn run lint --fix` - auto-fix problems with the code.
- `yarn run analyze` - run a bundle analyzer.
We also got some batch files in store, for those who don't like fiddling
with the console:
- `bin/tgui-build.bat` - build the project in production mode.
- `bin/tgui-dev-server.bat` - launch a development server.
> Remember to always run a full build before submitting a PR. It creates
> a compressed javascript bundle which is then referenced from DM code.
> We prefer to keep it version controlled, so that people could build the
> game just by using Dream Maker.
## Troubleshooting
**Development server doesn't find my BYOND cache!**
This happens if your Documents folder in Windows has a custom location, for
example in `E:\Libraries\Documents`. Development server has no knowledge
of these non-standard locations, therefore you have to run the dev server
with an additional environmental variable, with a full path to BYOND cache.
```
export BYOND_CACHE="E:/Libraries/Documents/BYOND/cache"
bin/tgui --dev
```
Note that in Windows, you have to go through Advanced System Settings,
System Properties and then open Environment Variables window to do the
same thing. You may need to reboot after this.
## Developer Tools
When developing with `tgui-dev-server`, you will have access to certain
development only features.
**Debug Logs.**
When running server via `bin/tgui --dev --debug`, server will print debug
logs and time spent on rendering. Use this information to optimize your
code, and try to keep re-renders below 16ms.
**Kitchen Sink.**
Press `Ctrl+Alt+=` to open the KitchenSink interface. This interface is a
playground to test various tgui components.
**Layout Debugger.**
Press `Ctrl+Alt+-` to toggle the *layout debugger*. It will show outlines of
all tgui elements, which makes it easy to understand how everything comes
together, and can reveal certain layout bugs which are not normally visible.
## Project Structure
- `/packages` - Each folder here represents a self-contained Node module.
- `/packages/common` - Helper functions
- `/packages/tgui/index.js` - Application entry point.
- `/packages/tgui/components` - Basic UI building blocks.
- `/packages/tgui/interfaces` - Actual in-game interfaces.
Interface takes data via the `state` prop and outputs an html-like stucture,
which you can build using existing UI components.
- `/packages/tgui/layouts` - Root level UI components, that affect the final
look and feel of the browser window. They usually hold various window
elements, like the titlebar and resize handlers, and control the UI theme.
- `/packages/tgui/routes.js` - This is where tgui decides which interface to
pull and render.
- `/packages/tgui/layout.js` - A root-level component, holding the
window elements, like the titlebar, buttons, resize handlers. Calls
`routes.js` to decide which component to render.
- `/packages/tgui/styles/main.scss` - CSS entry point.
- `/packages/tgui/styles/functions.scss` - Useful SASS functions.
Stuff like `lighten`, `darken`, `luminance` are defined here.
- `/packages/tgui/styles/atomic` - Atomic CSS classes.
These are very simple, tiny, reusable CSS classes which you can use and
combine to change appearance of your elements. Keep them small.
- `/packages/tgui/styles/components` - CSS classes which are used
in UI components. These stylesheets closely follow the
[BEM](https://en.bem.info/methodology/) methodology.
- `/packages/tgui/styles/interfaces` - Custom stylesheets for your interfaces.
Add stylesheets here if you really need a fine control over your UI styles.
- `/packages/tgui/styles/layouts` - Layout-related styles.
- `/packages/tgui/styles/themes` - Contains all the various themes you can
use in tgui. Each theme must be registered in `webpack.config.js` file.
## Component Reference
See: [Component Reference](docs/component-reference.md).
## License
All code is licensed with the parent license of *tgstation*, **AGPL-3.0**.
See the main [README](../README.md) for more details.
The Authors retain all copyright to their respective work here submitted.
+173
View File
@@ -0,0 +1,173 @@
#!/bin/bash
set -e
shopt -s globstar
shopt -s expand_aliases
## Initial set-up
## --------------------------------------------------------
## Returns an absolute path to file
alias tgui-realpath="readlink -f"
## Fallbacks for GNU readlink
## Detecting GNU coreutils http://stackoverflow.com/a/8748344/319952
if ! readlink --version >/dev/null 2>&1; then
if hash greadlink 2>/dev/null; then
alias tgui-realpath="greadlink -f"
else
alias tgui-realpath="perl -MCwd -le 'print Cwd::abs_path(shift)'"
fi
fi
## Find a canonical path to project root
base_dir="$(dirname "$(tgui-realpath "${0}")")/.."
base_dir="$(tgui-realpath "${base_dir}")"
## Add locally installed node programs to path
PATH="${PATH}:node_modules/.bin"
## Functions
## --------------------------------------------------------
## Installs node modules
task-install() {
cd "${base_dir}"
yarn install
}
## Runs webpack
task-webpack() {
cd "${base_dir}/packages/tgui"
webpack "${@}"
}
## Runs a development server
task-dev-server() {
cd "${base_dir}/packages/tgui-dev-server"
exec node --experimental-modules index.js "${@}"
}
## Run a linter through all packages
task-eslint() {
cd "${base_dir}"
eslint ./packages "${@}"
}
## Mr. Proper
task-clean() {
cd "${base_dir}"
rm -rf packages/tgui/public/.tmp
rm -rf **/node_modules
rm -f **/package-lock.json
}
## Validates current build against the build stored in git
task-validate-build() {
cd "${base_dir}"
local diff
diff="$(git diff packages/tgui/public/tgui.bundle.*)"
if [[ -n ${diff} ]]; then
echo "Error: our build differs from the build committed into git."
echo "Please rebuild tgui."
exit 1
fi
echo "tgui: build is ok"
}
## Installs merge drivers and git hooks
task-install-git-hooks() {
cd "${base_dir}"
local git_root
local git_base_dir
git_root="$(git rev-parse --show-toplevel)"
git_base_dir="${base_dir/${git_root}/.}"
git config --replace-all merge.tgui-merge-bundle.driver \
"${git_base_dir}/bin/tgui --merge=bundle %O %A %B %L"
echo "tgui: Merge drivers have been successfully installed!"
}
## Bundle merge driver
task-merge-bundle() {
local file_ancestor="${1}"
local file_current="${2}"
local file_other="${3}"
local conflict_marker_size="${4}"
echo "tgui: Discarding a local tgui build"
## Do nothing (file_current will be merged and is what we want to keep).
exit 0
}
## Main
## --------------------------------------------------------
if [[ ${1} == "--merge"* ]]; then
if [[ ${1} == "--merge=bundle" ]]; then
shift 1
task-merge-bundle "${@}"
fi
echo "Unknown merge strategy: ${1}"
exit 1
fi
if [[ ${1} == "--install-git-hooks" ]]; then
shift 1
task-install-git-hooks
exit 0
fi
## Continuous integration scenario
if [[ ${1} == "--ci" ]]; then
task-clean
task-install
task-eslint
task-webpack --mode=production
task-validate-build
exit 0
fi
if [[ ${1} == "--clean" ]]; then
task-clean
exit 0
fi
if [[ ${1} == "--dev" ]]; then
shift
task-install
task-dev-server "${@}"
exit 0
fi
if [[ ${1} == '--lint' ]]; then
shift 1
task-install
task-eslint "${@}"
exit 0
fi
if [[ ${1} == '--lint-harder' ]]; then
shift 1
task-install
task-eslint -c .eslintrc-harder.yml "${@}"
exit 0
fi
## Analyze the bundle
if [[ ${1} == '--analyze' ]]; then
task-install
task-webpack --mode=production --analyze
exit 0
fi
## Make a production webpack build
if [[ -z ${1} ]]; then
task-install
task-eslint
task-webpack --mode=production
exit 0
fi
## Run webpack with custom flags
task-install
task-webpack "${@}"
+5
View File
@@ -0,0 +1,5 @@
@echo off
cd "%~dp0\.."
call yarn install
call yarn run build
timeout /t 9
+4
View File
@@ -0,0 +1,4 @@
@echo off
cd "%~dp0\.."
call yarn install
call yarn run watch
File diff suppressed because it is too large Load Diff
+321
View File
@@ -0,0 +1,321 @@
# Converting old NanoUI interfaces to TGUI
This guide is going to assume you already know roughly how tgui-next works, how to make new uis, etc. It's mostly aimed at helping translate concepts between nano and tgui-next, and clarify some confusing parts of the transition.
## Backend
Backend in almost every case does not require any changes. In particularly heavy ui cases, something to be aware of is the new `tgui_static_data()` proc. This proc allows you to split some data sent to the interface off into data that will only be sent on ui initialize and when manually updated by elsewhere in the code. Useful for things like cargo where you have a very large set of mostly identical code.
Keep in mind that for uis where *all* data doesn't need to be live updating, you can just toggle off autoupdate for the ui instead of messing with static data.
## Frontend
The very first thing to note is the name of the `tmpl` file containing the old interface. Whatever the name is (minus the extension) is going to be what the route key is going to be.
One thing I like to do before starting work on a conversion is screenshot what the old interface looks like so I have something to reference to make sure that the styling can line up as well.
## General syntax changes
Ractive has a fairly different templating syntax from React.
### `data`
You likely already know that React data inserts look like this
```jsx
{data.example_data}
```
Ractive looks very similar, the only real difference is that React uses one paranthesis instead of two.
```tmpl
{{data.example_data}}
```
However, you may occasionally come across data inserts that instead of referencing the `data` var or things contained within it instead reference `adata`. `adata` was short for animated data, and was used for smooth number animations in interfaces. instead of having a seperate data structure for this. tgui-next instead uses a component, which is `AnimatedNumber`.
`AnimatedNumber` is used like this
```jsx
<AnimatedNumber value={data.example_data}/>
```
Make sure you don't forget to import it.
### Conditionals
Template conditionals look very different from React conditionals.
A template `if` (only render if result of expression is true) looks like this
```tmpl
{{#if data.condition}}
<span>Example Render</span>
{{/if}}
```
The equivalent React would be
```jsx
{!!data.condition && (
<Fragment>Example Render</Fragment>
)}
```
This might look a bit intimidating compared to the reactive part but it's not as complicated as it seems:
1. A new jsx context is opened with `{}`
2. jsx contexts like this always render whatever the return value is, so we can use `&&` to return a value we want. `&&` returns the last true value (or not "falsey" because this is js).
3. jsx tags are never "falsey", so a conditioned paired with a jsx tag will mean the condition being true will continue on and return the tag. `()` is just used to contain the tag
4. The `!!` is not a special operator, it is a literal double negation. This is because most `false` values coming from byond are going to actually be `0`, which would be rendered if the condition is false. Negating `0` returns `true`, negating `true` returns `false`, which isn't rendered.
5. `Fragment` is actually a true "dead tag". It's similar to `span` in that it just contains things without providing functionality, but it's unwrapped before the final render and children of it are injected into its parent. In a case where you only need to render text without any styling, it's probably better to just return a string literal (`"Example Render"`), but this was just to illustrate that you can put any tag in this expression.
You don't really need to know all this to understand how to use it, but I find it helps with understanding when things go wrong.
Template conditionals can have an `else` as well
```tmpl
{{#if data.condition}}
value
{{else}}
other value
{{/if}}
```
Similarly to the previous example, just add a `||` operator to handle the
"falsy" condition:
```jsx
{!!data.condition && (
<Fragment>
value
</Fragment>
) || (
<Fragment>
other value
</Fragment>
)}
```
There's also our good old friend - the ternary:
```jsx
{data.condition ? 'value' : 'other value'}
```
Keep in mind you can also use tags here like the conditional example,
and you can mix string literals, values, and tags as well.
```jsx
{data.is_robot ? (
<Button content="Robot Button"/>
) : 'Not a robot'}
```
### Loops
Templates have loops for iterating over data and inserting something for each
member of an array or object
```tmpl
{{for data.entries}}
{{:value.name}}
{{/for}}
```
This didn't care whether the data was an array or an object, and members of each entry of the loop were "unwrapped" so to say. `{{number}}` in that example is referring to the `{{number}}` value on the entry of the list for that iterate.
The React equivalent to this is going to be `map`.
_AN IMPORTANT DISTINCTION HERE IS THAT NOW WE CARE WHETHER THIS IS AN OBJECT OR AN ARRAY BEING ACTED ON._
Objects are represented by `{}`, arrays by `[]`
"How can I tell?" you may ask. It's fairly simple, associated lists on the byond side are going to be turned into objects when they get json converted, normal lists are going to be turned into arrays.
`list("bla", "blo")` would become `["bla", "blo"]` and `list("foo" = 1, "bar" = 2)` would become `{"foo": 1, "bar": 2}`
First things first, above the `return` of the function you're making the interface in, you're going to want to add something like this
```jsx
const things = data.things || [];
```
This ensures that you'll never be reading a null entry by mistake. Substitute `{}` for objects as appropriate.
If it's an array, you'll want to do this in the template
```jsx
{things.map(thing => (
<Fragment>
Thing {thing.number} is here!
</Fragment>
))}
```
`map` is a function that calls a passed function (a lambda) on each entry, and returns the value. You should already know that returned tags and values (except `false`) get rendered, so that's how it's rendering each time.
A lambda is what's known as an anonymous function, it's a function that doesn't have a name that's only used for a specific usage. `map` wants a function that has one parameter, so we define one parameter then use `=>` to say the parameter has to do with the following block.
`parameter => ()` is just a shorthand for `parameter => {return();}`
This is quite a bit higher concept than ractive's each statements, so feel free to look around and ~~copy paste~~ learn from how other interfaces use this.
Now for objects, there's a genuinely pretty gross syntax here. We apoligize, it's related to ie8 compatibility nonsense.
```jsx
{map((value, key) => (
<Fragment>
Key is {key}, value is {value}
</Fragment>
))(fooObject)}
```
Again, sorry for this syntax. `fooObject` would be the object being iterated on, value would be the value of the iterated entry on the list, and key would be the key. the naming of value and key isn't important here, but knowing that it goes `value`, `key` in that order is important.
It is sometimes better to preemptively convert an object to array before
the big return statement, like this:
```jsx
const fooArray = map((value, key) => {
return { key, value };
})(fooObject);
```
Or if you just want to discard all keys, this will also work nicely:
```jsx
const fooArray = toArray(fooObject);
```
If you want to see if an array has no contents and output a message, just check if array is empty like this:
```jsx
{fooArray.length === 0 && 'fooArray is empty.'}
{fooArray.map(foo => (
<Fragment>
Foo is {foo}
</Fragment>
))}
```
### Extra Stuff
I'll put some extra stuff here when I think of it.
## Components
This will be a reference of tgui components and the tgui-next equivalent.
### `ui-display`
Equivalent of `<ui-display>` is `<Section>`
```
<ui-display title="Status">
Contents
</ui-display>
```
becomes
```jsx
<Section title="Status">
Contents
</Section>
```
A feature sometimes used is if `ui-display` has the `button` property, it will contain a `partial` command. This becomes the `buttons` property on `Section`:
```
<ui-display title="Status" button>
{{#partial button}}
<ui-button /> // lots more button bullshit here
{{/partial}}
Contents
</ui-display>
```
becomes
```jsx
<Section
title="Status"
buttons={(
<Button />
)}>
Contents
</Section>
```
### `ui-section`
Very important to note `ui-section` is NOT the equivalent of `Section`
`<ui-section>` does not have a direct equivalent, but the closest equivalent is `<LabeledList>`
```
<ui-section label="power">
No Power
</ui-section>
<ui-section label="connection">
No Connection
</ui-section>
```
becomes
```jsx
<LabeledList>
<LabeledList.Item label="power">
No Power
</LabeledList.Item>
<LabeledList.Item label="connection">
No Connection
</LabeledList.Item>
</LabeledList>
```
Important to note that `LabeledList.Item` has `buttons` as well.
Also good to know that if you need the contents of a `LabeledList.Item` to be colored, you can just set the `color` prop on it instead of putting a `span` inside it.
### `ui-notice`
`<ui-notice>` has a direct equivalent in `<NoticeBox>`
```
<ui-notice>
Notice stuff!
</ui-notice>
```
becomes
```jsx
<NoticeBox>
Notice stuff!
</NoticeBox>
```
### `ui-button`
The equivalent of `ui-button` is `Button` but it works quite a bit differently.
```
<ui-button
state='{{data.condition ? "disabled" : null}}'
action="ui_action"
params={param: value}>
Click
</ui-button>
```
becomes
```jsx
<Button
content="Click"
disabled={data.condition}
onClick={() => act('ui_action', {
param: value,
})}/>
```
+356
View File
@@ -0,0 +1,356 @@
# Tutorial and Examples
## Main concepts
Basic tgui backend code consists of the following vars and procs:
```
tgui_interact(mob/user, ui_key, datum/tgui/ui, force_open,
datum/tgui/master_ui, datum/tgui_state/state)
tgui_data(mob/user)
tgui_act(action, params)
```
- `src_object` - The atom, which UI corresponds to in the game world.
- `tgui_interact` - The proc where you will handle a request to open an
interface. Typically, you would update an existing UI (if it exists),
or set up a new instance of UI by calling the `SStgui` subsystem.
- `tgui_data` - In this proc you munges whatever complex data your `src_object`
has into an associative list, which will then be sent to UI as a JSON string.
- `tgui_act` - This proc receives user actions and reacts to them by changing
the state of the game.
- `tgui_state` (set in `tgui_interact`) - This var dictates under what conditions
a UI may be interacted with. This may be the standard checks that check if
you are in range and conscious, or more.
Once backend is complete, you create an new interface component on the
frontend, which will receive this JSON data and render it on screen.
States are easy to write and extend, and what make tgui interactions so
powerful. Because states can be overridden from other procs, you can build
powerful interactions for embedded objects or remote access.
## Using It
### Backend
Let's start with a very basic hello world.
```dm
/obj/machinery/my_machine/tgui_interact(mob/user, ui_key = "main", datum/tgui/ui = null, force_open = 0, datum/tgui/master_ui = null, datum/tgui_state/state = GLOB.tgui_default_state)
ui = SStgui.try_update_ui(user, src, ui_key, ui, force_open)
if(!ui)
ui = new(user, src, ui_key, "my_machine", name, 300, 300, master_ui, state)
ui.open()
```
This is the proc that defines our interface. There's a bit going on here, so
let's break it down. First, we override the tgui_interact proc on our object. This
will be called by `interact` for you, which is in turn called by `attack_hand`
(or `attack_self` for items). `tgui_interact` is also called to update a UI (hence
the `try_update_ui`), so we accept an existing UI to update. The `state` is a
default argument so that a caller can overload it with named arguments
(`tgui_interact(state = overloaded_state)`) if needed.
Inside the `if(!ui)` block (which means we are creating a new UI), we choose our
template, title, and size; we can also set various options like `style` (for
themes), or autoupdate. These options will be elaborated on later (as will
`ui_state`s).
After `tgui_interact`, we need to define `tgui_data`. This just returns a list of
data for our object to use. Let's imagine our object has a few vars:
```dm
/obj/machinery/my_machine/tgui_data(mob/user)
var/list/data = list()
data["health"] = health
data["color"] = color
return data
```
The `tgui_data` proc is what people often find the hardest about tgui, but its
really quite simple! You just need to represent your object as numbers, strings,
and lists, instead of atoms and datums.
Finally, the `tgui_act` proc is called by the interface whenever the user used an
input. The input's `action` and `params` are passed to the proc.
```dm
/obj/machinery/my_machine/tgui_act(action, params)
if(..())
return
if(action == "change_color")
var/new_color = params["color"]
if(!(color in allowed_coors))
return FALSE
color = new_color
. = TRUE
update_icon()
```
The `..()` (parent call) is very important here, as it is how we check that the
user is allowed to use this interface (to avoid so-called href exploits). It is
also very important to clamp and sanitize all input here. Always assume the user
is attempting to exploit the game.
Also note the use of `. = TRUE` (or `FALSE`), which is used to notify the UI
that this input caused an update. This is especially important for UIs that do
not auto-update, as otherwise the user will never see their change.
### Frontend
Finally, let's make a React Component for your interface. This is also
a source of confusion for new developers. If you got some basic javascript
and HTML knowledge, that should ease the learning process, although we
recommend getting yourself introduced to
[React and JSX](https://reactjs.org/docs/introducing-jsx.html).
A React component is not a regular HTML template. A component is a
javascript function, which accepts a `props` object (that contains
properties passed to a component) and a `context` object (which is
necessary to access UI data) as arguments, and outputs an HTML-like
structure.
So let's create our first React Component. Create a file with a name
`SampleInterface.js` (or any other name you want), and copy this code
snippet (make sure component name matches the file name):
```jsx
import { useBackend } from '../backend';
import { Button, LabeledList, Section } from '../components';
import { Window } from '../layouts';
export const SampleInterface = (props, context) => {
const { act, data } = useBackend(context);
// Extract `health` and `color` variables from the `data` object.
const {
health,
color,
} = data;
return (
<Window resizable>
<Window.Content scrollable>
<Section title="Health status">
<LabeledList>
<LabeledList.Item label="Health">
{health}
</LabeledList.Item>
<LabeledList.Item label="Color">
{color}
</LabeledList.Item>
<LabeledList.Item label="Button">
<Button
content="Dispatch a 'test' action"
onClick={() => act('test')} />
</LabeledList.Item>
</LabeledList>
</Section>
</Window.Content>
</Window>
);
};
```
Here are the key variables you get from a `useBackend(context)` function:
- `config` is part of core tgui. It contains meta-information about the
interface and who uses it, BYOND refs to various objects, and so forth.
You are rarely going to use it, but sometimes it can be used to your
advantage when doing complex UIs.
- `data` is the data returned from `tgui_data` and `tgui_static_data` procs in
your DM code. Pretty straight forward.
- Note, that javascript doesn't have associative arrays, so when you
return an associative list from DM, it will be available in `data` as a
javascript object instead of an array. You can use it normally
like so: `object.key`, so it's not a problem if it's representing a
data structure, but common `Array` methods, such as `array.map(item => ...)`,
are not available on it. Always prefer returning clean arrays from your
code, since arrays are easier to work with in javascript!
- `act(name, params)` is a function, which you can call to dispatch an action
to your DM code. It will be processed in `ui_act` proc. Action name will be
available in `params["action"]`, mixed together with the rest of parameters
you have passed in `params` object.
**Let's talk about the syntax.**
The syntax you're seeing here is called JSX - a very simple extension of the
core javascript language. It's basically a pre-processor, that takes
expressions that look like html, and turns them into function calls.
Take a look at this example:
```jsx
<div className={'color-' + status}>
You are in {status} condition!
</div>
```
After compiling the code above, this is what it becomes:
```js
createElement('div',
{ className: 'color-' + status },
'You are in ', status, ' condition!');
```
It is very important to remember, that JSX is just a javascript expression
made out of `createElement` function calls. Naturally, this allows doing
all sorts of stuff on these expressions, just like you would with anything
else in javascript.
Take a look at these examples:
**Render an element inside of another element if `showProgress` is true.**
This example uses the `&&` operator (the logical AND). It returns
the first operand if it evaluates to `false`, and returns the second operand
if it evaluates to `true`.
If `showProgress` is `true`, the whole expression evaluates
to a `<ProgressBar />` element. If `showProgress` is `false`, the whole
expression evaluates to `false`, and `false` is not rendered by React.
```jsx
<Box>
{showProgress && (
<ProgressBar value={progress} />
)}
</Box>
```
You can also use the `||` operator (the logical OR), which works the same way,
except it will return the second operand on `false` instead of `true`.
**Loop over the array to map every item to a corresponding React element.**
`Array.map()` is a method, that calls a function on every item in the array,
and builds a new array based on what was returned by that function.
```jsx
<LabeledList>
{items.map(item => (
<LabeledList.Item
key={item.id}
label={item.label}>
{item.content}
</LabeledList.Item>
))}
</LabeledList>
```
If you need more examples of what you can do with React, see the
[interface conversion guide](docs/converting-old-tgui-interfaces.md).
#### Splitting UIs into smaller, modular components
You interface will eventually get really, really big. The easiest thing
you can do in this situation, is divide and conquer. Grab a chunk of your
JSX code, and wrap it into a second, smaller React component:
```jsx
import { useBackend } from '../backend';
import { Button, LabeledList, Section } from '../components';
import { Window } from '../layouts';
export const SampleInterface = (props, context) => {
return (
<Window resizable>
<Window.Content scrollable>
<HealthStatus user="Jerry" />
</Window.Content>
</Window>
);
};
const HealthStatus = (props, context) => {
const { act, data } = useBackend(context);
const {
user,
} = props;
const {
health,
color,
} = data;
return (
<Section title={"Health status of: " + user}>
<LabeledList>
<LabeledList.Item label="Health">
{health}
</LabeledList.Item>
<LabeledList.Item label="Color">
{color}
</LabeledList.Item>
</LabeledList>
</Section>
);
};
```
## Copypasta
We all do it, even the best of us. If you just want to make a tgui **fast**,
here's what you need (note that you'll probably be forced to clean your shit up
upon code review):
```dm
/obj/copypasta/tgui_interact(mob/user, ui_key = "main", datum/tgui/ui = null, force_open = 0, datum/tgui/master_ui = null, datum/tgui_state/state = GLOB.tgui_default_state) // Remember to use the appropriate state.
ui = SStgui.try_update_ui(user, src, ui_key, ui, force_open)
if(!ui)
ui = new(user, src, ui_key, "copypasta", name, 300, 300, master_ui, state)
ui.open()
/obj/copypasta/tgui_data(mob/user)
var/list/data = list()
data["var"] = var
return data
/obj/copypasta/tgui_act(action, params)
if(..())
return
switch(action)
if("copypasta")
var/newvar = params["var"]
// A demo of proper input sanitation.
var = CLAMP(newvar, min_val, max_val)
. = TRUE
update_icon() // Not applicable to all objects.
```
And the template:
```jsx
import { useBackend } from '../backend';
import { Button, LabeledList, Section } from '../components';
import { Window } from '../layouts';
export const SampleInterface = (props, context) => {
const { act, data } = useBackend(context);
// Extract `health` and `color` variables from the `data` object.
const {
health,
color,
} = data;
return (
<Window resizable>
<Window.Content scrollable>
<Section title="Health status">
<LabeledList>
<LabeledList.Item label="Health">
{health}
</LabeledList.Item>
<LabeledList.Item label="Color">
{color}
</LabeledList.Item>
<LabeledList.Item label="Button">
<Button
content="Dispatch a 'test' action"
onClick={() => act('test')} />
</LabeledList.Item>
</LabeledList>
</Section>
</Window.Content>
</Window>
);
};
```
+19
View File
@@ -0,0 +1,19 @@
{
"private": true,
"name": "tgui",
"version": "3.0.0",
"workspaces": [
"packages/*"
],
"scripts": {
"build": "eslint packages && cd packages/tgui && npx webpack --mode=production",
"watch": "cd packages/tgui-dev-server && node --experimental-modules index.js",
"analyze": "cd packages/tgui && npx webpack --mode=production --env.analyze=1",
"lint": "eslint packages"
},
"dependencies": {
"babel-eslint": "^10.0.3",
"eslint": "^6.7.2",
"eslint-plugin-react": "^7.17.0"
}
}
+265
View File
@@ -0,0 +1,265 @@
/**
* Converts a given collection to an array.
*
* - Arrays are returned unmodified;
* - If object was provided, keys will be discarded;
* - Everything else will result in an empty array.
*
* @returns {any[]}
*/
export const toArray = collection => {
if (Array.isArray(collection)) {
return collection;
}
if (typeof collection === 'object') {
const hasOwnProperty = Object.prototype.hasOwnProperty;
const result = [];
for (let i in collection) {
if (hasOwnProperty.call(collection, i)) {
result.push(collection[i]);
}
}
return result;
}
return [];
};
/**
* Converts a given object to an array, and appends a key to every
* object inside of that array.
*
* Example input (object):
* ```
* {
* 'Foo': { info: 'Hello world!' },
* 'Bar': { info: 'Hello world!' },
* }
* ```
*
* Example output (array):
* ```
* [
* { key: 'Foo', info: 'Hello world!' },
* { key: 'Bar', info: 'Hello world!' },
* ]
* ```
*
* @template T
* @param {{ [key: string]: T }} obj Object, or in DM terms, an assoc array
* @param {string} keyProp Property, to which key will be assigned
* @returns {T[]} Array of keyed objects
*/
export const toKeyedArray = (obj, keyProp = 'key') => {
return map((item, key) => ({
[keyProp]: key,
...item,
}))(obj);
};
/**
* Iterates over elements of collection, returning an array of all elements
* iteratee returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* If collection is 'null' or 'undefined', it will be returned "as is"
* without emitting any errors (which can be useful in some cases).
*
* @returns {any[]}
*/
export const filter = iterateeFn => collection => {
if (collection === null && collection === undefined) {
return collection;
}
if (Array.isArray(collection)) {
const result = [];
for (let i = 0; i < collection.length; i++) {
const item = collection[i];
if (iterateeFn(item, i, collection)) {
result.push(item);
}
}
return result;
}
throw new Error(`filter() can't iterate on type ${typeof collection}`);
};
/**
* Creates an array of values by running each element in collection
* thru an iteratee function. The iteratee is invoked with three
* arguments: (value, index|key, collection).
*
* If collection is 'null' or 'undefined', it will be returned "as is"
* without emitting any errors (which can be useful in some cases).
*
* @returns {any[]}
*/
export const map = iterateeFn => collection => {
if (collection === null && collection === undefined) {
return collection;
}
if (Array.isArray(collection)) {
const result = [];
for (let i = 0; i < collection.length; i++) {
result.push(iterateeFn(collection[i], i, collection));
}
return result;
}
if (typeof collection === 'object') {
const hasOwnProperty = Object.prototype.hasOwnProperty;
const result = [];
for (let i in collection) {
if (hasOwnProperty.call(collection, i)) {
result.push(iterateeFn(collection[i], i, collection));
}
}
return result;
}
throw new Error(`map() can't iterate on type ${typeof collection}`);
};
const COMPARATOR = (objA, objB) => {
const criteriaA = objA.criteria;
const criteriaB = objB.criteria;
const length = criteriaA.length;
for (let i = 0; i < length; i++) {
const a = criteriaA[i];
const b = criteriaB[i];
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
}
return 0;
};
/**
* Creates an array of elements, sorted in ascending order by the results
* of running each element in a collection thru each iteratee.
*
* Iteratees are called with one argument (value).
*
* @returns {any[]}
*/
export const sortBy = (...iterateeFns) => array => {
if (!Array.isArray(array)) {
return array;
}
let length = array.length;
// Iterate over the array to collect criteria to sort it by
let mappedArray = [];
for (let i = 0; i < length; i++) {
const value = array[i];
mappedArray.push({
criteria: iterateeFns.map(fn => fn(value)),
value,
});
}
// Sort criteria using the base comparator
mappedArray.sort(COMPARATOR);
// Unwrap values
while (length--) {
mappedArray[length] = mappedArray[length].value;
}
return mappedArray;
};
/**
* A fast implementation of reduce.
*/
export const reduce = (reducerFn, initialValue) => array => {
const length = array.length;
let i;
let result;
if (initialValue === undefined) {
i = 1;
result = array[0];
}
else {
i = 0;
result = initialValue;
}
for (; i < length; i++) {
result = reducerFn(result, array[i], i, array);
}
return result;
};
/**
* Creates a duplicate-free version of an array, using SameValueZero for
* equality comparisons, in which only the first occurrence of each element
* is kept. The order of result values is determined by the order they occur
* in the array.
*
* It accepts iteratee which is invoked for each element in array to generate
* the criterion by which uniqueness is computed. The order of result values
* is determined by the order they occur in the array. The iteratee is
* invoked with one argument: value.
*/
export const uniqBy = iterateeFn => array => {
const { length } = array;
const result = [];
const seen = iterateeFn ? [] : result;
let index = -1;
outer:
while (++index < length) {
let value = array[index];
const computed = iterateeFn ? iterateeFn(value) : value;
value = value !== 0 ? value : 0;
if (computed === computed) {
let seenIndex = seen.length;
while (seenIndex--) {
if (seen[seenIndex] === computed) {
continue outer;
}
}
if (iterateeFn) {
seen.push(computed);
}
result.push(value);
}
else if (!seen.includes(computed)) {
if (seen !== result) {
seen.push(computed);
}
result.push(value);
}
}
return result;
};
/**
* Creates an array of grouped elements, the first of which contains
* the first elements of the given arrays, the second of which contains
* the second elements of the given arrays, and so on.
*
* @returns {any[]}
*/
export const zip = (...arrays) => {
if (arrays.length === 0) {
return;
}
const numArrays = arrays.length;
const numValues = arrays[0].length;
const result = [];
for (let valueIndex = 0; valueIndex < numValues; valueIndex++) {
const entry = [];
for (let arrayIndex = 0; arrayIndex < numArrays; arrayIndex++) {
entry.push(arrays[arrayIndex][valueIndex]);
}
result.push(entry);
}
return result;
};
/**
* This method is like "zip" except that it accepts iteratee to
* specify how grouped values should be combined. The iteratee is
* invoked with the elements of each group.
*
* @returns {any[]}
*/
export const zipWith = iterateeFn => (...arrays) => {
return map(values => iterateeFn(...values))(zip(...arrays));
};
+41
View File
@@ -0,0 +1,41 @@
/**
* Creates a function that returns the result of invoking the given
* functions, where each successive invocation is supplied the return
* value of the previous.
*/
export const flow = (...funcs) => (input, ...rest) => {
let output = input;
for (let func of funcs) {
// Recurse into the array of functions
if (Array.isArray(func)) {
output = flow(...func)(output, ...rest);
}
else if (func) {
output = func(output, ...rest);
}
}
return output;
};
/**
* Composes single-argument functions from right to left.
*
* All functions might accept a context in form of additional arguments.
* If the resulting function is called with more than 1 argument, rest of
* the arguments are passed to all functions unchanged.
*
* @param {...Function} funcs The functions to compose
* @returns {Function} A function obtained by composing the argument functions
* from right to left. For example, compose(f, g, h) is identical to doing
* (input, ...rest) => f(g(h(input, ...rest), ...rest), ...rest)
*/
export const compose = (...funcs) => {
if (funcs.length === 0) {
return arg => arg;
}
if (funcs.length === 1) {
return funcs[0];
}
return funcs.reduce((a, b) => (value, ...rest) =>
a(b(value, ...rest), ...rest));
};
+66
View File
@@ -0,0 +1,66 @@
const inception = Date.now();
// Runtime detection
const isNode = process && process.release && process.release.name === 'node';
let isChrome = false;
try {
isChrome = window.navigator.userAgent.toLowerCase().includes('chrome');
}
catch {}
// Timestamping function
const getTimestamp = () => {
const timestamp = String(Date.now() - inception)
.padStart(4, '0')
.padStart(7, ' ');
const seconds = timestamp.substr(0, timestamp.length - 3);
const millis = timestamp.substr(-3);
return `${seconds}.${millis}`;
};
const getPrefix = (() => {
if (isNode) {
// Escape sequences
const ESC = {
dimmed: '\x1b[38;5;240m',
bright: '\x1b[37;1m',
reset: '\x1b[0m',
};
return ns => [
`${ESC.dimmed}${getTimestamp()} ${ESC.bright}${ns}${ESC.reset}`,
];
}
if (isChrome) {
// Styles
const styles = {
dimmed: 'color: #888',
bright: 'font-weight: bold',
};
return ns => [
`%c${getTimestamp()}%c ${ns}`,
styles.dimmed,
styles.bright,
];
}
return ns => [
`${getTimestamp()} ${ns}`,
];
})();
/**
* Creates a logger object.
*/
export const createLogger = ns => ({
log: (...args) => console.log(...getPrefix(ns), ...args),
trace: (...args) => console.trace(...getPrefix(ns), ...args),
debug: (...args) => console.debug(...getPrefix(ns), ...args),
info: (...args) => console.info(...getPrefix(ns), ...args),
warn: (...args) => console.warn(...getPrefix(ns), ...args),
error: (...args) => console.error(...getPrefix(ns), ...args),
});
/**
* Explicitly log with chosen namespace.
*/
export const directLog = (ns, ...args) =>
console.log(...getPrefix(ns), ...args);
+84
View File
@@ -0,0 +1,84 @@
/**
* Limits a number to the range between 'min' and 'max'.
*/
export const clamp = (value, min, max) => {
return value < min ? min : value > max ? max : value;
};
/**
* Limits a number between 0 and 1.
*/
export const clamp01 = value => {
return value < 0 ? 0 : value > 1 ? 1 : value;
};
/**
* Scales a number to fit into the range between min and max.
*/
export const scale = (value, min, max) => {
return (value - min) / (max - min);
};
/**
* Robust number rounding.
*
* Adapted from Locutus, see: http://locutus.io/php/math/round/
*
* @param {number} value
* @param {number} precision
* @return {number}
*/
export const round = (value, precision) => {
if (!value || isNaN(value)) {
return value;
}
// helper variables
let m, f, isHalf, sgn;
// making sure precision is integer
precision |= 0;
m = Math.pow(10, precision);
value *= m;
// sign of the number
sgn = (value > 0) | -(value < 0);
// isHalf = value % 1 === 0.5 * sgn;
isHalf = Math.abs(value % 1) >= 0.4999999999854481;
f = Math.floor(value);
if (isHalf) {
// rounds .5 away from zero
value = f + (sgn > 0);
}
return (isHalf ? value : Math.round(value)) / m;
};
/**
* Returns a string representing a number in fixed point notation.
*/
export const toFixed = (value, fractionDigits = 0) => {
return Number(value).toFixed(Math.max(fractionDigits, 0));
};
/**
* Checks whether a value is within the provided range.
*
* Range is an array of two numbers, for example: [0, 15].
*/
export const inRange = (value, range) => {
return range
&& value >= range[0]
&& value <= range[1];
};
/**
* Walks over the object with ranges, comparing value against every range,
* and returns the key of the first matching range.
*
* Range is an array of two numbers, for example: [0, 15].
*/
export const keyOfMatchingRange = (value, ranges) => {
for (let rangeName of Object.keys(ranges)) {
const range = ranges[rangeName];
if (inRange(value, range)) {
return rangeName;
}
}
};
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"name": "common",
"version": "3.0.0",
"type": "module"
}
+67
View File
@@ -0,0 +1,67 @@
/**
* Helper for conditionally adding/removing classes in React
*
* @param {any[]} classNames
* @return {string}
*/
export const classes = classNames => {
let className = '';
for (let i = 0; i < classNames.length; i++) {
const part = classNames[i];
if (typeof part === 'string') {
className += part + ' ';
}
}
return className;
};
/**
* Normalizes children prop, so that it is always an array of VDom
* elements.
*/
export const normalizeChildren = children => {
if (Array.isArray(children)) {
return children.flat().filter(value => value);
}
if (typeof children === 'object') {
return [children];
}
return [];
};
/**
* Shallowly checks if two objects are different.
* Credit: https://github.com/developit/preact-compat
*/
export const shallowDiffers = (a, b) => {
let i;
for (i in a) {
if (!(i in b)) {
return true;
}
}
for (i in b) {
if (a[i] !== b[i]) {
return true;
}
}
return false;
};
/**
* Default inferno hooks for pure components.
*/
export const pureComponentHooks = {
onComponentShouldUpdate: (lastProps, nextProps) => {
return shallowDiffers(lastProps, nextProps);
},
};
/**
* A helper to determine whether to render an item.
*/
export const isFalsy = value => {
return value === undefined
|| value === null
|| value === false;
};
+65
View File
@@ -0,0 +1,65 @@
import { compose } from './fp';
/**
* Creates a Redux store.
*/
export const createStore = (reducer, enhancer) => {
// Apply a store enhancer (applyMiddleware is one of them).
if (enhancer) {
return enhancer(createStore)(reducer);
}
let currentState;
let listeners = [];
const getState = () => currentState;
const subscribe = listener => {
listeners.push(listener);
};
const dispatch = action => {
currentState = reducer(currentState, action);
listeners.forEach(fn => fn());
};
// This creates the initial store by causing each reducer to be called
// with an undefined state
dispatch({
type: '@@INIT',
});
return {
dispatch,
subscribe,
getState,
};
};
/**
* Creates a store enhancer which applies middleware to all dispatched
* actions.
*/
export const applyMiddleware = (...middlewares) => {
return createStore => (reducer, ...args) => {
const store = createStore(reducer, ...args);
let dispatch = () => {
throw new Error(
'Dispatching while constructing your middleware is not allowed.');
};
const storeApi = {
getState: store.getState,
dispatch: (action, ...args) => dispatch(action, ...args),
};
const chain = middlewares.map(middleware => middleware(storeApi));
dispatch = compose(...chain)(store.dispatch);
return {
...store,
dispatch,
};
};
};
@@ -0,0 +1,70 @@
/**
* @file
* We are using a .cjs extension because:
*
* 1. Webpack CLI only supports CommonJS modules;
* 2. tgui-dev-server supports both, but we still need to signal NodeJS
* to import it as a CommonJS module, hence .cjs extension.
*
* We need to copy-paste the whole "multiline" function because we can't
* synchronously import an ES module from a CommonJS module.
*
* This plugin saves overall about 10KB on the final bundle size, so it's
* sort of worth it.
*/
/**
* Removes excess whitespace and indentation from the string.
*/
const multiline = str => {
const lines = str.split('\n');
// Determine base indentation
let minIndent;
for (let line of lines) {
for (let indent = 0; indent < line.length; indent++) {
const char = line[indent];
if (char !== ' ') {
if (minIndent === undefined || indent < minIndent) {
minIndent = indent;
}
break;
}
}
}
if (!minIndent) {
minIndent = 0;
}
// Remove this base indentation and trim the resulting string
// from both ends.
return lines
.map(line => line.substr(minIndent).trimRight())
.join('\n')
.trim();
};
const StringPlugin = ref => {
return {
visitor: {
TaggedTemplateExpression: path => {
if (path.node.tag.name === 'multiline') {
const { quasi } = path.node;
if (quasi.expressions.length > 0) {
throw new Error('Multiline tag does not support expressions!');
}
if (quasi.quasis.length > 1) {
throw new Error('Quasis is longer than 1');
}
const { value } = quasi.quasis[0];
value.raw = multiline(value.raw);
value.cooked = multiline(value.cooked);
path.replaceWith(quasi);
}
},
},
};
};
module.exports = {
__esModule: true,
default: StringPlugin,
};
+156
View File
@@ -0,0 +1,156 @@
/**
* Removes excess whitespace and indentation from the string.
*/
export const multiline = str => {
if (Array.isArray(str)) {
// Small stub to allow usage as a template tag
return multiline(str.join(''));
}
const lines = str.split('\n');
// Determine base indentation
let minIndent;
for (let line of lines) {
for (let indent = 0; indent < line.length; indent++) {
const char = line[indent];
if (char !== ' ') {
if (minIndent === undefined || indent < minIndent) {
minIndent = indent;
}
break;
}
}
}
if (!minIndent) {
minIndent = 0;
}
// Remove this base indentation and trim the resulting string
// from both ends.
return lines
.map(line => line.substr(minIndent).trimRight())
.join('\n')
.trim();
};
/**
* Creates a glob pattern matcher.
*
* Matches strings with wildcards.
*
* Example: createGlobPattern('*@domain')('user@domain') === true
*/
export const createGlobPattern = pattern => {
const escapeString = str => str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');
const regex = new RegExp('^'
+ pattern.split(/\*+/).map(escapeString).join('.*')
+ '$');
return str => regex.test(str);
};
/**
* Creates a search terms matcher.
*
* Returns true if given string matches the search text.
*
* @template T
* @param {string} searchText
* @param {(obj: T) => string} stringifier
* @returns {(obj: T) => boolean}
*/
export const createSearch = (searchText, stringifier) => {
const preparedSearchText = searchText.toLowerCase().trim();
return obj => {
if (!preparedSearchText) {
return true;
}
const str = stringifier ? stringifier(obj) : obj;
if (!str) {
return false;
}
return str
.toLowerCase()
.includes(preparedSearchText);
};
};
export const capitalize = str => {
// Handle array
if (Array.isArray(str)) {
return str.map(capitalize);
}
// Handle string
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
};
export const toTitleCase = str => {
// Handle array
if (Array.isArray(str)) {
return str.map(toTitleCase);
}
// Pass non-string
if (typeof str !== 'string') {
return str;
}
// Handle string
const WORDS_UPPER = ['Id', 'Tv'];
const WORDS_LOWER = [
'A', 'An', 'And', 'As', 'At', 'But', 'By', 'For', 'For', 'From', 'In',
'Into', 'Near', 'Nor', 'Of', 'On', 'Onto', 'Or', 'The', 'To', 'With',
];
let currentStr = str.replace(/([^\W_]+[^\s-]*) */g, str => {
return str.charAt(0).toUpperCase() + str.substr(1).toLowerCase();
});
for (let word of WORDS_LOWER) {
const regex = new RegExp('\\s' + word + '\\s', 'g');
currentStr = currentStr.replace(regex, str => str.toLowerCase());
}
for (let word of WORDS_UPPER) {
const regex = new RegExp('\\b' + word + '\\b', 'g');
currentStr = currentStr.replace(regex, str => str.toLowerCase());
}
return currentStr;
};
/**
* Decodes HTML entities, and removes unnecessary HTML tags.
*
* @param {String} str Encoded HTML string
* @return {String} Decoded HTML string
*/
export const decodeHtmlEntities = str => {
if (!str) {
return str;
}
const translate_re = /&(nbsp|amp|quot|lt|gt|apos);/g;
const translate = {
nbsp: ' ',
amp: '&',
quot: '"',
lt: '<',
gt: '>',
apos: '\'',
};
return str
// Newline tags
.replace(/<br>/gi, '\n')
.replace(/<\/?[a-z0-9-_]+[^>]*>/gi, '')
// Basic entities
.replace(translate_re, (match, entity) => translate[entity])
// Decimal entities
.replace(/&#?([0-9]+);/gi, (match, numStr) => {
const num = parseInt(numStr, 10);
return String.fromCharCode(num);
})
// Hex entities
.replace(/&#x?([0-9a-f]+);/gi, (match, numStr) => {
const num = parseInt(numStr, 16);
return String.fromCharCode(num);
});
};
/**
* Converts an object into a query string,
*/
export const buildQueryString = obj => Object.keys(obj)
.map(key => encodeURIComponent(key)
+ '=' + encodeURIComponent(obj[key]))
.join('&');
+23
View File
@@ -0,0 +1,23 @@
/**
* Returns a function, that, as long as it continues to be invoked, will
* not be triggered. The function will be called after it stops being
* called for N milliseconds. If `immediate` is passed, trigger the
* function on the leading edge, instead of the trailing.
*/
export const debounce = (fn, time, immediate = false) => {
let timeout;
return (...args) => {
const later = () => {
timeout = null;
if (!immediate) {
fn(...args);
}
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, time);
if (callNow) {
fn(...args);
}
};
};
+48
View File
@@ -0,0 +1,48 @@
import { map, reduce, zipWith } from './collections';
/**
* Creates a vector, with as many dimensions are there are arguments.
*/
export const vecCreate = (...components) => {
if (Array.isArray(components[0])) {
return [...components[0]];
}
return components;
};
const ADD = (a, b) => a + b;
const SUB = (a, b) => a - b;
const MUL = (a, b) => a * b;
const DIV = (a, b) => a / b;
export const vecAdd = (...vecs) => {
return reduce((a, b) => zipWith(ADD)(a, b))(vecs);
};
export const vecSubtract = (...vecs) => {
return reduce((a, b) => zipWith(SUB)(a, b))(vecs);
};
export const vecMultiply = (...vecs) => {
return reduce((a, b) => zipWith(MUL)(a, b))(vecs);
};
export const vecDivide = (...vecs) => {
return reduce((a, b) => zipWith(DIV)(a, b))(vecs);
};
export const vecScale = (vec, n) => {
return map(x => x * n)(vec);
};
export const vecInverse = vec => {
return map(x => -x)(vec);
};
export const vecLength = vec => {
return Math.sqrt(reduce(ADD)(zipWith(MUL)(vec, vec)));
};
export const vecNormalize = vec => {
return vecDivide(vec, vecLength(vec));
};
+22
View File
@@ -0,0 +1,22 @@
import { setupWebpack, getWebpackConfig } from './webpack.js';
import { reloadByondCache } from './reloader.js';
const noHot = process.argv.includes('--no-hot');
const reloadOnce = process.argv.includes('--reload');
const setupServer = async () => {
const config = await getWebpackConfig({
mode: 'development',
hot: !noHot,
});
// Reload cache once
if (reloadOnce) {
const bundleDir = config.output.path;
await reloadByondCache(bundleDir);
return;
}
// Run a development server
await setupWebpack(config);
};
setupServer();
@@ -0,0 +1,161 @@
let socket;
const queue = [];
const subscribers = [];
const ensureConnection = () => {
if (process.env.NODE_ENV !== 'production') {
if (!window.WebSocket) {
return;
}
if (!socket || socket.readyState === WebSocket.CLOSED) {
const DEV_SERVER_IP = process.env.DEV_SERVER_IP || '127.0.0.1';
socket = new WebSocket(`ws://${DEV_SERVER_IP}:3000`);
socket.onopen = () => {
// Empty the message queue
while (queue.length !== 0) {
const msg = queue.shift();
socket.send(msg);
}
};
socket.onmessage = event => {
const msg = JSON.parse(event.data);
for (let subscriber of subscribers) {
subscriber(msg);
}
};
}
}
};
if (process.env.NODE_ENV !== 'production') {
window.onunload = () => socket && socket.close();
}
const subscribe = fn => subscribers.push(fn);
/**
* A json serializer which handles circular references and other junk.
*/
const serializeObject = obj => {
let refs = [];
const primitiveReviver = value => {
if (typeof value === 'number' && !Number.isFinite(value)) {
return {
__number__: String(value),
};
}
if (typeof value === 'undefined') {
return {
__undefined__: true,
};
}
return value;
};
const objectReviver = (key, value) => {
if (typeof value === 'object') {
if (value === null) {
return value;
}
// Circular reference
if (refs.includes(value)) {
return '[circular ref]';
}
refs.push(value);
// Error object
if (value instanceof Error) {
return {
__error__: true,
string: String(value),
stack: value.stack,
};
}
// Array
if (Array.isArray(value)) {
return value.map(primitiveReviver);
}
return value;
}
return primitiveReviver(value);
};
const json = JSON.stringify(obj, objectReviver);
refs = null;
return json;
};
const sendRawMessage = msg => {
if (process.env.NODE_ENV !== 'production') {
const json = serializeObject(msg);
// Send message using WebSocket
if (window.WebSocket) {
ensureConnection();
if (socket.readyState === WebSocket.OPEN) {
socket.send(json);
}
else {
// Keep only 10 latest messages in the queue
if (queue.length > 10) {
queue.shift();
}
queue.push(json);
}
}
// Send message using plain HTTP request.
else {
const DEV_SERVER_IP = process.env.DEV_SERVER_IP || '127.0.0.1';
const req = new XMLHttpRequest();
req.open('POST', `http://${DEV_SERVER_IP}:3001`);
req.timeout = 500;
req.send(json);
}
}
};
export const sendLogEntry = (level, ns, ...args) => {
if (process.env.NODE_ENV !== 'production') {
try {
sendRawMessage({
type: 'log',
payload: {
level,
ns: ns || 'client',
args,
},
});
}
catch (err) {}
}
};
export const setupHotReloading = () => {
if (process.env.NODE_ENV !== 'production'
&& process.env.WEBPACK_HMR_ENABLED
&& window.WebSocket) {
if (module.hot) {
ensureConnection();
sendLogEntry(0, null, 'setting up hot reloading');
subscribe(msg => {
const { type } = msg;
sendLogEntry(0, null, 'received', type);
if (type === 'hotUpdate') {
const status = module.hot.status();
if (status !== 'idle') {
sendLogEntry(0, null, 'hot reload status:', status);
return;
}
module.hot
.check({
ignoreUnaccepted: true,
ignoreDeclined: true,
ignoreErrored: true,
})
.then(modules => {
sendLogEntry(0, null, 'outdated modules', modules);
})
.catch(err => {
sendLogEntry(0, null, 'reload error', err);
});
}
});
}
}
};
@@ -0,0 +1,76 @@
import { createLogger } from 'common/logging.js';
import fs from 'fs';
import { basename } from 'path';
import SourceMap from 'source-map';
import StackTraceParser from 'stacktrace-parser';
import { resolveGlob } from '../util.js';
const logger = createLogger('retrace');
const { SourceMapConsumer } = SourceMap;
const sourceMaps = [];
export const loadSourceMaps = async bundleDir => {
// Destroy and garbage collect consumers
while (sourceMaps.length !== 0) {
const { consumer } = sourceMaps.shift();
consumer.destroy();
}
// Load new sourcemaps
const paths = await resolveGlob(bundleDir, '*.map');
for (let path of paths) {
try {
const file = basename(path).replace('.map', '');
const consumer = await new SourceMapConsumer(
JSON.parse(fs.readFileSync(path, 'utf8')));
sourceMaps.push({ file, consumer });
}
catch (err) {
logger.error(err);
}
}
logger.log(`loaded ${sourceMaps.length} source maps`);
};
export const retrace = stack => {
const header = stack.split(/\n\s.*at/)[0];
const mappedStack = StackTraceParser.parse(stack)
.map(frame => {
if (!frame.file) {
return frame;
}
// Find the correct source map
const sourceMap = sourceMaps.find(sourceMap => {
return frame.file.includes(sourceMap.file);
});
if (!sourceMap) {
return frame;
}
// Map the frame
const { consumer } = sourceMap;
const mappedFrame = consumer.originalPositionFor({
source: basename(frame.file),
line: frame.lineNumber,
column: frame.column,
});
return {
...frame,
file: mappedFrame.source,
lineNumber: mappedFrame.line,
column: mappedFrame.column,
};
})
.map(frame => {
// Stringify the frame
const { file, methodName, lineNumber } = frame;
if (!file) {
return ` at ${methodName}`;
}
const compactPath = file
.replace(/^webpack:\/\/\/?/, './')
.replace(/.*node_modules\//, '');
return ` at ${methodName} (${compactPath}:${lineNumber})`;
})
.join('\n');
return header + '\n' + mappedStack;
};
@@ -0,0 +1,127 @@
import { createLogger, directLog } from 'common/logging.js';
import http from 'http';
import { inspect } from 'util';
import WebSocket from 'ws';
import { retrace, loadSourceMaps } from './retrace.js';
const logger = createLogger('link');
const DEBUG = process.argv.includes('--debug');
export { loadSourceMaps };
export const setupLink = () => {
logger.log('setting up');
const wss = setupWebSocketLink();
setupHttpLink();
return {
wss,
};
};
export const broadcastMessage = (link, msg) => {
const { wss } = link;
const clients = [...wss.clients];
logger.log(`broadcasting ${msg.type} to ${clients.length} clients`);
for (let client of clients) {
const json = JSON.stringify(msg);
client.send(json);
}
};
const deserializeObject = str => {
return JSON.parse(str, (key, value) => {
if (typeof value === 'object' && value !== null) {
if (value.__error__) {
if (!value.stack) {
return value.string;
}
return retrace(value.stack);
}
if (value.__number__) {
return parseFloat(value.__number__);
}
if (value.__undefined__) {
// NOTE: You should not rely on deserialized object's undefined,
// this is purely for inspection purposes.
return {
[inspect.custom]: () => undefined,
};
}
return value;
}
return value;
});
};
const handleLinkMessage = msg => {
const { type, payload } = msg;
if (type === 'log') {
const { level, ns, args } = payload;
// Skip debug messages
if (level <= 0 && !DEBUG) {
return;
}
directLog(ns, ...args.map(arg => {
if (typeof arg === 'object') {
return inspect(arg, {
depth: Infinity,
colors: true,
compact: 8,
});
}
return arg;
}));
return;
}
logger.log('unhandled message', msg);
};
// WebSocket-based client link
const setupWebSocketLink = () => {
const port = 3000;
const wss = new WebSocket.Server({ port });
wss.on('connection', ws => {
logger.log('client connected');
ws.on('message', json => {
const msg = deserializeObject(json);
handleLinkMessage(msg);
});
ws.on('close', () => {
logger.log('client disconnected');
});
});
logger.log(`listening on port ${port} (WebSocket)`);
return wss;
};
// One way HTTP-based client link for IE8
const setupHttpLink = () => {
const port = 3001;
const server = http.createServer((req, res) => {
if (req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
const msg = deserializeObject(body);
handleLinkMessage(msg);
res.end();
});
return;
}
res.write('Hello');
res.end();
});
server.listen(port);
logger.log(`listening on port ${port} (HTTP)`);
};
@@ -0,0 +1,12 @@
{
"private": true,
"name": "tgui-dev-server",
"version": "3.0.0",
"type": "module",
"dependencies": {
"glob": "^7.1.4",
"source-map": "^0.7.3",
"stacktrace-parser": "^0.1.7",
"ws": "^7.1.2"
}
}
+87
View File
@@ -0,0 +1,87 @@
import { createLogger } from 'common/logging.js';
import fs from 'fs';
import os from 'os';
import { basename } from 'path';
import { promisify } from 'util';
import { resolveGlob, resolvePath } from './util.js';
import { regQuery } from './winreg.js';
const logger = createLogger('reloader');
const HOME = os.homedir();
const SEARCH_LOCATIONS = [
// Custom location
process.env.BYOND_CACHE,
// Windows
`${HOME}/*/BYOND/cache`,
// Wine
`${HOME}/.wine/drive_c/users/*/*/BYOND/cache`,
// Lutris
`${HOME}/Games/byond/drive_c/users/*/*/BYOND/cache`,
// WSL
`/mnt/c/Users/*/*/BYOND/cache`,
];
let cacheRoot;
export const findCacheRoot = async () => {
if (cacheRoot) {
return cacheRoot;
}
logger.log('looking for byond cache');
// Find BYOND cache folders
for (let pattern of SEARCH_LOCATIONS) {
if (!pattern) {
continue;
}
const paths = await resolveGlob(pattern);
if (paths.length > 0) {
cacheRoot = paths[0];
logger.log(`found cache at '${cacheRoot}'`);
return cacheRoot;
}
}
// Query the Windows Registry
if (process.platform === 'win32') {
logger.log('querying windows registry');
let userpath = await regQuery(
'HKCU\\Software\\Dantom\\BYOND',
'userpath');
if (userpath) {
cacheRoot = userpath
.replace(/\\$/, '')
.replace(/\\/g, '/')
+ '/cache';
logger.log(`found cache at '${cacheRoot}'`);
return cacheRoot;
}
}
logger.log('found no cache directories');
};
export const reloadByondCache = async bundleDir => {
const cacheRoot = await findCacheRoot();
if (!cacheRoot) {
return;
}
// Find tmp folders in cache
const cacheDirs = await resolveGlob(cacheRoot, './tmp*');
if (cacheDirs.length === 0) {
logger.log('found no tmp folder in cache');
return;
}
const assets = await resolveGlob(bundleDir, './*.+(bundle|hot-update).*');
for (let cacheDir of cacheDirs) {
// Clear garbage
const garbage = await resolveGlob(cacheDir, './*.+(bundle|hot-update).*');
for (let file of garbage) {
await promisify(fs.unlink)(file);
}
// Copy assets
for (let asset of assets) {
const destination = resolvePath(cacheDir, basename(asset));
await promisify(fs.copyFile)(asset, destination);
}
logger.log(`copied ${assets.length} files to '${cacheDir}'`);
}
};
+26
View File
@@ -0,0 +1,26 @@
import glob from 'glob';
import { resolve as resolvePath } from 'path';
import fs from 'fs';
import { promisify } from 'util';
export { resolvePath };
/**
* Combines path.resolve with glob patterns.
*/
export const resolveGlob = async (...sections) => {
const unsafePaths = await promisify(glob)(
resolvePath(...sections), {
strict: false,
silent: true,
});
const safePaths = [];
for (let path of unsafePaths) {
try {
await promisify(fs.stat)(path);
safePaths.push(path);
}
catch {}
}
return safePaths;
};
+54
View File
@@ -0,0 +1,54 @@
import { createLogger } from 'common/logging.js';
import fs from 'fs';
import { createRequire } from 'module';
import { promisify } from 'util';
import webpack from 'webpack';
import { broadcastMessage, loadSourceMaps, setupLink } from './link/server.js';
import { reloadByondCache } from './reloader.js';
import { resolveGlob } from './util.js';
const logger = createLogger('webpack');
export const getWebpackConfig = async options => {
const require = createRequire(import.meta.url);
const createConfig = await require('../tgui/webpack.config.js');
return createConfig({}, options);
};
export const setupWebpack = async config => {
logger.log('setting up');
const bundleDir = config.output.path;
// Setup link
const link = setupLink();
// Instantiate the compiler
const compiler = webpack(config);
// Clear garbage before compiling
compiler.hooks.watchRun.tapPromise('tgui-dev-server', async () => {
const files = await resolveGlob(bundleDir, './*.hot-update.*');
logger.log(`clearing garbage (${files.length} files)`);
for (let file of files) {
await promisify(fs.unlink)(file);
}
logger.log('compiling');
});
// Start reloading when it's finished
compiler.hooks.done.tap('tgui-dev-server', async stats => {
// Load source maps
await loadSourceMaps(bundleDir);
// Reload cache
await reloadByondCache(bundleDir);
// Notify all clients that update has happened
broadcastMessage(link, {
type: 'hotUpdate',
});
});
// Start watching
logger.log('watching for changes');
compiler.watch({}, (err, stats) => {
if (err) {
logger.error('compilation error', err);
return;
}
logger.log(stats.toString(config.devServer.stats));
});
};
+43
View File
@@ -0,0 +1,43 @@
/**
* @file
* Tools for dealing with Windows Registry bullshit.
*/
import { exec } from 'child_process';
import { createLogger } from 'common/logging.js';
import { promisify } from 'util';
const logger = createLogger('winreg');
export const regQuery = async (path, key) => {
if (process.platform !== 'win32') {
return null;
}
try {
const command = `reg query "${path}" /v ${key}`;
const { stdout } = await promisify(exec)(command);
const keyPattern = ` ${key} `;
const indexOfKey = stdout.indexOf(keyPattern);
if (indexOfKey === -1) {
logger.error('could not find the registry key');
return null;
}
const indexOfEol = stdout.indexOf('\r\n', indexOfKey);
if (indexOfEol === -1) {
logger.error('could not find the end of the line');
return null;
}
const indexOfValue = stdout.indexOf(
' ',
indexOfKey + keyPattern.length);
if (indexOfValue === -1) {
logger.error('could not find the start of the key value');
return null;
}
const value = stdout.substring(indexOfValue + 4, indexOfEol);
return value;
}
catch (err) {
logger.error(err);
return null;
}
};
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg" version="1.0" viewBox="0 0 425 200" opacity=".33">
<path d="m 178.00399,0.03869 -71.20393,0 a 6.7613422,6.0255495 0 0 0 -6.76134,6.02555 l 0,187.87147 a 6.7613422,6.0255495 0 0 0 6.76134,6.02554 l 53.1072,0 a 6.7613422,6.0255495 0 0 0 6.76135,-6.02554 l 0,-101.544018 72.21628,104.699398 a 6.7613422,6.0255495 0 0 0 5.76015,2.87016 l 73.55487,0 a 6.7613422,6.0255495 0 0 0 6.76135,-6.02554 l 0,-187.87147 a 6.7613422,6.0255495 0 0 0 -6.76135,-6.02555 l -54.71644,0 a 6.7613422,6.0255495 0 0 0 -6.76133,6.02555 l 0,102.61935 L 183.76413,2.90886 a 6.7613422,6.0255495 0 0 0 -5.76014,-2.87017 z" />
<path d="M 4.8446333,22.10875 A 13.412039,12.501842 0 0 1 13.477588,0.03924 l 66.118315,0 a 5.3648158,5.000737 0 0 1 5.364823,5.00073 l 0,79.87931 z" />
<path d="m 420.15535,177.89119 a 13.412038,12.501842 0 0 1 -8.63295,22.06951 l -66.11832,0 a 5.3648152,5.000737 0 0 1 -5.36482,-5.00074 l 0,-79.87931 z" />
</svg>
<!-- This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License. -->
<!-- http://creativecommons.org/licenses/by-sa/4.0/ -->

After

Width:  |  Height:  |  Size: 1.1 KiB

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg" version="1.0" viewBox="0 0 200 289.742" opacity=".33">
<path d="m 93.537677,0 c -18.113125,0 -34.220133,3.11164 -48.323484,9.33437 -13.965092,6.22167 -24.612442,15.07114 -31.940651,26.5471 -7.1899398,11.33789 -10.3012266,24.74911 -10.3012266,40.23478 0,10.64662 2.7250026,20.46465 8.1751116,29.45258 5.615277,8.98686 14.038277,17.35204 25.268821,25.09436 11.230544,7.60531 26.507421,15.41835 45.830514,23.43782 19.983748,8.29557 34.848848,15.55471 44.592998,21.77638 9.74414,6.22273 16.7617,12.8585 21.05572,19.90951 4.29404,7.05208 6.44193,15.76408 6.44193,26.13459 0,16.17702 -5.20196,28.48222 -15.60673,36.91682 -10.2396,8.4347 -25.02203,12.6523 -44.345169,12.6523 -14.038171,0 -25.515247,-1.6594 -34.433618,-4.9777 -8.91837,-3.4566 -16.185572,-8.7113 -21.800839,-15.7633 -5.615277,-7.0521 -10.074795,-16.66088 -13.377899,-28.82812 l -24.7731626293945,0 0,56.82632 C 33.856769,286.07601 63.74904,289.74201 89.678383,289.74201 c 16.020027,0 30.719787,-1.3827 44.097337,-4.1479 13.54272,-2.9043 25.1041,-7.4676 34.68309,-13.6893 9.74413,-6.3597 17.34042,-14.5195 22.79052,-24.4748 5.4501,-10.09332 8.17511,-22.39959 8.17511,-36.91682 0,-12.99764 -3.3021,-24.33539 -9.90829,-34.0146 -6.44105,-9.81725 -15.52545,-18.52707 -27.25146,-26.13133 -11.56085,-7.60427 -27.91083,-15.83142 -49.05066,-24.68022 -17.50644,-7.19012 -30.719668,-13.68948 -39.638038,-19.49701 -8.918371,-5.80752 -18.607474,-12.43409 -24.096524,-18.87417 -5.426043,-6.36616 -9.658826,-15.07003 -9.658826,-24.88729 0,-9.26401 2.075414,-17.21345 6.223454,-23.85033 11.098298,-14.39748 41.286638,-1.79507 45.075609,24.34762 4.839392,6.77491 8.84935,16.24729 12.029515,28.4156 l 20.53234,0 0,-55.99967 c -4.47825,-5.92448 -9.95488,-10.63222 -15.90837,-14.37411 1.64055,0.47905 3.19039,1.02376 4.63865,1.64024 6.49861,2.62607 12.16793,7.32747 17.0073,14.10345 4.83939,6.77491 8.84935,16.24567 12.02952,28.41397 0,0 8.48128,-0.12894 8.48978,-0.002 0.41776,6.41494 -1.75339,9.45286 -4.12342,12.56104 -2.4174,3.16978 -5.14486,6.78973 -4.00278,13.0029 1.50786,8.20318 10.18354,10.59642 14.62194,9.31154 -3.31842,-0.49911 -5.31855,-1.74948 -5.31855,-1.74948 0,0 1.87646,0.99868 5.65117,-1.35981 -3.27695,0.95571 -10.70529,-0.79738 -11.80125,-6.76313 -0.95752,-5.20861 0.94654,-7.29514 3.40113,-10.51482 2.45462,-3.21968 5.28426,-6.95831 4.6843,-14.48824 l 0.003,0.002 8.92676,0 0,-55.99967 c -15.07125,-3.87168 -27.65314,-6.36042 -37.74671,-7.46586 -9.95531,-1.10755 -20.18823,-1.65981 -30.696613,-1.65981 z m 70.321603,17.30893 0.23805,40.3049 c 1.31808,1.22666 2.43965,2.27815 3.34081,3.10602 4.83939,6.77491 8.84934,16.24566 12.02951,28.41397 l 20.53234,0 0,-55.99967 c -6.67731,-4.59381 -19.83643,-10.47309 -36.14071,-15.82522 z m -28.12049,5.60551 8.56479,17.71655 c -11.97037,-6.46697 -13.84678,-9.71726 -8.56479,-17.71655 z m 22.79705,0 c 2.7715,7.99929 1.78741,11.24958 -4.49354,17.71655 l 4.49354,-17.71655 z m 15.22195,24.00848 8.56479,17.71655 c -11.97038,-6.46697 -13.84679,-9.71726 -8.56479,-17.71655 z m 22.79704,0 c 2.7715,7.99929 1.78741,11.24958 -4.49354,17.71655 l 4.49354,-17.71655 z m -99.11384,2.20764 8.56479,17.71655 c -11.970382,-6.46697 -13.846782,-9.71726 -8.56479,-17.71655 z m 22.79542,0 c 2.7715,7.99929 1.78741,11.24958 -4.49354,17.71655 l 4.49354,-17.71655 z" />
</svg>
<!-- This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License. -->
<!-- http://creativecommons.org/licenses/by-sa/4.0/ -->

After

Width:  |  Height:  |  Size: 3.4 KiB

+184
View File
@@ -0,0 +1,184 @@
/**
* This file provides a clear separation layer between backend updates
* and what state our React app sees.
*
* Sometimes backend can response without a "data" field, but our final
* state will still contain previous "data" because we are merging
* the response with already existing state.
*/
import { UI_DISABLED, UI_INTERACTIVE } from './constants';
import { callByond } from './byond';
export const backendUpdate = state => ({
type: 'backend/update',
payload: state,
});
export const backendSetSharedState = (key, nextState) => ({
type: 'backend/setSharedState',
payload: { key, nextState },
});
export const backendReducer = (state, action) => {
const { type, payload } = action;
if (type === 'backend/update') {
// Merge config
const config = {
...state.config,
...payload.config,
};
// Merge data
const data = {
...state.data,
...payload.static_data,
...payload.data,
};
// Merge shared states
const shared = { ...state.shared };
if (payload.shared) {
for (let key of Object.keys(payload.shared)) {
const value = payload.shared[key];
if (value === '') {
shared[key] = undefined;
}
else {
shared[key] = JSON.parse(value);
}
}
}
// Calculate our own fields
const visible = config.status !== UI_DISABLED;
const interactive = config.status === UI_INTERACTIVE;
// Return new state
return {
...state,
config,
data,
shared,
visible,
interactive,
};
}
if (type === 'backend/setSharedState') {
const { key, nextState } = payload;
return {
...state,
shared: {
...state.shared,
[key]: nextState,
},
};
}
return state;
};
/**
* @typedef BackendState
* @type {{
* config: {
* title: string,
* status: number,
* screen: string,
* style: string,
* interface: string,
* fancy: number,
* observer: number,
* window: string,
* ref: string,
* },
* data: any,
* visible: boolean,
* interactive: boolean,
* }}
*/
/**
* A React hook (sort of) for getting tgui state and related functions.
*
* This is supposed to be replaced with a real React Hook, which can only
* be used in functional components.
*
* @return {BackendState & {
* act: (action: string, params?: object) => void,
* }}
*/
export const useBackend = context => {
const { store } = context;
const state = store.getState();
const ref = state.config.ref;
const act = (action, params = {}) => {
callByond('', {
src: ref,
action,
...params,
});
};
return { ...state, act };
};
/**
* Allocates state on Redux store without sharing it with other clients.
*
* Use it when you want to have a stateful variable in your component
* that persists between renders, but will be forgotten after you close
* the UI.
*
* It is a lot more performant than `setSharedState`.
*
* @param {any} context React context.
* @param {string} key Key which uniquely identifies this state in Redux store.
* @param {any} initialState Initializes your global variable with this value.
*/
export const useLocalState = (context, key, initialState) => {
const { store } = context;
const state = store.getState();
const sharedStates = state.shared ?? {};
const sharedState = (key in sharedStates)
? sharedStates[key]
: initialState;
return [
sharedState,
nextState => {
store.dispatch(backendSetSharedState(key, nextState));
},
];
};
/**
* Allocates state on Redux store, and **shares** it with other clients
* in the game.
*
* Use it when you want to have a stateful variable in your component
* that persists not only between renders, but also gets pushed to other
* clients that observe this UI.
*
* This makes creation of observable s
*
* @param {any} context React context.
* @param {string} key Key which uniquely identifies this state in Redux store.
* @param {any} initialState Initializes your global variable with this value.
*/
export const useSharedState = (context, key, initialState) => {
const { store } = context;
const state = store.getState();
const ref = state.config.ref;
const sharedStates = state.shared ?? {};
const sharedState = (key in sharedStates)
? sharedStates[key]
: initialState;
return [
sharedState,
nextState => {
callByond('', {
src: ref,
action: 'tgui:setSharedState',
key,
value: JSON.stringify(nextState) || '',
});
},
];
};
+88
View File
@@ -0,0 +1,88 @@
// Reference a global Byond object
const { Byond } = window;
/**
* Version of Trident engine used in Internet Explorer.
* An integer number or `null` if this is not a trident engine.
*
* - IE 8 - Trident 4.0
* - IE 11 - Trident 7.0
*/
const tridentVersion = (() => {
const groups = navigator.userAgent.match(/Trident\/(\d+).+?;/i);
if (!groups) {
return null;
}
const majorVersion = groups[1];
if (!majorVersion) {
return null;
}
return parseInt(majorVersion, 10);
})();
/**
* True if browser is an Internet Explorer 8 or lower.
*
* (Actually, no, it also includes IE9 and IE10).
*/
export const IS_IE8 = tridentVersion !== null
&& tridentVersion <= 6;
/**
* Makes a BYOND call.
*
* If path is empty, this will trigger a Topic call.
* You can reference a specific object by setting the "src" parameter.
*
* See: https://secure.byond.com/docs/ref/skinparams.html
*/
export const callByond = (path, params = {}) => {
Byond.call(path, params);
};
/**
* A high-level abstraction of BYOND calls. Makes a BYOND call and returns
* a promise, which (if endpoint has a callback parameter) resolves
* with the return value of that call.
*/
export const callByondAsync = (path, params = {}) => {
// Create a callback array if it doesn't exist yet
window.__callbacks__ = window.__callbacks__ || [];
// Create a Promise and push its resolve function into callback array
const callbackIndex = window.__callbacks__.length;
const promise = new Promise(resolve => {
// TODO: Fix a potential memory leak
window.__callbacks__.push(resolve);
});
// Call BYOND client
Byond.call(path, {
...params,
callback: `__callbacks__[${callbackIndex}]`,
});
return promise;
};
/**
* Runs a BYOND skin command
*
* See: https://secure.byond.com/docs/ref/skinparams.html
*/
export const runCommand = command => callByond('winset', { command });
/**
* Calls 'winget' on a BYOND skin element, retrieving value by the 'key'.
*/
export const winget = async (id, key) => {
const obj = await callByondAsync('winget', {
id,
property: key,
});
return obj[key];
};
/**
* Calls 'winset' on a BYOND skin element, setting 'key' to 'value'.
*/
export const winset = (id, key, value) => callByond('winset', {
[`${id}.${key}`]: value,
});
@@ -0,0 +1,77 @@
import { clamp, toFixed } from 'common/math';
import { Component } from 'inferno';
const FPS = 20;
const Q = 0.5;
const isSafeNumber = value => {
return typeof value === 'number'
&& Number.isFinite(value)
&& !Number.isNaN(value);
};
export class AnimatedNumber extends Component {
constructor(props) {
super(props);
this.timer = null;
this.state = {
value: 0,
};
// Use provided initial state
if (isSafeNumber(props.initial)) {
this.state.value = props.initial;
}
// Set initial state with value provided in props
else if (isSafeNumber(props.value)) {
this.state.value = Number(props.value);
}
}
tick() {
const { props, state } = this;
const currentValue = Number(state.value);
const targetValue = Number(props.value);
// Avoid poisoning our state with infinities and NaN
if (!isSafeNumber(targetValue)) {
return;
}
// Smooth the value using an exponential moving average
const value = currentValue * Q + targetValue * (1 - Q);
this.setState({ value });
}
componentDidMount() {
this.timer = setInterval(() => this.tick(), 1000 / FPS);
}
componentWillUnmount() {
clearTimeout(this.timer);
}
render() {
const { props, state } = this;
const { format, children } = props;
const currentValue = state.value;
const targetValue = props.value;
// Directly display values which can't be animated
if (!isSafeNumber(targetValue)) {
return targetValue || null;
}
let formattedValue = currentValue;
// Use custom formatter
if (format) {
formattedValue = format(currentValue);
}
// Fix our animated precision at target value's precision.
else {
const fraction = String(targetValue).split('.')[1];
const precision = fraction ? fraction.length : 0;
formattedValue = toFixed(currentValue, clamp(precision, 0, 8));
}
// Use a custom render function
if (typeof children === 'function') {
return children(formattedValue, currentValue);
}
return formattedValue;
}
}
@@ -0,0 +1,14 @@
import { classes } from 'common/react';
import { Box } from './Box';
export const BlockQuote = props => {
const { className, ...rest } = props;
return (
<Box
className={classes([
'BlockQuote',
className,
])}
{...rest} />
);
};
+209
View File
@@ -0,0 +1,209 @@
import { classes, isFalsy, pureComponentHooks } from 'common/react';
import { createVNode } from 'inferno';
import { ChildFlags, VNodeFlags } from 'inferno-vnode-flags';
import { CSS_COLORS } from '../constants';
const UNIT_PX = 12;
/**
* Coverts our rem-like spacing unit into a CSS unit.
*/
export const unit = value => {
if (typeof value === 'string') {
return value;
}
if (typeof value === 'number') {
return (value * UNIT_PX) + 'px';
}
};
/**
* Same as `unit`, but half the size for integers numbers.
*/
export const halfUnit = value => {
if (typeof value === 'string') {
return value;
}
if (typeof value === 'number') {
return (value * UNIT_PX * 0.5) + 'px';
}
};
const isColorCode = str => !isColorClass(str);
const isColorClass = str => typeof str === 'string'
&& CSS_COLORS.includes(str);
const mapRawPropTo = attrName => (style, value) => {
if (!isFalsy(value)) {
style[attrName] = value;
}
};
const mapUnitPropTo = (attrName, unit) => (style, value) => {
if (!isFalsy(value)) {
style[attrName] = unit(value);
}
};
const mapBooleanPropTo = (attrName, attrValue) => (style, value) => {
if (!isFalsy(value)) {
style[attrName] = attrValue;
}
};
const mapDirectionalUnitPropTo = (attrName, unit, dirs) => (style, value) => {
if (!isFalsy(value)) {
for (let i = 0; i < dirs.length; i++) {
style[attrName + '-' + dirs[i]] = unit(value);
}
}
};
const mapColorPropTo = attrName => (style, value) => {
if (isColorCode(value)) {
style[attrName] = value;
}
};
const styleMapperByPropName = {
// Direct mapping
position: mapRawPropTo('position'),
overflow: mapRawPropTo('overflow'),
overflowX: mapRawPropTo('overflow-x'),
overflowY: mapRawPropTo('overflow-y'),
top: mapUnitPropTo('top', unit),
bottom: mapUnitPropTo('bottom', unit),
left: mapUnitPropTo('left', unit),
right: mapUnitPropTo('right', unit),
width: mapUnitPropTo('width', unit),
minWidth: mapUnitPropTo('min-width', unit),
maxWidth: mapUnitPropTo('max-width', unit),
height: mapUnitPropTo('height', unit),
minHeight: mapUnitPropTo('min-height', unit),
maxHeight: mapUnitPropTo('max-height', unit),
fontSize: mapUnitPropTo('font-size', unit),
fontFamily: mapRawPropTo('font-family'),
lineHeight: mapRawPropTo('line-height'),
opacity: mapRawPropTo('opacity'),
textAlign: mapRawPropTo('text-align'),
verticalAlign: mapRawPropTo('vertical-align'),
// Boolean props
inline: mapBooleanPropTo('display', 'inline-block'),
bold: mapBooleanPropTo('font-weight', 'bold'),
italic: mapBooleanPropTo('font-style', 'italic'),
nowrap: mapBooleanPropTo('white-space', 'nowrap'),
// Margins
m: mapDirectionalUnitPropTo('margin', halfUnit, [
'top', 'bottom', 'left', 'right',
]),
mx: mapDirectionalUnitPropTo('margin', halfUnit, [
'left', 'right',
]),
my: mapDirectionalUnitPropTo('margin', halfUnit, [
'top', 'bottom',
]),
mt: mapUnitPropTo('margin-top', halfUnit),
mb: mapUnitPropTo('margin-bottom', halfUnit),
ml: mapUnitPropTo('margin-left', halfUnit),
mr: mapUnitPropTo('margin-right', halfUnit),
// Margins
p: mapDirectionalUnitPropTo('padding', halfUnit, [
'top', 'bottom', 'left', 'right',
]),
px: mapDirectionalUnitPropTo('padding', halfUnit, [
'left', 'right',
]),
py: mapDirectionalUnitPropTo('padding', halfUnit, [
'top', 'bottom',
]),
pt: mapUnitPropTo('padding-top', halfUnit),
pb: mapUnitPropTo('padding-bottom', halfUnit),
pl: mapUnitPropTo('padding-left', halfUnit),
pr: mapUnitPropTo('padding-right', halfUnit),
// Color props
color: mapColorPropTo('color'),
textColor: mapColorPropTo('color'),
backgroundColor: mapColorPropTo('background-color'),
// Utility props
fillPositionedParent: (style, value) => {
if (value) {
style['position'] = 'absolute';
style['top'] = 0;
style['bottom'] = 0;
style['left'] = 0;
style['right'] = 0;
}
},
};
export const computeBoxProps = props => {
const computedProps = {};
const computedStyles = {};
// Compute props
for (let propName of Object.keys(props)) {
if (propName === 'style') {
continue;
}
const propValue = props[propName];
const mapPropToStyle = styleMapperByPropName[propName];
if (mapPropToStyle) {
mapPropToStyle(computedStyles, propValue);
}
else {
computedProps[propName] = propValue;
}
}
// Concatenate styles
let style = '';
for (let attrName of Object.keys(computedStyles)) {
const attrValue = computedStyles[attrName];
style += attrName + ':' + attrValue + ';';
}
if (props.style) {
for (let attrName of Object.keys(props.style)) {
const attrValue = props.style[attrName];
style += attrName + ':' + attrValue + ';';
}
}
if (style.length > 0) {
computedProps.style = style;
}
return computedProps;
};
export const computeBoxClassName = props => {
const color = props.textColor || props.color;
const backgroundColor = props.backgroundColor;
return classes([
isColorClass(color) && 'color-' + color,
isColorClass(backgroundColor) && 'color-bg-' + backgroundColor,
]);
};
export const Box = props => {
const {
as = 'div',
className,
children,
...rest
} = props;
// Render props
if (typeof children === 'function') {
return children(computeBoxProps(props));
}
const computedClassName = typeof className === 'string'
? className + ' ' + computeBoxClassName(rest)
: computeBoxClassName(rest);
const computedProps = computeBoxProps(rest);
// Render a wrapper element
return createVNode(
VNodeFlags.HtmlElement,
as,
computedClassName,
children,
ChildFlags.UnknownChildren,
computedProps);
};
Box.defaultHooks = pureComponentHooks;
+272
View File
@@ -0,0 +1,272 @@
import { classes, pureComponentHooks } from 'common/react';
import { Component, createRef } from 'inferno';
import { IS_IE8 } from '../byond';
import { KEY_ENTER, KEY_ESCAPE, KEY_SPACE } from '../hotkeys';
import { refocusLayout } from '../layouts';
import { createLogger } from '../logging';
import { Box } from './Box';
import { Icon } from './Icon';
import { Tooltip } from './Tooltip';
const logger = createLogger('Button');
export const Button = props => {
const {
className,
fluid,
icon,
color,
disabled,
selected,
tooltip,
tooltipPosition,
ellipsis,
content,
iconRotation,
iconSpin,
children,
onclick,
onClick,
...rest
} = props;
const hasContent = !!(content || children);
// A warning about the lowercase onclick
if (onclick) {
logger.warn(
`Lowercase 'onclick' is not supported on Button and lowercase`
+ ` prop names are discouraged in general. Please use a camelCase`
+ `'onClick' instead and read: `
+ `https://infernojs.org/docs/guides/event-handling`);
}
// IE8: Use a lowercase "onclick" because synthetic events are fucked.
// IE8: Use an "unselectable" prop because "user-select" doesn't work.
return (
<Box
className={classes([
'Button',
fluid && 'Button--fluid',
disabled && 'Button--disabled',
selected && 'Button--selected',
hasContent && 'Button--hasContent',
ellipsis && 'Button--ellipsis',
(color && typeof color === 'string')
? 'Button--color--' + color
: 'Button--color--default',
className,
])}
tabIndex={!disabled && '0'}
unselectable={IS_IE8}
onclick={e => {
refocusLayout();
if (!disabled && onClick) {
onClick(e);
}
}}
onKeyDown={e => {
const keyCode = window.event ? e.which : e.keyCode;
// Simulate a click when pressing space or enter.
if (keyCode === KEY_SPACE || keyCode === KEY_ENTER) {
e.preventDefault();
if (!disabled && onClick) {
onClick(e);
}
return;
}
// Refocus layout on pressing escape.
if (keyCode === KEY_ESCAPE) {
e.preventDefault();
refocusLayout();
return;
}
}}
{...rest}>
{icon && (
<Icon name={icon} rotation={iconRotation} spin={iconSpin} />
)}
{content}
{children}
{tooltip && (
<Tooltip
content={tooltip}
position={tooltipPosition} />
)}
</Box>
);
};
Button.defaultHooks = pureComponentHooks;
export const ButtonCheckbox = props => {
const { checked, ...rest } = props;
return (
<Button
color="transparent"
icon={checked ? 'check-square-o' : 'square-o'}
selected={checked}
{...rest} />
);
};
Button.Checkbox = ButtonCheckbox;
export class ButtonConfirm extends Component {
constructor() {
super();
this.state = {
clickedOnce: false,
};
this.handleClick = () => {
if (this.state.clickedOnce) {
this.setClickedOnce(false);
}
};
}
setClickedOnce(clickedOnce) {
this.setState({
clickedOnce,
});
if (clickedOnce) {
setTimeout(() => window.addEventListener('click', this.handleClick));
}
else {
window.removeEventListener('click', this.handleClick);
}
}
render() {
const {
confirmContent = "Confirm?",
confirmColor = "bad",
confirmIcon,
icon,
color,
content,
onClick,
...rest
} = this.props;
return (
<Button
content={this.state.clickedOnce ? confirmContent : content}
icon={this.state.clickedOnce ? confirmIcon : icon}
color={this.state.clickedOnce ? confirmColor : color}
onClick={() => this.state.clickedOnce
? onClick()
: this.setClickedOnce(true)}
{...rest}
/>
);
}
}
Button.Confirm = ButtonConfirm;
export class ButtonInput extends Component {
constructor() {
super();
this.inputRef = createRef();
this.state = {
inInput: false,
};
}
setInInput(inInput) {
this.setState({
inInput,
});
if (this.inputRef) {
const input = this.inputRef.current;
if (inInput) {
input.value = this.props.currentValue || "";
try {
input.focus();
input.select();
}
catch {}
}
}
}
commitResult(e) {
if (this.inputRef) {
const input = this.inputRef.current;
const hasValue = (input.value !== "");
if (hasValue) {
this.props.onCommit(e, input.value);
return;
} else {
if (!this.props.defaultValue) {
return;
}
this.props.onCommit(e, this.props.defaultValue);
}
}
}
render() {
const {
fluid,
content,
icon,
iconRotation,
iconSpin,
tooltip,
tooltipPosition,
color = 'default',
placeholder,
maxLength,
...rest
} = this.props;
return (
<Box
className={classes([
'Button',
fluid && 'Button--fluid',
'Button--color--' + color,
])}
{...rest}
onClick={() => this.setInInput(true)}>
{icon && (
<Icon name={icon} rotation={iconRotation} spin={iconSpin} />
)}
<div>
{content}
</div>
<input
ref={this.inputRef}
className="NumberInput__input"
style={{
'display': !this.state.inInput ? 'none' : undefined,
'text-align': 'left',
}}
onBlur={e => {
if (!this.state.inInput) {
return;
}
this.setInInput(false);
this.commitResult(e);
}}
onKeyDown={e => {
if (e.keyCode === KEY_ENTER) {
this.setInInput(false);
this.commitResult(e);
return;
}
if (e.keyCode === KEY_ESCAPE) {
this.setInInput(false);
}
}}
/>
{tooltip && (
<Tooltip
content={tooltip}
position={tooltipPosition}
/>
)}
</Box>
);
}
}
Button.Input = ButtonInput;
+154
View File
@@ -0,0 +1,154 @@
import { shallowDiffers } from 'common/react';
import { debounce } from 'common/timer';
import { Component, createRef } from 'inferno';
import { callByond, IS_IE8 } from '../byond';
import { createLogger } from '../logging';
import { computeBoxProps } from './Box';
const logger = createLogger('ByondUi');
// Stack of currently allocated BYOND UI element ids.
const byondUiStack = [];
const createByondUiElement = elementId => {
// Reserve an index in the stack
const index = byondUiStack.length;
byondUiStack.push(null);
// Get a unique id
const id = elementId || 'byondui_' + index;
logger.log(`allocated '${id}'`);
// Return a control structure
return {
render: params => {
logger.log(`rendering '${id}'`);
byondUiStack[index] = id;
callByond('winset', {
...params,
id,
});
},
unmount: () => {
logger.log(`unmounting '${id}'`);
byondUiStack[index] = null;
callByond('winset', {
id,
parent: '',
});
},
};
};
window.addEventListener('beforeunload', () => {
// Cleanly unmount all visible UI elements
for (let index = 0; index < byondUiStack.length; index++) {
const id = byondUiStack[index];
if (typeof id === 'string') {
logger.log(`unmounting '${id}' (beforeunload)`);
byondUiStack[index] = null;
callByond('winset', {
id,
parent: '',
});
}
}
});
/**
* Get the bounding box of the DOM element.
*/
const getBoundingBox = element => {
const rect = element.getBoundingClientRect();
return {
pos: [
rect.left,
rect.top,
],
size: [
rect.right - rect.left,
rect.bottom - rect.top,
],
};
};
export class ByondUi extends Component {
constructor(props) {
super(props);
this.containerRef = createRef();
this.byondUiElement = createByondUiElement(props.params?.id);
this.handleResize = debounce(() => {
this.forceUpdate();
}, 500);
}
shouldComponentUpdate(nextProps) {
const {
params: prevParams = {},
...prevRest
} = this.props;
const {
params: nextParams = {},
...nextRest
} = nextProps;
return shallowDiffers(prevParams, nextParams)
|| shallowDiffers(prevRest, nextRest);
}
componentDidMount() {
// IE8: It probably works, but fuck you anyway.
if (IS_IE8) {
return;
}
window.addEventListener('resize', this.handleResize);
return this.componentDidUpdate();
}
componentDidUpdate() {
// IE8: It probably works, but fuck you anyway.
if (IS_IE8) {
return;
}
const {
params = {},
} = this.props;
const box = getBoundingBox(this.containerRef.current);
logger.log('bounding box', box);
this.byondUiElement.render({
...params,
pos: box.pos[0] + ',' + box.pos[1],
size: box.size[0] + 'x' + box.size[1],
});
}
componentWillUnmount() {
// IE8: It probably works, but fuck you anyway.
if (IS_IE8) {
return;
}
window.removeEventListener('resize', this.handleResize);
this.byondUiElement.unmount();
}
render() {
const {
parent,
params,
...rest
} = this.props;
const type = params?.type;
const boxProps = computeBoxProps(rest);
return (
<div
ref={this.containerRef}
{...boxProps}>
{type === 'button' && <ButtonMock />}
</div>
);
}
}
const ButtonMock = () => (
<div
style={{
'min-height': '22px',
}} />
);
+121
View File
@@ -0,0 +1,121 @@
import { map, zipWith } from 'common/collections';
import { pureComponentHooks } from 'common/react';
import { Component, createRef } from 'inferno';
import { IS_IE8 } from '../byond';
import { Box } from './Box';
const normalizeData = (data, scale, rangeX, rangeY) => {
if (data.length === 0) {
return [];
}
const min = zipWith(Math.min)(...data);
const max = zipWith(Math.max)(...data);
if (rangeX !== undefined) {
min[0] = rangeX[0];
max[0] = rangeX[1];
}
if (rangeY !== undefined) {
min[1] = rangeY[0];
max[1] = rangeY[1];
}
const normalized = map(point => {
return zipWith((value, min, max, scale) => {
return (value - min) / (max - min) * scale;
})(point, min, max, scale);
})(data);
return normalized;
};
const dataToPolylinePoints = data => {
let points = '';
for (let i = 0; i < data.length; i++) {
const point = data[i];
points += point[0] + ',' + point[1] + ' ';
}
return points;
};
class LineChart extends Component {
constructor(props) {
super(props);
this.ref = createRef();
this.state = {
// Initial guess
viewBox: [600, 200],
};
this.handleResize = () => {
const element = this.ref.current;
this.setState({
viewBox: [element.offsetWidth, element.offsetHeight],
});
};
}
componentDidMount() {
window.addEventListener('resize', this.handleResize);
this.handleResize();
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleResize);
}
render() {
const {
data = [],
rangeX,
rangeY,
fillColor = 'none',
strokeColor = '#ffffff',
strokeWidth = 2,
...rest
} = this.props;
const { viewBox } = this.state;
const normalized = normalizeData(data, viewBox, rangeX, rangeY);
// Push data outside viewBox and form a fillable polygon
if (normalized.length > 0) {
const first = normalized[0];
const last = normalized[normalized.length - 1];
normalized.push([viewBox[0] + strokeWidth, last[1]]);
normalized.push([viewBox[0] + strokeWidth, -strokeWidth]);
normalized.push([-strokeWidth, -strokeWidth]);
normalized.push([-strokeWidth, first[1]]);
}
const points = dataToPolylinePoints(normalized);
return (
<Box position="relative" {...rest}>
{props => (
<div ref={this.ref} {...props}>
<svg
viewBox={`0 0 ${viewBox[0]} ${viewBox[1]}`}
preserveAspectRatio="none"
style={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
overflow: 'hidden',
}}>
<polyline
transform={`scale(1, -1) translate(0, -${viewBox[1]})`}
fill={fillColor}
stroke={strokeColor}
strokeWidth={strokeWidth}
points={points} />
</svg>
</div>
)}
</Box>
);
}
}
LineChart.defaultHooks = pureComponentHooks;
const Stub = props => null;
// IE8: No inline svg support
export const Chart = {
Line: IS_IE8 ? Stub : LineChart,
};
@@ -0,0 +1,51 @@
import { Component } from 'inferno';
import { Box } from './Box';
import { Button } from './Button';
export class Collapsible extends Component {
constructor(props) {
super(props);
const { open } = props;
this.state = {
open: open || false,
};
}
render() {
const { props } = this;
const { open } = this.state;
const {
children,
color = 'default',
title,
buttons,
...rest
} = props;
return (
<Box mb={1}>
<div className="Table">
<div className="Table__cell">
<Button
fluid
color={color}
icon={open ? 'chevron-down' : 'chevron-right'}
onClick={() => this.setState({ open: !open })}
{...rest}>
{title}
</Button>
</div>
{buttons && (
<div className="Table__cell Table__cell--collapsing">
{buttons}
</div>
)}
</div>
{open && (
<Box mt={1}>
{children}
</Box>
)}
</Box>
);
}
}
+28
View File
@@ -0,0 +1,28 @@
import { classes, pureComponentHooks } from 'common/react';
import { computeBoxClassName, computeBoxProps } from './Box';
export const ColorBox = props => {
const {
content,
children,
className,
color,
backgroundColor,
...rest
} = props;
rest.color = content ? null : 'transparent';
rest.backgroundColor = color || backgroundColor;
return (
<div
className={classes([
'ColorBox',
className,
computeBoxClassName(rest),
])}
{...computeBoxProps(rest)}>
{content || '.'}
</div>
);
};
ColorBox.defaultHooks = pureComponentHooks;
+18
View File
@@ -0,0 +1,18 @@
import { classes } from 'common/react';
import { Box } from './Box';
export const Dimmer = props => {
const { className, children, ...rest } = props;
return (
<Box
className={classes([
'Dimmer',
...className,
])}
{...rest}>
<div className="Dimmer__inner">
{children}
</div>
</Box>
);
};
+18
View File
@@ -0,0 +1,18 @@
import { classes } from 'common/react';
export const Divider = props => {
const {
vertical,
hidden,
} = props;
return (
<div
className={classes([
'Divider',
hidden && 'Divider--hidden',
vertical
? 'Divider--vertical'
: 'Divider--horizontal',
])} />
);
};
@@ -0,0 +1,274 @@
import { clamp } from 'common/math';
import { pureComponentHooks } from 'common/react';
import { Component, createRef } from 'inferno';
import { AnimatedNumber } from './AnimatedNumber';
/**
* Reduces screen offset to a single number based on the matrix provided.
*/
const getScalarScreenOffset = (e, matrix) => {
return e.screenX * matrix[0] + e.screenY * matrix[1];
};
export class DraggableControl extends Component {
constructor(props) {
super(props);
this.inputRef = createRef();
this.state = {
value: props.value,
dragging: false,
editing: false,
internalValue: null,
origin: null,
suppressingFlicker: false,
};
// Suppresses flickering while the value propagates through the backend
this.flickerTimer = null;
this.suppressFlicker = () => {
const { suppressFlicker } = this.props;
if (suppressFlicker > 0) {
this.setState({
suppressingFlicker: true,
});
clearTimeout(this.flickerTimer);
this.flickerTimer = setTimeout(() => this.setState({
suppressingFlicker: false,
}), suppressFlicker);
}
};
this.handleDragStart = e => {
const {
value,
dragMatrix,
} = this.props;
const { editing } = this.state;
if (editing) {
return;
}
document.body.style['pointer-events'] = 'none';
this.ref = e.target;
this.setState({
dragging: false,
origin: getScalarScreenOffset(e, dragMatrix),
value,
internalValue: value,
});
this.timer = setTimeout(() => {
this.setState({
dragging: true,
});
}, 250);
this.dragInterval = setInterval(() => {
const { dragging, value } = this.state;
const { onDrag } = this.props;
if (dragging && onDrag) {
onDrag(e, value);
}
}, 500);
document.addEventListener('mousemove', this.handleDragMove);
document.addEventListener('mouseup', this.handleDragEnd);
};
this.handleDragMove = e => {
const {
minValue,
maxValue,
step,
stepPixelSize,
dragMatrix,
} = this.props;
this.setState(prevState => {
const state = { ...prevState };
const offset = getScalarScreenOffset(e, dragMatrix) - state.origin;
if (prevState.dragging) {
const stepOffset = Number.isFinite(minValue)
? minValue % step
: 0;
// Translate mouse movement to value
// Give it some headroom (by increasing clamp range by 1 step)
state.internalValue = clamp(
state.internalValue
+ offset * step / stepPixelSize,
minValue - step,
maxValue + step);
// Clamp the final value
state.value = clamp(
state.internalValue
- state.internalValue % step
+ stepOffset,
minValue,
maxValue);
state.origin = getScalarScreenOffset(e, dragMatrix);
}
else if (Math.abs(offset) > 4) {
state.dragging = true;
}
return state;
});
};
this.handleDragEnd = e => {
const {
onChange,
onDrag,
} = this.props;
const {
dragging,
value,
internalValue,
} = this.state;
document.body.style['pointer-events'] = 'auto';
clearTimeout(this.timer);
clearInterval(this.dragInterval);
this.setState({
dragging: false,
editing: !dragging,
origin: null,
});
document.removeEventListener('mousemove', this.handleDragMove);
document.removeEventListener('mouseup', this.handleDragEnd);
if (dragging) {
this.suppressFlicker();
if (onChange) {
onChange(e, value);
}
if (onDrag) {
onDrag(e, value);
}
}
else if (this.inputRef) {
const input = this.inputRef.current;
input.value = internalValue;
// IE8: Dies when trying to focus a hidden element
// (Error: Object does not support this action)
try {
input.focus();
input.select();
}
catch {}
}
};
}
render() {
const {
dragging,
editing,
value: intermediateValue,
suppressingFlicker,
} = this.state;
const {
animated,
value,
unit,
minValue,
maxValue,
format,
onChange,
onDrag,
children,
// Input props
height,
lineHeight,
fontSize,
} = this.props;
let displayValue = value;
if (dragging || suppressingFlicker) {
displayValue = intermediateValue;
}
// Setup a display element
// Shows a formatted number based on what we are currently doing
// with the draggable surface.
const renderDisplayElement = value => (
value + (unit ? ' ' + unit : '')
);
const displayElement = (
animated && !dragging && !suppressingFlicker && (
<AnimatedNumber
value={displayValue}
format={format}>
{renderDisplayElement}
</AnimatedNumber>
) || (
renderDisplayElement(format
? format(displayValue)
: displayValue)
)
);
// Setup an input element
// Handles direct input via the keyboard
const inputElement = (
<input
ref={this.inputRef}
className="NumberInput__input"
style={{
display: !editing ? 'none' : undefined,
height: height,
'line-height': lineHeight,
'font-size': fontSize,
}}
onBlur={e => {
if (!editing) {
return;
}
const value = clamp(e.target.value, minValue, maxValue);
this.setState({
editing: false,
value,
});
this.suppressFlicker();
if (onChange) {
onChange(e, value);
}
if (onDrag) {
onDrag(e, value);
}
}}
onKeyDown={e => {
if (e.keyCode === 13) {
const value = clamp(e.target.value, minValue, maxValue);
this.setState({
editing: false,
value,
});
this.suppressFlicker();
if (onChange) {
onChange(e, value);
}
if (onDrag) {
onDrag(e, value);
}
return;
}
if (e.keyCode === 27) {
this.setState({
editing: false,
});
return;
}
}} />
);
// Return a part of the state for higher-level components to use.
return children({
dragging,
editing,
value,
displayValue,
displayElement,
inputElement,
handleDragStart: this.handleDragStart,
});
}
}
DraggableControl.defaultHooks = pureComponentHooks;
DraggableControl.defaultProps = {
minValue: -Infinity,
maxValue: +Infinity,
step: 1,
stepPixelSize: 1,
suppressFlicker: 50,
dragMatrix: [1, 0],
};
+124
View File
@@ -0,0 +1,124 @@
import { classes } from 'common/react';
import { Component } from 'inferno';
import { Box } from './Box';
import { Icon } from './Icon';
export class Dropdown extends Component {
constructor(props) {
super(props);
this.state = {
selected: props.selected,
open: false,
};
this.handleClick = () => {
if (this.state.open) {
this.setOpen(false);
}
};
}
componentWillUnmount() {
window.removeEventListener('click', this.handleClick);
}
setOpen(open) {
this.setState({ open: open });
if (open) {
setTimeout(() => window.addEventListener('click', this.handleClick));
this.menuRef.focus();
}
else {
window.removeEventListener('click', this.handleClick);
}
}
setSelected(selected) {
this.setState({
selected: selected,
});
this.setOpen(false);
this.props.onSelected(selected);
}
buildMenu() {
const { options = [] } = this.props;
const ops = options.map(option => (
<div
key={option}
className="Dropdown__menuentry"
onClick={() => {
this.setSelected(option);
}}>
{option}
</div>
));
return ops.length ? ops : 'No Options Found';
}
render() {
const { props } = this;
const {
color = 'default',
over,
noscroll,
nochevron,
width,
onClick,
selected,
disabled,
...boxProps
} = props;
const {
className,
...rest
} = boxProps;
const adjustedOpen = over ? !this.state.open : this.state.open;
const menu = this.state.open ? (
<div
ref={menu => { this.menuRef = menu; }}
tabIndex="-1"
style={{
'width': width,
}}
className={classes([
noscroll && 'Dropdown__menu-noscroll' || 'Dropdown__menu',
over && 'Dropdown__over',
])}>
{this.buildMenu()}
</div>
) : null;
return (
<div className="Dropdown">
<Box
width={width}
className={classes([
'Dropdown__control',
'Button',
'Button--color--' + color,
disabled && 'Button--disabled',
className,
])}
{...rest}
onClick={() => {
if (disabled && !this.state.open) {
return;
}
this.setOpen(!this.state.open);
}}>
<span className="Dropdown__selected-text">
{this.state.selected}
</span>
{!!nochevron || (
<span className="Dropdown__arrow-button">
<Icon name={adjustedOpen ? 'chevron-up' : 'chevron-down'} />
</span>
)}
</Box>
{menu}
</div>
);
}
}
+81
View File
@@ -0,0 +1,81 @@
import { classes, pureComponentHooks } from 'common/react';
import { IS_IE8 } from '../byond';
import { Box, unit } from './Box';
export const computeFlexProps = props => {
const {
className,
direction,
wrap,
align,
justify,
inline,
spacing = 0,
...rest
} = props;
return {
className: classes([
'Flex',
IS_IE8 && (
direction === 'column'
? 'Flex--ie8--column'
: 'Flex--ie8'
),
inline && 'Flex--inline',
spacing > 0 && 'Flex--spacing--' + spacing,
className,
]),
style: {
...rest.style,
'flex-direction': direction,
'flex-wrap': wrap,
'align-items': align,
'justify-content': justify,
},
...rest,
};
};
export const Flex = props => (
<Box {...computeFlexProps(props)} />
);
Flex.defaultHooks = pureComponentHooks;
export const computeFlexItemProps = props => {
const {
className,
grow,
order,
shrink,
// IE11: Always set basis to specified width, which fixes certain
// bugs when rendering tables inside the flex.
basis = props.width,
align,
...rest
} = props;
return {
className: classes([
'Flex__item',
IS_IE8 && 'Flex__item--ie8',
className,
]),
style: {
...rest.style,
'flex-grow': grow,
'flex-shrink': shrink,
'flex-basis': unit(basis),
'order': order,
'align-self': align,
},
...rest,
};
};
export const FlexItem = props => (
<Box {...computeFlexItemProps(props)} />
);
FlexItem.defaultHooks = pureComponentHooks;
Flex.Item = FlexItem;
+31
View File
@@ -0,0 +1,31 @@
import { Table } from './Table';
import { pureComponentHooks } from 'common/react';
export const Grid = props => {
const { children, ...rest } = props;
return (
<Table {...rest}>
<Table.Row>
{children}
</Table.Row>
</Table>
);
};
Grid.defaultHooks = pureComponentHooks;
export const GridColumn = props => {
const { size = 1, style, ...rest } = props;
return (
<Table.Cell
style={{
width: size + '%',
...style,
}}
{...rest} />
);
};
Grid.defaultHooks = pureComponentHooks;
Grid.Column = GridColumn;
+30
View File
@@ -0,0 +1,30 @@
import { classes, pureComponentHooks } from 'common/react';
import { Box } from './Box';
const FA_OUTLINE_REGEX = /-o$/;
export const Icon = props => {
const { name, size, spin, className, style = {}, rotation, ...rest } = props;
if (size) {
style['font-size'] = (size * 100) + '%';
}
if (typeof rotation === 'number') {
style['transform'] = `rotate(${rotation}deg)`;
}
const faRegular = FA_OUTLINE_REGEX.test(name);
const faName = name.replace(FA_OUTLINE_REGEX, '');
return (
<Box
as="i"
className={classes([
className,
faRegular ? 'far' : 'fas',
'fa-' + faName,
spin && 'fa-spin',
])}
style={style}
{...rest} />
);
};
Icon.defaultHooks = pureComponentHooks;
+138
View File
@@ -0,0 +1,138 @@
import { classes, isFalsy } from 'common/react';
import { Component, createRef } from 'inferno';
import { Box } from './Box';
const toInputValue = value => {
if (isFalsy(value)) {
return '';
}
return value;
};
export class Input extends Component {
constructor() {
super();
this.inputRef = createRef();
this.state = {
editing: false,
};
this.handleInput = e => {
const { editing } = this.state;
const { onInput } = this.props;
if (!editing) {
this.setEditing(true);
}
if (onInput) {
onInput(e, e.target.value);
}
};
this.handleFocus = e => {
const { editing } = this.state;
if (!editing) {
this.setEditing(true);
}
};
this.handleBlur = e => {
const { editing } = this.state;
const { onChange } = this.props;
if (editing) {
this.setEditing(false);
if (onChange) {
onChange(e, e.target.value);
}
}
};
this.handleKeyDown = e => {
const { onInput, onChange, onEnter } = this.props;
if (e.keyCode === 13) {
this.setEditing(false);
if (onChange) {
onChange(e, e.target.value);
}
if (onInput) {
onInput(e, e.target.value);
}
if (onEnter) {
onEnter(e, e.target.value);
}
if (this.props.selfClear) {
e.target.value = '';
} else {
e.target.blur();
}
return;
}
if (e.keyCode === 27) {
this.setEditing(false);
e.target.value = toInputValue(this.props.value);
e.target.blur();
return;
}
};
}
componentDidMount() {
const nextValue = this.props.value;
const input = this.inputRef.current;
if (input) {
input.value = toInputValue(nextValue);
}
}
componentDidUpdate(prevProps, prevState) {
const { editing } = this.state;
const prevValue = prevProps.value;
const nextValue = this.props.value;
const input = this.inputRef.current;
if (input && !editing && prevValue !== nextValue) {
input.value = toInputValue(nextValue);
}
}
setEditing(editing) {
this.setState({ editing });
}
render() {
const { props } = this;
// Input only props
const {
selfClear,
onInput,
onChange,
onEnter,
value,
maxLength,
placeholder,
...boxProps
} = props;
// Box props
const {
className,
fluid,
...rest
} = boxProps;
return (
<Box
className={classes([
'Input',
fluid && 'Input--fluid',
className,
])}
{...rest}>
<div className="Input__baseline">
.
</div>
<input
ref={this.inputRef}
className="Input__input"
placeholder={placeholder}
onInput={this.handleInput}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
onKeyDown={this.handleKeyDown}
maxLength={maxLength} />
</Box>
);
}
}
+139
View File
@@ -0,0 +1,139 @@
import { keyOfMatchingRange, scale } from 'common/math';
import { classes } from 'common/react';
import { IS_IE8 } from '../byond';
import { computeBoxClassName, computeBoxProps } from './Box';
import { DraggableControl } from './DraggableControl';
import { NumberInput } from './NumberInput';
export const Knob = props => {
// IE8: I don't want to support a yet another component on IE8.
// IE8: It also can't handle SVG.
if (IS_IE8) {
return (
<NumberInput {...props} />
);
}
const {
// Draggable props (passthrough)
animated,
format,
maxValue,
minValue,
onChange,
onDrag,
step,
stepPixelSize,
suppressFlicker,
unit,
value,
// Own props
className,
style,
fillValue,
color,
ranges = {},
size,
bipolar,
children,
...rest
} = props;
return (
<DraggableControl
dragMatrix={[0, -1]}
{...{
animated,
format,
maxValue,
minValue,
onChange,
onDrag,
step,
stepPixelSize,
suppressFlicker,
unit,
value,
}}>
{control => {
const {
dragging,
editing,
value,
displayValue,
displayElement,
inputElement,
handleDragStart,
} = control;
const scaledFillValue = scale(
fillValue ?? displayValue,
minValue,
maxValue);
const scaledDisplayValue = scale(
displayValue,
minValue,
maxValue);
const effectiveColor = color
|| keyOfMatchingRange(fillValue ?? value, ranges)
|| 'default';
const rotation = (scaledDisplayValue - 0.5) * 270;
return (
<div
className={classes([
'Knob',
'Knob--color--' + effectiveColor,
bipolar && 'Knob--bipolar',
className,
computeBoxClassName(rest),
])}
{...computeBoxProps({
style: {
'font-size': size + 'rem',
...style,
},
...rest,
})}
onMouseDown={handleDragStart}>
<div className="Knob__circle">
<div
className="Knob__cursorBox"
style={{
transform: `rotate(${rotation}deg)`,
}}>
<div className="Knob__cursor" />
</div>
</div>
{dragging && (
<div className="Knob__popupValue">
{displayElement}
</div>
)}
<svg
className="Knob__ring Knob__ringTrackPivot"
viewBox="0 0 100 100">
<circle
className="Knob__ringTrack"
cx="50"
cy="50"
r="50" />
</svg>
<svg
className="Knob__ring Knob__ringFillPivot"
viewBox="0 0 100 100">
<circle
className="Knob__ringFill"
style={{
'stroke-dashoffset': (
((bipolar ? 2.75 : 2.00) - scaledFillValue * 1.5)
* Math.PI * 50
),
}}
cx="50"
cy="50"
r="50" />
</svg>
{inputElement}
</div>
);
}}
</DraggableControl>
);
};

Some files were not shown because too many files have changed in this diff Show More