harvest/game/scripts/confirm_box.gd
2026-10-04 12:07:36 -04:00

80 lines
2.2 KiB
GDScript

class_name ConfirmBox
extends CenterContainer
## A yes / no question over the menus (Main): the message, the confirming button, and Cancel
## (focused, so a stray Enter / A never throws progress away). Escape / B cancels.
var message: Label
var yes_button: Button
var no_button: Button
var is_open := false
var _on_yes: Callable
func _ready() -> void:
set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
var panel := PanelContainer.new()
add_child(panel)
var margin := MarginContainer.new()
for side in ["left", "right", "top", "bottom"]:
margin.add_theme_constant_override("margin_" + side, 30)
panel.add_child(margin)
var box := VBoxContainer.new()
box.add_theme_constant_override("separation", 22)
margin.add_child(box)
message = Label.new()
message.custom_minimum_size = Vector2(560.0, 0.0)
message.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
message.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
message.add_theme_font_size_override("font_size", 24)
box.add_child(message)
var row := HBoxContainer.new()
row.alignment = BoxContainer.ALIGNMENT_CENTER
row.add_theme_constant_override("separation", 24)
box.add_child(row)
yes_button = Button.new()
yes_button.custom_minimum_size = Vector2(240.0, 54.0)
yes_button.pressed.connect(_yes)
row.add_child(yes_button)
no_button = Button.new()
no_button.text = "Cancel"
no_button.custom_minimum_size = Vector2(200.0, 54.0)
no_button.pressed.connect(close)
row.add_child(no_button)
visible = false
mouse_filter = Control.MOUSE_FILTER_IGNORE
func ask(text: String, confirm_text: String, on_yes: Callable) -> void:
message.text = text
yes_button.text = confirm_text
_on_yes = on_yes
is_open = true
visible = true
mouse_filter = Control.MOUSE_FILTER_STOP
no_button.grab_focus.call_deferred()
func close() -> void:
if not is_open:
return
is_open = false
visible = false
mouse_filter = Control.MOUSE_FILTER_IGNORE
func _draw() -> void:
draw_rect(Rect2(Vector2.ZERO, size), Color(0.0, 0.0, 0.0, 0.45)) # dims what's behind
func _yes() -> void:
var then := _on_yes
close()
if then.is_valid():
then.call()
func _unhandled_input(event: InputEvent) -> void:
if is_open and event.is_action_pressed("ui_cancel"):
close()
get_viewport().set_input_as_handled()