Skip to content

Instantly share code, notes, and snippets.

@KevinBatdorf
Last active April 26, 2021 21:09
Show Gist options
  • Save KevinBatdorf/d772807789a79f07453c144c772d6a76 to your computer and use it in GitHub Desktop.
Save KevinBatdorf/d772807789a79f07453c144c772d6a76 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==
//! Note: See the comments below for an updated version
// https://gist.github.com/KevinBatdorf/d772807789a79f07453c144c772d6a76#gistcomment-3720594
// 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('ClipboardCode'))
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=htmlClipboardCode]')
// Add it to the dom for parsing
const temp = document.createElement('div')
temp.innerHTML = content.value
// 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)
})
})
@KevinBatdorf
Copy link
Author

It's fine. People will see the comment and use yours. I'll edit it with a note.

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