Skip to content

Commit cee11b3

Browse files
Fix clipboard button in ui.code after content has been changed (zauberzeug#5298)
### Motivation In zauberzeug#5177 we noticed that the copy button writes old content to the clipboard when the content of `ui.code` has been updated: ```py c = ui.code('old content') c.content = 'new content' ``` Clicking the button will write "old content" to the clipboard. ### Implementation This PR introduces a new "content" prop to hold the raw (non-HTML) version of the content. When clicking the copy button, a JavaScript call will write the value of this prop to the clipboard. ### Progress - [x] I chose a meaningful title that completes the sentence: "If applied, this PR will..." - [x] The implementation is complete. - [x] Pytests are probably not necessary (and probably pretty hard to write). - [x] Documentation is not necessary.
1 parent a234dd0 commit cee11b3

File tree

2 files changed

+6
-3
lines changed

2 files changed

+6
-3
lines changed

nicegui/elements/code.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,7 @@ export default {
33
mounted() {
44
if (!navigator.clipboard) this.$el.querySelector(".q-btn").style.display = "none";
55
},
6+
props: {
7+
content: String,
8+
},
69
};

nicegui/elements/code.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
import time
33
from typing import Optional
44

5-
from .. import json
65
from .button import Button as button
76
from .markdown import Markdown as markdown
87
from .markdown import remove_indentation
@@ -29,8 +28,9 @@ def __init__(self, content: str = '', *, language: Optional[str] = 'python') ->
2928
.bind_content_from(self, 'content', lambda content: f'```{language}\n{content}\n```')
3029
self.copy_button = button(icon='content_copy', on_click=self.show_checkmark) \
3130
.props('round flat size=sm').classes('absolute right-2 top-2 opacity-20 hover:opacity-80') \
32-
.on('click', js_handler=f'() => navigator.clipboard.writeText({json.dumps(self.content)})')
31+
.on('click', js_handler=f'() => navigator.clipboard.writeText(getElement("{self.id}").content)')
3332

33+
self._props['content'] = self.content
3434
self._last_scroll: float = 0.0
3535
self.markdown.on('scroll', self._handle_scroll)
3636
with self:
@@ -49,4 +49,4 @@ def _update_copy_button(self) -> None:
4949
self.copy_button.set_visibility(time.time() > self._last_scroll + 1.0)
5050

5151
def _handle_content_change(self, content: str) -> None:
52-
pass # handled by markdown element
52+
self._props['content'] = content

0 commit comments

Comments
 (0)