Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pass invoking element as event data #1112

Merged
merged 1 commit into from
Dec 14, 2023
Merged

Pass invoking element as event data #1112

merged 1 commit into from
Dec 14, 2023

Conversation

swanson
Copy link
Contributor

@swanson swanson commented Dec 13, 2023

Given toolbar buttons that triggers an external action like:

<button type="button" data-trix-action="x-insert-token" data-token="{{ user.name }}">Insert name</button>
<button type="button" data-trix-action="x-insert-token" data-token="{{ user.email }}">Insert email</button>

Trix will call trix-action-invoke with event.actionName of x-insert-token.

We can register behavior to handle this event:

addEventListener('trix-action-invoke', function (event) {
  if (event.actionName == 'x-insert-token') {
    event.target.editor.insertString("Testing!")
  }
})

But only the actionName is sent in event, there appears to be no way to get a reference to the invoking element. In this case, we need that reference to read the data-token attribute so we could then write:

if (event.actionName == 'x-insert-token') {
  const token = event.invokingElement.getAttribute("data-token")
  event.target.editor.insertString(token)
}

This PR changes invokeAction to pass along the invokingElement for toolbar external actions.

Currently, you can work around this by using something like Stimulus to process the button click as an action and then get a reference to the Trix editor instance, but this change would support this kind of extension directly using Trix primitives and concepts.

I did not see any tests around this event functionality so I have omitted them. Happy to take a stab if that helps!

@afcapel
Copy link
Contributor

afcapel commented Dec 14, 2023

This makes sense 👍

I was wondering if calling the property event.target or event.originalTarget would make more sense than event.invokingElement. But event.target is already the editor itself, and event.originalTarget has a loaded history. I think event.invokingElement is a good name.

@afcapel afcapel merged commit ca59588 into basecamp:main Dec 14, 2023
1 check failed
@afcapel
Copy link
Contributor

afcapel commented Dec 14, 2023

Thanks @swanson! 🙏

@swanson swanson deleted the swanson/invoke-action-pass-element branch December 14, 2023 21:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants