JuliaPluto / PlutoUI.jl

https://featured.plutojl.org/basic/plutoui.jl
The Unlicense
302 stars 55 forks source link

Add `transformed_value` to add a value transformation to an existing widget #176

Closed fonsp closed 2 years ago

fonsp commented 2 years ago
transformed_value(transform::Function, widget::Any; [initial_value::Function])

Create a new widget that wraps around an existing one, with a value transformation.

This function creates a so-called high-level widget: it returns your existing widget, but with additional functionality. You can use it in your package

Example

A simple example to get the point accross:

function RepeatedTextSlider(text::String)   
    old_widget = PlutoUI.Slider(1:10)

    # our transformation function
    transform = input -> repeat(text, input)

    # use `transformed_value` to add the value tranformation to our widget
    new_widget = transformed_value(transform, old_widget)
    return new_widget
end

@bind greeting RepeatedTextSlider("hello")

# moving the slider to the right...

greeting == "hellohellohello"

screenshot of the above code in action


This function is very useful in combination with PlutoUI.combine. Let's enhance our previous example by adding a text box where the repeated text can be entered. If you have not used PlutoUI.combine yet, you should read about that first.

function RepeatedTextSlider()
    old_widget = PlutoUI.combine() do Child
        md""" $(Child(PlutoUI.TextField())) $(Child(PlutoUI.Slider(1:10)))"""
    end

    # Note that the input to `transform` is now a Tuple!
    # (This is the output of `PlutoUI.combine`)
    transform = input -> repeat(input[1], input[2])

    # use `transformed_value` to add the value tranformation to our widget
    new_widget = transformed_value(transform, old_widget)
    return new_widget
end

screenshot of the above code in action

github-actions[bot] commented 2 years ago

Try this Pull Request!

Open Julia and type:

  julia> import Pkg
julia> Pkg.activate(temp=true)
julia> Pkg.add(url="https://github.com/JuliaPluto/PlutoUI.jl", rev="transformed_value")
julia> using PlutoUI

Or run this code in your browser: Run with binder

fonsp commented 2 years ago

@MichaelHatherly maybe this is useful to you? Let me know if you get a chance to try it out!

MichaelHatherly commented 2 years ago

Thanks, looks like it definitely will be! I'll let you know if I get a chance to try it out.