Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kmbremner/1aaadb6fb05fdea37495fe23c7623cef to your computer and use it in GitHub Desktop.
Save kmbremner/1aaadb6fb05fdea37495fe23c7623cef to your computer and use it in GitHub Desktop.
Add a prefix to Tailwind UI components automatically (with Tampermonkey)
// ==UserScript==
// @name Add TW UI prefix
// @namespace http://tampermonkey.net/
// @version 1.0
// @description Add a prefix to Tailwind UI
// @author https://gist.github.com/KevinBatdorf/d772807789a79f07453c144c772d6a76
// @match https://tailwindui.com/components/*
// @grant none
// ==/UserScript==
// Requires Tampermonkey
// Chrome - https://chrome.google.com/webstore/detail/tampermonkey/dhdgffkkebhmkfjojejmpbldmpobfkfo?hl=en
// FF - https://addons.mozilla.org/en-US/firefox/addon/tampermonkey/
// Find me on Twitter: https://twitter.com/kevinbatdorf
const prefix = 'tw'
// Grab all components
const code = Array.from(document.querySelectorAll('button')).filter(b => b.getAttribute('@click') && b.getAttribute('@click').includes('navigator.clipboard.writeText'))
code.forEach(node => {
// Override clipboard button
node.addEventListener('click', function(event) {
event.preventDefault()
// Get the htmls
const content = event.target.closest('[id^=component-]').querySelector('[x-ref=codeBlockhtml]')
// Add it to the dom for parsing
const temp = document.createElement('div')
temp.innerHTML = content.innerText
// Replace all classes
temp.querySelectorAll('[class]').forEach((el) => {
const prefixed = Array.from(el.classList).map(
c => {
// Check for variants
const variant = c.split(':').slice(0, -1)
const rule = c.split(':').slice(-1)
return variant.length ? `${variant.join(':')}:${prefix}-${rule.join()}` : `${prefix}-${rule.join()}`
}
)
// Remove the old and add the new!
el.className = ''
el.classList.add(...prefixed)
})
// Insert back into a text area to be copied
const textarea = document.createElement('textarea')
textarea.textContent = temp.innerHTML
document.body.appendChild(textarea)
setTimeout(() => {
// Do the copy thing!
textarea.select()
document.execCommand('copy')
document.body.removeChild(textarea)
}, 50)
})
})
@sigmazen
Copy link

sigmazen commented Nov 6, 2021

Hi ... does this still work? For some reason it's not copying the alpine code. Thanks in advance

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment