Problem/Motivation
This is a follow-up of #3020716: Add vertical tabs style menu to media library. The current AJAX system supports opening dialogs by adding the use-ajax class to a link. In the media library, once you are in the library, we have some links that need to replace parts of the dialog instead of close the current dialog and open a new one (which is an accessibility issue, see #3020716-18: Add vertical tabs style menu to media library).
The AJAX system supports replacing selectors with AJAX content, but to do that you currently have to do a custom implementation in JS. It would be great if the AJAX system provides an easier way to do this.
Proposed resolution
Add more flexibility to the current AJAX system for the use-ajax class OR add a new class for this new use-case.
The following things would be nice:
- Add a class to a link so the AJAX behavior is automatically attached to the link.
- The href of the link will be used to fetch the new content.
- A data attribute to specify the selector that needs to be replaced.
- A data attribute to specify where the focus needs to go afterwards.
- A data attribute to specify the throbber.
Remaining tasks
Discuss how to implement this.
Write a patch.
User interface changes
API changes
Data model changes
Release notes snippet
| Comment | File | Size | Author |
|---|
Issue fork drupal-3026636
Show commands
Start within a Git clone of the project using the version control instructions.
Or, if you do not have SSH keys set up on git.drupalcode.org:
Comments
Comment #2
seanbHere is a first patch:
This works by default with the use-ajax class.
This works by default with the use-ajax class.
Added this in the patch. Drupal.Ajax does not allow you to specify a selector, but you can specify a wrapper ID. So used that.
Added this in the patch. Not sure how we can test this though?
Added this in the patch.
Comment #3
phenaproximaSo here, I think, is my major question about this change: it's possible for the AJAX response to contain commands which replace things targeted by a selector. What if the response, then, collides with the way the link is configured? What will take precedence?
Comment #4
seanbThe ajax response takes precedence. The wrapper from the data attribute is only used if there is no wrapper set in the response. Same as for focus (which already worked that way).
This already worked that way, since the following code enforces that:
Added an extra test to make sure this still works as expected.
Comment #5
phenaproximaOkay, that makes sense to me. In addition to a change record, I think we'll need to update whatever documentation exists about the use-ajax class. I'm also tagging this for JS and framework manager review.
Comment #6
phenaproximaAlso tagging for front-end framework manager review.
Comment #7
wim leers👍 This makes sense: it allows the HTML to specify a progress indicator other than
throbber.Same thing here.
🤔 Why no
|| falsefallback here?data-progress,data-wrapperanddata-focus. Why notdata-ajax-progress,data-ajax-wrapperanddata-ajax-focus?Why this?
Sounds sensible.
"check if there is a specific element that needs to get the focus"
->
"check if the triggering element has a `data-focus` attribute that specifies a selector which should get focus"
Comment #8
seanb#7:
1. Yay!
2. Yay!
3. Fixed. It should be null instead of false I guess.
4. Fixed. The other data attributes also didn't have the ajax prefix, but since they did have the dialog prefix, let's add them for clarity and to prevent conflicts.
5. All settings have defaults and documentation. This is they only new one I have added so I though a default would be consistent.
6. Fixed.
Comment #9
wim leerss/data-focus/data-ajax-focus/
Once that's fixed, RTBC!
Comment #10
seanbThanks, fixed that. Also referencing 2 issues that could immediately use this nice feature once it lands.
Comment #11
phenaproximaNice! Unfortunately, I need to kick this back for a change record...
Comment #12
seanbAdded a CR: https://www.drupal.org/node/3031444
Comment #13
seanbAbout the documentation, there does not seem to be any documentation to update. The use-ajax class is mentioned once (https://api.drupal.org/api/drupal/core%21core.api.php/group/ajax/8.6.x) but only that it exists more or less. The dialog related data attributes that were supported before are not mentioned anywhere.
Not really sure what the best place would be to document this. Should we just add a list of supported data attributes to this section? And is documenting the use-ajax class in scope of this patch or should we have a followup to properly document everything about this class?
Comment #14
phenaproximaLet's defer to a framework manager on that one.
Comment #15
wim leersThis seems the reasonable approach. I don't see how this patch would make things materially worse or more complex — it's all opt-in. Let's create a follow-up issue, or ideally, expand the scope of the existing issue (if one exists, I hope it does!).
Comment #16
seanbWe have #610068: Document AJAX no-js and use-ajax to document it. I'll link this issue and the CR there as well.
Comment #17
larowlanThis looks ok to me, previously I've done focus stuff with the InvokeCommand - is there a reason why we can't use that here and avoid adding the additional focus logic?
Still needs FE FM review, leaving at NR
Comment #18
seanbIf I'm not mistaken that would require the URL to return an AJAX response. And that would also mean the element that should receive focus is fixed.
I think what's great about this is that you don't have to add routes or alter existing ones to load content inside an element. So even though there are other ways to do this, this would provide a lot of power and flexibility to site builders and themers via "simple" links.
Comment #19
larowlanMakes sense, thanks
Comment #20
lauriiiShould we add test coverage for this as well? Did you consider whether this should be added to the '#ajax' API as well (maybe in a follow-up)?
1. This doesn't support defining progress.type as empty which is an option supported by the current APIs. Maybe we should instead explicitly check if the data attribute exists?
2. We should probably allow providing other configuration options that are available in '#ajax' as well to get into feature parity.
Comment #21
panchoYes, I agree. We should strive for feature parity and for consistency with the Form API '#ajax' property.
This would mean:
Attributes should IMHO also be consistently named in the render array and the actual attributes output. However, we want to avoid duplication. This is not easy. But how about something like this:
which would be relatively consistent with Form Ajax API. I'm unsure if we have to do a
json_encodeat this place or how we would otherwise render this, but that's the next question. In the end, the attributes need to be prepended with data-ajax anyway.Please see also Ajax commands for opening and closing Dialogs and generic Dialog Controller added to core. Unsure if we could also use the
#ajaxproperty (['accepts' => 'application/vnd.drupal-modal']) instead of or alternatively to#attributes.Comment #22
seanb#20
1. Not sure how to test for focus? I couldn't find any existing tests doing this and/or support for this in PHP Unit.
2.1. Fixed, and added a test.
2.2 and #21
I think creating feature parity with the ajax system is a nice feature, but that is a different scope. Also looking at the request/question regarding focus options for the form API, could we do this in a separate issue?
Comment #23
seanbAhh missed one coding style issue.
Comment #24
panchore #22:
Less features (e.g. in regard to 'progress') aren't a problem, more features (e.g. in regard to the 'focus' element) might be one, and differently named/implemented features clearly are a problem for consistency.
I don't think we should introduce new inconsistencies in Core, so while in the end it's not my decision to take, I don't think it'd be a good idea to introduce new features with new options that are inconsistent with already existing features and then defer the cleanup to a later point. That would mean more cleanup work, more work with BC, more deprecations, and finally, more pressure towards leaving everything in an inconsistent state to avoid all that hassle.
So while I think consistency with existing FormAPI features should be taken care of right here, it's rather the addition of the 'focus' functionality that should be spun off to a followup issue.
But again, that's my 2 cents. It's @lauriii who is in charge for the framework coordination.
Comment #25
lauriiiSomething like this should allow you to assert if element is focused:
$this->assertTrue($this->getSession()->evaluateScript(jQuery('.element').is(":focus"))In this case, it's only about feature parity of a single property. I looked at if these settings are being utilized in core and I found that the 'message' setting is being used only in a single instance. The progress bar isn't being used anywhere. Given that, I think it would be fine to postpone supporting those to a follow-up. We should also open another follow-up for supporting 'focus' in '#ajax'.
I started wondering, what happens if returned commands try to change the focused element as well. Who will win in this situation? It seems valid use case to have conditions on which element should be focused after calculating the response, so this could theoretically happen.
Comment #26
phenaproximaThe response always wins. That's documented in the patch, I think, and in #4.
Comment #27
seanbAdded extra tests for the focus attribute and a focus related test with AJAX commands to make sure the commands take precedence as well.
Comment #28
seanbCreated #3033150: Add feature parity for consistency between AJAX links and the Form AJAX API and #3033155: Add focus attribute to Form AJAX API.
Comment #29
panchoThere it is: #3033151: Add ['#ajax']['refocus'] property to FormAPI elements. Now how do we handle the 'focus' vs. 'refocus' naming? 'focus' nicer, simpler. But with 'focus', a 'none' option doesn't make any sense, which is why I'm tending to call it 'refocus'. You however might have an idea how to solve this even better.
Comment #30
panchoOops, crossposted. I made #3033150: Add feature parity for consistency between AJAX links and the Form AJAX API the parent issue, however.
Comment #31
seanbThat's ok, added a reply to your question in #3033151: Add ['#ajax']['refocus'] property to FormAPI elements. Thanks for posting the issue!
Comment #32
panchoPlease see #2821793: Replace #ajax['wrapper'] with #ajax['wrapper_selector']. Targeting HTML classes rather than just IDs is underway for FormAPI #ajax, so we probably want to be consistent here.
Comment #33
seanbI totally agree, but I don't think that other issue is a blocker? I think we should update this issue if the other one lands first, and vice versa. Setting it back to needs review.
Comment #34
phenaproximaThis seems like 'progress' could and should be a const, set with a ternary expression.
Should be "hasn't been". Also, "ajax" should be all-caps.
This is strange, can there at least be a comment here explaining what's happening?
Comment #37
pipicom commented@seanB have tried patch #27 with Drupal 8.9.0-beta2 and the following code:
Node is being loaded as it should in the page without reload! Success!
However, the whole
<div id="content"></div>is replaced by the node content instead of it being printed *in* the<div>In other words, instead of
<div id="content">NODE CONTENT</div>I get
NODE CONTENTI tried unsuccessfully to read the patch code and perhaps amend it but had no luck :(
Could someone help me on this?
Comment #41
carsteng commentedunfortunately this is not part of D9 yet.
Comment #44
lind101 commentedIn #43 I've tried to re-roll the patch in #27 for 9.3.x.
I've applied the suggestions from #34. However I stopped short of adding a new comment to the
target = document.querySelector(..)section as this is the original code (no change), plus I think the amended comment from #27 explains well enough whats going on?I've also added a way to choose the replacement method using the
data-ajax-methodattribute (as suggested in #37), usage (Defaults toreplaceWith):This is my first contribution to core, so please let me know if there is some process I've missed!
Cheers!
Comment #46
gaëlgI've just rebased against 9.3.x
GaëlG made their first commit to this issue’s fork.
Comment #47
ranjith_kumar_k_u commentedFixed CS errors.
Comment #49
Duvan.Slabbert commentedI have applied patch #47 to my Drupal 9.4.1 installation.
I then continued to create a views page with the path set to /test. After that I created a link to call the test page and load it into a div with the id of content as follow,
but it does not seem to work. All i get is the throbber showing the page is being loaded and then after a sec the throbber disappears, but no page has been loaded.
I would really like this to work and to be able to load the views page in the div using ajax, but I think I might be missing something here. Can someone please point me in the right direction.
Comment #50
pipicom commented#47 works for me for latest Drupal 9.4.1.
@Duvan.Slabbert make sure 'core/drupal.ajax' library is loaded. Or perhaps try to load your view content in another div e.g. id="test" just for testing.
Comment #51
Duvan.Slabbert commented@pipicorn
Thank you for replying so quickly and please do excuse my ignorance, but how does one load the core/drupal.ajax library? I'm rather new to this Drupal 9 scene and still learning all the ins and outs.
Comment #52
pipicom commented@Duvan.Slabbert you are welcome.
Open the themename.libraries.yml file located inside the themename folder (themename is whatever you have named your theme) and make sure this line exists
- core/drupal.ajax. Just to make things simple add it below- core/drupal.My theme's libraries.yml includes (among others) these dependencies.
Watch out for indentation errors when working with yaml files.
Read more about the libraries.yml file: https://www.drupal.org/docs/theming-drupal/adding-assets-css-js-to-a-dru...
Comment #53
Duvan.Slabbert commentedOK, I have done a bit of research and I made a new install of Drupal 9.4.1. I continued to install W3CSS Theme V2 and saw the following in the drupal8_w3css_theme.libraries.yml file.
Am I correct in assuming that the theme is loading the library that is needed? I hope so.
After that I went ahead and created a views page with the path set to /test and for ease I just used the Frontpage view to add a "Global: Unfiltered text" with the following code in it
to the header of the view. I made sure that the ID of content was placed in the theme and also double check that both views had the "Use AJAX" value set to "Yes", but I still get the same result, throbber is spinning, after a sec it disappears with no results and no errors.
I also continued to test the link with a deferent ID, flushed all the caches and ran the crons without any success.
Comment #54
Duvan.Slabbert commentedFinally got this to work.
It was a rookie mistake. I can confirm that patch #47 works great. For anyone else who lands on this page and struggled like I did, make sure to follow @pipicorn's advice to double check if the libraries gets loaded as described in comment #52 and once you have finished applying the patch, dont just clear your cache, but clear your browser history as well. Thank you @pipicorn for your help.
Comment #55
pipicom commentedNice that everything worked out in the end 🥳
Comment #56
Duvan.Slabbert commentedJust a quick food for thoughts. How much trouble would it be to have the URL change in the browser as the user clicks on the link in order to resolve a issue where if the user refreshes the page?
Comment #57
pipicom commented@Duvan.Slabbert On an ajaxified project of mine I use the following code. Anytime an ajax link is being clicked I run this code.
Replace title_of_new_page & url_of_new_page with the title and URL of the new page to be loaded. The
document.titleis used for firefox; I noticed that without it the page title will not change to the new one on firefox. Or perhaps the way I usewindow.historyis wrong? I am not sure.Read more about the window.history API here: https://developer.mozilla.org/en-US/docs/Web/API/History
Comment #58
Duvan.Slabbert commentedI made a custom module and gave it a couple of test runs with the following code.
So far everything tests fine in Opera and Chrome, have not tested on to many platforms. The problem I have, or at least, I'm not sure if it is a problem, is once you add the code
just bellow the code
and you click on any link using the "use-ajax" class that also contains a parameter "data-ajax-wrapper" it tends to run a couple of times by displaying the "Hi" message, just as a test, the alert does not need to be there. The other problem would be how and where to incorporate this into core or the patch? Like I said, I'm still rather new to the Drupal 9 scene and kind of learning as I go.
Comment #59
oldeb@Duvan.Slabbert you should use jQuery once to avoid attaching the click event multiple times to the link.
Comment #60
oldebI have applied patch #47 to my Drupal 9.4.1 installation and it works like a charm.
Good job guys !
Comment #61
alexpottNew features need to land in 10.1.x first and this patch needs quite a bit of work to land there because JS coding standards and the whole .es6 thing have changed in Drupal 10.
Once this lands in 10.1.x we can discussed backports but since 9.5.0 is in beta it's unlikely to land there.
Comment #62
prudloff commentedHere is a reroll for 9.5.
Comment #63
_utsavsharma commentedPatch for 10.1.x.
Comment #64
ovanes commentedHello adding adjusted patch for core 9.5.x
Comment #65
b_sharpe commentedThere's some issues here with focus with:
Seeing the following error in the console:
because in the context here, "this" is actually the Window object, so focus is a function.
Comment #66
m.bkm commentedI have applied patch #64 to my Drupal 9.5.3 and I’m having the same issue and getting the same error message. Anyone have any ideas on how to fix this ?
An error occurred during the execution of the Ajax response: SyntaxError: Failed to execute ‘querySelector’ on ‘Document’: ‘function focus() { [native code] }’ is not a valid selector.Comment #68
tregonia commentedConfirming that the patch in #63 worked for my implementation of the code below on
10.1.6.When executed with the patch, the correct element is replaced as expected.
I cannot speak to any other pieces except the
data-ajax-wrapperfunctionality.Comment #69
martins.bertins commentedAdjusted patch for 10.1.x from #63.
Found that progress was not being set correctly and there was a .orig file included.
Comment #70
tregonia commentedFound out today that the patches do not apply against 10.2. I have been debugging and the apply failure is isolated to the form loop in ajax.js; or the logic that handles the focus.
I have removed that section, and resolved the apply failure. I cannot speak to whether any further changes are necessary for other concerns. Please review.
Comment #71
tregonia commentedUpdated the diff because it was not applying.
Comment #72
akalam commentedRerolled #69 for 10.2
Comment #73
akalam commentedThe wrapper ajax setting is not being considered when replacing the content. That can causes issues when the wrapper is set to something different than the content region. Here is a patch fixing it. Basically if the wrapper exist on the content inside the ajax response, we reduce the content to just the "wrapper" element. If the wrapper element is not found, we keep the content as it is, replacing the wrapper with the content from the ajax response.
Comment #74
akalam commentedPatch 73 was introducing a regression: In the context of an Ajax call, there are situations when the wrapper id is in the response, but we don't want to replace just the partial but the whole response. This is the case of the media library after adding a new media, because the div containing the media add form, has the same id as the form with the file upload at the top of the media list.
As consequence, with the patch applied, when you add a new media through the media library, the dialog gets replaced with just the file upload form, so the auto-insert feature doesn't work (because the media list doesn't get replaced).
As a solution, I'm proposing the replacement of partial response to be an opt-in (disabled by default). This setting can be activated through a data attribute (data-replace-partial="true") on specific links, so it can be used keeping the default behavior untouched.
Comment #80
mrogers commentedRebased #74 for Drupal 10.4.8
Comment #82
prudloff commentedI think this is still relevant but it might go against #3404409: [Plan] Gradually replace Drupal's AJAX system with htmx?
Comment #84
prudloff commentedIf we do this we need to be extra sure the selector can't contain a dangerous HTML payload that would be passed to $().