if not is_client then
    return
end

function set_slider(node)
    local value = node:get_property_float("value") or 1
    local min = node:get_property_float("min") or 0
    local max = node:get_property_float("max") or 1
    local format = node:get_property_string("format") or "%f"

    local thumb = node:query():name("slider_thumb"):matches()(nil, nil)
    thumb:set_property_float("offset", (value - min) / (max - min))
    local text = node:query():name("slider_value"):child():text():matches()(nil, nil)
    text:set_text(string.format(format, value))
end

function warp_to(node, evt)
    local min = node:get_property_float("min") or 0
    local max = node:get_property_float("max") or 1

    local rx, _, _, _ = node:render_position()
    local _, _, w, h = node:raw_position()

    local offset = (evt.x - (h/2) - rx) / (w - h)
    if offset > 1 then
        offset = 1
    end
    if offset < 0 then
        offset = 0
    end
    node:set_property_float("value", min + (max - min) * offset)
    set_slider(node)
end

function start_slider(node, evt)
    warp_to(node, evt)
    local catcher = ui.new("slider_catcher")
    catcher:set_property_table("$slider", {
        slider = node,
    })
    ui.add_node(catcher)
end

function close_slider()
    local dc = ui.query():name("slider_catcher"):matches()(nil, nil)
    if dc == nil then
        return
    end
    ui.remove_node(dc)
end