Skip to content

Instantly share code, notes, and snippets.

@coolprobn
Created October 8, 2024 04:26
Show Gist options
  • Save coolprobn/8664f9c71ddedd5a31f2a6abd5546644 to your computer and use it in GitHub Desktop.
Save coolprobn/8664f9c71ddedd5a31f2a6abd5546644 to your computer and use it in GitHub Desktop.
Copy to Clipboard with Rails, StimuluJS & TailwindCSS + DaisyUI
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = ["source", "checkbox"]
copy() {
const textToCopy = this.sourceTarget.innerText
if (!this.checkboxTarget.checked && this.isManuallyTriggeredClick) {
this.isManuallyTriggeredClick = false
return
}
navigator.clipboard.writeText(textToCopy).then(
() => {
const x = this;
setTimeout(function () {
x.isManuallyTriggeredClick = true
x.checkboxTarget.click()
}, 1500)
},
() => {
console.log("Failed to copy command to clipboard")
},
);
}
}
<div data-controller="clipboard" class="mockup-code pb-0">
<label class="swap absolute top-4 right-4">
<!-- this hidden checkbox controls the state -->
<input type="checkbox" class="hidden" data-action="click->clipboard#copy" data-clipboard-target="checkbox" />
<%= heroicon "clipboard" , options: { class: "swap-off" } %>
<%= heroicon "check" , options: { class: "swap-on text-success" } %>
</label>
<div class="generator-command max-h-16 overflow-y-auto">
<div class="pb-6">
<pre class="whitespace-pre-wrap break-all mx-6 p-0 before:mr-0">
<code data-clipboard-target="source">
zen add ci:gitlab_ci
</code>
</pre>
</div>
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment