Skip to content

Commit

Permalink
Add support for variables in buttons and fix an issue where the varia…
Browse files Browse the repository at this point in the history
…ble regex would only match every other time

Signed-off-by: Axel Boberg <[email protected]>
  • Loading branch information
axelboberg committed Feb 12, 2025
1 parent f2f9498 commit 83b31a5
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 3 deletions.
17 changes: 16 additions & 1 deletion api/variables.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,22 @@ const objectPath = require('object-path')

const DIController = require('../shared/DIController')

const VARIABLE_REGEX = /\$\((.*?)\)/g
/**
* The regex used to match
* variables in strings
*
* @example
* "My string $(my_variable)" -> MATCH
* "My string no variable" -> NO MATCH
*
* This should NOT be made global "/g" as that will trigger
* an issue where the expression will only match every
* other time it's used – this is known behaviour in
* multiple browsers
*
* @type { RegExp }
*/
const VARIABLE_REGEX = /\$\((.*?)\)/

class Variables {
#props
Expand Down
34 changes: 32 additions & 2 deletions plugins/button/app/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,32 @@ import { QueryPath } from './components/QueryPath'
import { ItemButton } from './components/ItemButton'
import { ItemDropArea } from './components/ItemDropArea'

/**
* Get the label to display in a button
* for an item or non-item
*
* @param { any } item
* @returns { Promise.<String> }
*/
async function getLabel (item) {
if (!item) {
return 'Drop an item here'
}

if (!item?.data?.name) {
return 'Unnamed'
}

if (!bridge.variables.stringContainsVariable(item?.data?.name)) {
return item?.data?.name
}

return await bridge.items.renderValue(item.id, 'data.name')
}

export default function App () {
const [itemId, setItemId] = React.useState()
const [label, setLabel] = React.useState()
const [item, setItem] = React.useState()

React.useEffect(() => {
Expand Down Expand Up @@ -39,6 +63,14 @@ export default function App () {
}
}, [item])

React.useEffect(() => {
async function render () {
const label = await getLabel(item)
setLabel(label)
}
render()
}, [itemId, item])

function handleItemChange (itemId) {
window.WIDGET_UPDATE({
'itemId': itemId
Expand All @@ -60,8 +92,6 @@ export default function App () {
bridge.items.stopItem(itemId)
}

const label = item ? (item?.data?.name || 'Unnamed') : 'Drop an item here'

return (
<>
<QueryPath path='play'>
Expand Down

0 comments on commit 83b31a5

Please sign in to comment.