Skip to content

Commit

Permalink
dynamically hide ui.code's copy button
Browse files Browse the repository at this point in the history
  • Loading branch information
falkoschindler committed Jan 5, 2024
1 parent d31782e commit d837e69
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions nicegui/elements/code.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import asyncio
import time
from typing import Optional

from ..element import Element
from ..elements.button import Button as button
from ..elements.markdown import Markdown as markdown
from ..elements.markdown import remove_indentation
from ..functions.javascript import run_javascript
from .button import Button as button
from .markdown import Markdown as markdown
from .markdown import remove_indentation
from .timer import Timer as timer


class Code(Element):
Expand All @@ -28,9 +30,19 @@ def __init__(self, content: str, *, language: Optional[str] = 'python') -> None:
self.copy_button = button(icon='content_copy', on_click=self.copy_to_clipboard) \
.props('round flat size=sm').classes('absolute right-2 top-2 opacity-20 hover:opacity-80')

self._last_scroll: float = 0.0
self.markdown.on('scroll', self._handle_scroll)
timer(0.1, self._update_copy_button)

async def copy_to_clipboard(self) -> None:
"""Copy the code to the clipboard."""
run_javascript('navigator.clipboard.writeText(`' + self.content + '`)')
self.copy_button.props('icon=check')
await asyncio.sleep(3.0)
self.copy_button.props('icon=content_copy')

def _handle_scroll(self) -> None:
self._last_scroll = time.time()

def _update_copy_button(self) -> None:
self.copy_button.set_visibility(time.time() > self._last_scroll + 1.0)

0 comments on commit d837e69

Please sign in to comment.