Skip to content

Make it easy to create copy-to-clipboard button #6621

@MarcSkovMadsen

Description

@MarcSkovMadsen

I'm very often in need of a copy-to-clipboard button. The users can copy text (plain, markdown, code) or data (dataframes). Currently its not easy to do in Panel. The new ButtonIcon provides the basic widget to do this.

My request is to either add example code to the ButtonIcon reference guide or even better add a class method create_copy_to_clipboard_button. I would prefer the class method.

Code

Example implementation and usage.

import panel as pn
import pandas as pd

pn.extension()

def _create_copy_to_clipboard_code(text):
    return f"""
const text = `{ text }`
navigator.clipboard.writeText(text)
"""

def _create_copy_to_clipboard_text(value, index):
    if isinstance(value, pd.DataFrame):
        return value.to_csv(index=index)
    return value

def create_copy_to_clipboard_button(value: str|pd.DataFrame, index=False, icon="clipboard", active_icon: str="check", description="Copy", toggle_duration: int=2000, **params):
    button = pn.widgets.ButtonIcon(
        active_icon=active_icon,
        description=description,
        icon=icon,
        toggle_duration=toggle_duration,
        **params,
    )
    
    text = _create_copy_to_clipboard_text(value, index=index)
    code = _create_copy_to_clipboard_code(text)
    button.js_on_click(code=code)
    return button

text="Hello World"
text_button = create_copy_to_clipboard_button(text)
text_button.servable()

data = pd.DataFrame({'Column1': [1, 2, 3], 'Column2': [4, 5, 6]})
table_button=create_copy_to_clipboard_button(data, size="5em", index=False)
table_button.servable()

I would like to enable users to provide a callback function that provides the value dynamically when the button is clicked. But I have no idea how this can be supported.

[x] Yes, I would be willing to contribute a PR if this proposal is accepted and guidance on whether docs or methods+docs should be contributed.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions