Page MenuHomePhabricator

"wikipage.content" JS hook: $content should be consistent on live previews
Open, Needs TriagePublic

Description

Boilerplate code:

mw.hook( 'wikipage.content' ).add( $content => console.log( $content ) );

What element $content contains:

  • When viewing a page: #mw-content-text
  • When editing a page - no preview: #mw-content-text
  • When editing a page - during a regular preview: #mw-content-text
  • When editing a page - during a live preview: .mw-content-ltr ⚠️

This should be made consistent. Case in point, a bug varying whether live preview is enabled or not, would be quite unexpected and hard to spot.

Note that on edit pages, #mw-content-text also contains the edit interface, whereas .mw-content-ltr contains only the wiki page content. Though, I think we should unify to #mw-content-text, if we consider that on an edit page, the "page content" is actually the edit interface, which may include a page preview. Also, that's what the regular previews (probably much more widespread) already do.

By the way, there is still no element designed for getting just the wiki page content… So far, I'm mainly using $content / #mw-content-text, but have already encountered several, quite unexpected issues (for example on diff pages), that I solved by adding a .find( '.mw-parser-output' ) (and $( '.mw-parser-output' ) can't be used directly, as .mw-indicators also contains an occurrence of it).

Some refs:

Event Timeline

I don't think Parsoid is related here -- the classes you name here are part of the core OutputPage/ParserOutput mechanism. Parsoid is just matching legacy output.

It seems that the wikipage.content hook is doing exactly the right thing, you're just complaining that you'd rather use document.getElementId('mw-content-text') and have that always work?

I have just encountered an issue in a gadget because of this discrepancy: https://fr.wikipedia.org/w/index.php?title=MediaWiki:Gadget-Accessibility.js&diff=prev&oldid=212995332

(edit: then followed by https://fr.wikipedia.org/w/index.php?title=MediaWiki:Gadget-Accessibility.js&type=revision&diff=212999820&oldid=212995448, as there was another confusion because the hook is run at least once on all pages, even when there is no page content)

By the way, I just noticed that when running mw.hook('wikipage.content').add($content => ...) in the visual editor, the $content element is completely unrelated to the page content, see File:Hook_param_$content_in_visual_editor.png.

The problem is that the topmost known element is config.$previewNode, which is the #wikiPreview element (unless configured somehow else, but I'm not aware of any occurrence of such tweak).

As a reminder, currently the hierarchy is #mw-content-text > .mw-content-ltr.mw-parser-output in regular pages, and #mw-content-text > #wikiPreview > .mw-content-ltr.mw-parser-output in previews.

To provide the #mw-content-text element to the hook's $content parameter, I would suggest to :

  • Do $previewNode.closest( '#mw-content-text' )
  • And if for any reason this element is not found (which shouldn't happen), use the $previewNode element, as a fallback. Using $previewNode (i.e. #wikiPreview) would be less worse than using the current .mw-content-ltr.mw-parser-output, because doing $content.find( '.mw-parser-output' ) with the former would give a result, whereas the latter doesn't give a result, as the queried element is actually the $content element, not a child of it.

@Od1n Is there a functional problem here in terms of what a gadget is able to do or observe?

Consistency is imho not a problem by itself here, since that is very much a matter of perspective. I do not believe that the $content parameter must always hold an element with the same HTML ID. If such outcome were feasible, the hook would not need to exist, or at least would not need to have such a parameter. The reason this parameter exists is precisely so that extensions and gadgets do not have to be aware of (intentional) differences with how, where and why content is presented and rendered in a certain context. Instead, you get the parameter and it will refer to wherever the content was rendered this time.

Other examples where "consistency" is incompatible with the hook being useful:

  • WikiEditor extension, real-time preview split view on the side, while the rest of the edit page is still there above it.
  • MediaWiki core, gallery re-rendering.
  • VisualEditor modal preview of part of a page, while the whole page is also there in the background.
  • VisualEditor, TOC widget.

I would also include here the item you mentioned, which is MediaWiki core's live preview. There #mw-content-text is used, as always, for "consistency", to refer to the OutputPage as generated by the current route handler (whether that be ViewAction, EditAction, HistoryAction, or a SpecialPage). In other words, all output that isn't controlled by the Skin. This is a contract and requirement for various other parts of the system. In case of an EditAction/EditPage, that means only a portion of #mw-content-text is the editable wikitext rendering. And, "for consistency", the wikipage.content thus here give you access to only that portion, just like it always does.

On a related note, for the extensions in charge of rendering this content and firing this hook for you, they also hace the responsiblity of making sure mw-content-ltr and mw-parser-output are always applied to this element (or a parent element) for correct skin styling, TemplateStyles, and gadget support.

However, afaik there is no documentation, or promise, or indeed known use case, for why a consumer of wikipage.content would care what ID or class is set on the $content itself. Can you give a bit more context on what how you are using this hook, and why this poses a problem? I suspect there may be a misunderstanding somewhere, and there's probably a very similar way that would work instead without any of these complexities involved.

There are two issues discussed here, I'll try to answer about them separately.

First, there is the issue that $content parameter in the wikipage.content hook doesn't contain the parsed content, but an upper element, containing the "main" page content (all pages have a main content, including special pages, history pages, and so on). It's fine by itself, but: 1) many codes have been written overlooking this fact, and 2) there is still no selector to just get the parsed content, which is most often what people want (thus, don't be surprised if people use .mw-content-ltr, that's because they think it's their best available option).

I have encountered many cases where #mw-content-text (i.e. $content) is too broad, and I had to restrict to #mw-content-text .mw-parser-output, for instance:

And overall, it just feels really wrong to process elements that are not the parsed content, when the intent is to specifically process the parsed content.

I had thought about it, and I think the best would be to add a new hook, like wikipage.parserContent, whose $parserContent parameter would be the parsed content. Of course, the hook wouldn't be triggered when there is no such content (history pages, etc.)


Now, quickly back to the initial issue of this ticket, the fact that the element is different on live previews. Currently I have to add code specifically because of this issue, and at parts that I would have preferred to not complexify.

function getPageContentElement( $content = null ) {
    if ( $content ) {
        if ( $content.is( '.mw-parser-output' ) ) {
            // $content is already the .mw-parser-output element, [[phab:T349298]]
            return $content;
        } else {
            // it may find no element, in particular if it's
            // an edit page that doesn't have a preview yet
            return $content.find( '.mw-parser-output' );
        }
    } else {
        // it may find no element, in particular if it's
        // an edit page that doesn't have a preview yet
        return $( '#mw-content-text' ).find( '.mw-parser-output' );
    }
}

to this:

function getPageContentElement( $content = null ) {
    if ( !$content ) {
        $content = $( '#mw-content-text' );
    }
    // it may find no element, in particular if it's
    // an edit page that doesn't have a preview yet
    return $content.find( '.mw-parser-output' );
}
let $pageContent;

const $parserOutput = $content.find( '.mw-parser-output' );
if ( $parserOutput.length ) { // the element that has the page content
    $pageContent = $parserOutput;
} else if ( $content.hasClass( 'mw-parser-output' ) ) { // [[phab:T349298]]
    $pageContent = $content;
} else { // no page content (history pages, special pages, etc.)
    return;
}

to this:

const $pageContent = $content.find( '.mw-parser-output' );

if ( !$pageContent.length ) {
    // no page content (history pages, special pages, etc.)
    return;
}

Of course, solving the first issue (for example by adding a hook as I suggested) would be even better, and the above codes could be further simplified, to one-liners, and more future-proof.

Since then, I am still encountering annoyances because of these issues, on a regular basis.

I was about to suggest adding a new hook, dedicated to parser output, but actually I have already suggested this. I think it's really the way to go.

To provide a visual representation:

mw.hook('wikipage.content')mw.hook('wikipage.parsercontent')
page viewsfired, providing #mw-content-text elementfired, providing #mw-content-text .mw-parser-output element
edit pages (not having a preview)fired, providing #mw-content-text elementnot fired
edit pages (having a preview)fired, providing #mw-content-text elementfired, providing #mw-content-text .mw-parser-output element
history pagesfired, providing #mw-content-text elementnot fired
special pagesfired, providing #mw-content-text elementnot fired

Quick note, the code comment here is wrong:

@param {jQuery} $content The most appropriate element containing the content, such as #mw-content-text (regular content root) or #wikiPreview (live preview root)

Because in live previews (and only in that case), $content is the .mw-parser-output element (as I've already stated… it's the subject of this ticket). Not #wikiPreview as documented. See here:

$content = $( $.parseHTML( response.parse.text ) );
config.$previewNode.append( $content ).show();
mw.hook( 'wikipage.content' ).fire( $content );

I have already reported this here: https://phabricator.wikimedia.org/T349298#9656199

At the very least, the last line should be replaced with:

mw.hook( 'wikipage.content' ).fire( config.$previewNode );

But considering that mw.hook( 'wikipage.content' ) just provides the "whole content" element (#mw-content-text) on all pages, which includes edit forms, page histories, and so on, #mw-content-text would be more adequate in live previews too, rather than #wikiPreview. That would additionally include some preview banners and the edit form. Using #mw-content-text or #wikiPreview might be debatable, but for sure the former would bring more consistency, and client codes should work with both (we should not assume that .mw-parser-output is a direct child).

Because we can confidently assume the #mw-content-text element exists (as it's so fundamental), we could simply do:

mw.hook( 'wikipage.content' ).fire( $( '#mw-content-text' ) );

it just feels really wrong to process elements that are not the parsed content

The elements are parsed content, just not the main article body. Edit notices are parsed wikitext content, as are section previews and the other things @Krinkle mentions above. All of these may require plugins to be aware of them rendering (e.g. if they contain a sortable table) so we try to fire the wikipage.content whenever parsed content is rendered. If you want to know if the $content is specifically the main article body, then hook listeners can perform those checks themselves (e.g. in DiscussionTools we check:

if ( $content.is( '#mw-content-text' ) || $content.find( '#mw-content-text' ).length ) { ...

I'm not sure we need a new hook just to provide this simple check...

The most specific selector for parsed content is always .mw-parser-output. I'm not sure what's the point of the hook returning more than that (maybe just legacy; it predates the parser-output class) but I doubt it would be worth the disruption to change that - it's easy for clients to drill down.

The wikipage.content hook notifies subscribers about new elements holding "content".

During page views, or post-edit, this will be the entire content area. Typicallly #mw-content-text since that's most stable across skins on page views, and has the benefit of not containing something that isn't considered "wiki page content".

During edits and previews, this is different because on action=edit (and also special pages) the skin's concept of "content" maps to a user interface that includes lots of other things. Hence a more specific element is used instead. This way, it will not wrongly notify about the same elements multiple times. Only the portion that is new is handed to the subscriber. This avoids corruption and bugs from binding the same element multiple times.

This is indeed "inconsistent" if you look at the complete DOM, but that's on purpose, and it should not be relevant to subscribers where in the DOM the passed parameter might be. That's why it is a parameter after all. If the caller was supposed to know and care about where it is, you can use $('#mw-content-text') instead, you don't need a hook parameter to do that.

Where this makes the most sense, and thus how the current implememtation is at the same time "consistent" is that it is consistently passing new elements that hold content. These can appear anywhere.

Other examples, as found via Codesearch:

  • mediawiki.special.upload: Not a page view, specific elemenet.
  • RCFilters: Not a page view, specific element.
  • DiscussionTools: New comment.
  • MobileFrontend: Modal context outside pageview, previewing, outside content area.
  • VisualEditor: If using "new wikitext editor" mode, modal preview, outside content area.
  • VisualEditor: Modal rendering of partial pieces of content, outside content area.
  • Translate: Message documentation, outside content area.

Being consisitent about passing what is new, is an important thing to be consistent about, because it's something you as subscriber can't know otherwise. This is unique information being passed through from the code that knows (producer/renderer) to code that doesn't/can't/shouldn't know (consumer/subscriber, reacting to new content).

While I recognise that it may seem inconsistent to pass different concrete elements, what is the practical problem here? What kind of problem or difficulty are you experiencing today in a user script or gadget with mw.hook('wikipage.content').add()? I'd like to know because I'm curious how that same script behaves in the above scenarios. It seems like it shouldn't be causing a problem. If it is, we may want to focus on that instead, of on what DOM position is being passed to the hook, which is very much on purpose.

I've re-read the comment thread, and I missed T349298#9675438:

[…] I have encountered many cases where #mw-content-text (i.e. $content) is too broad, and I had to restrict to #mw-content-text .mw-parser-output, […]

As per the other comments, passing a narrower element than today would break other things. And, I believe you're also asking at the same time for broader than today for cases where we pass a sub section. That would cause double binding or missed updates for other people.

If your particular gadget needs to exclude element soutside .mw-parser-output, this can be done as follows, with less complexity than your current workarounds:

mw.hook( 'wikipage.content' ).add( function ( $content ) {
  // Anywhere in content area
  var $x = $content.find( '.mything' );

  // Exclude certain edge cases
  var $x = $content.find( '.mything' ).filter( '.mw-parser-output *' );

Note that this doesn't involve any is(), find() or hasClass(). The filter is applied based on the absolute identity of the found elements.

If your particular script musn't act on elements outside .mw-parser-output, would this work for you?

(TL;DR: The following message doesn't bring much value. Just writing down some notes.)

Many codes date from the age of addOnloadHook(). Much later, a handful of them have been modified (on frwiki, mostly by myself) to be compatible with Live preview. At that time, dynamic tools such as VisualEditor, DiscussionTools, etc. were not as much of concern as nowadays.

Firing wikipage.content hook makes sense in all these new cases (BTW, thanks for the listing), as indeed some wikitext is parsed and displayed. Though, it adds up to the things to be kept in mind, also it might cause performance issues in the case of DiscussionTools case (it's basically fired at each character input).

I was about to mention an issue that I recently encountered, with DiscussionTools and a function that alters content (namely, #catlinks) that is outside the $content element. See 218852982 and 218853314. The function recently had been made compatible with Live preview, which replaces #catlinks on each preview. But on the other hand it was not compatible with DiscussionTools, and probably other tools, as you have listed a handful of them above. Note that afterwards, I have fixed this particular function for good, and easily, thanks to the wikipage.categories hook: 218880054/218883767.

It might be more tricky with some other functions that alter stuff outside $content, namely "transformeEnPageDeDiscussion", "rewritePageTitle", "sousTitreH1" and "rewritePageH1bis". I think the best would be to not execute such functions in VisualEditor, DiscussionTools, etc. Only in regular page views, edit previews, and maybe also in Live previews, but no other dynamic tool. Maybe adding some if (mw.config.get('wgAction') === 'edit') condition would do the work (… but what about regular views?), I haven't looked into it yet.

So, $content may be various kind of element, as long as it contains page content (whether parsed or not). And in turn, parsed content is encapsulated in a .mw-parser-output div.

Thus, $content may contain a .mw-parser-output element (if there is parsed content), possibly amongst other stuff. Also, the .mw-parser-output element may be a direct child or a deeper nested child, and let's be crazy, there could even be multiple .mw-parser-output elements.

BUT, and that's the point of this message, $content should not be the .mw-parser-output element itself. $content is a container, it should not be mixed up with what it contains.


Case in point, there is the code comment that I referenced above,

And look at this change:

-		$content.html( response.parse.text );
+		$content = $( $.parseHTML( response.parse.text ) );

Previously, in live previews, $content was the #wikiPreview element actually! Whether is was intentional (but oversighting the effects) or not, $content being the .mw-parser-output element clearly seems to be a regression.

We should bring back $content to being #wikiPreview, and according to your answers, you should agree with this.

It would be a great step forward, as it would allow to remove that workaround.

Then, considering the variety of tools that run this hook actually, I would happily accept the rest: $content that can be other elements than #mw-content-text, and having to target .mw-parser-output when only wikitext content should be processed.

If your particular gadget needs to exclude element soutside .mw-parser-output, this can be done as follows, with less complexity than your current workarounds:

mw.hook( 'wikipage.content' ).add( function ( $content ) {
  // Anywhere in content area
  var $x = $content.find( '.mything' );

  // Exclude certain edge cases
  var $x = $content.find( '.mything' ).filter( '.mw-parser-output *' );

Note that this doesn't involve any is(), find() or hasClass(). The filter is applied based on the absolute identity of the found elements.

If your particular script musn't act on elements outside .mw-parser-output, would this work for you?

The filter is executed on each element, and as I was expecting, the performances are not great:

(function () {
    let i, nb = 1000;
    let $content = $( '#mw-content-text' );

    let T1 = new Date();
    for ( i = nb; i--; ) {
        $content.find( 'a' );
    }
    let T2 = new Date();
    for ( i = nb; i--; ) {
        $content.find( '.mw-parser-output' ).find( 'a' );
    }
    let T3 = new Date();
    for ( i = nb; i--; ) {
        $content.find( 'a' ).filter( '.mw-parser-output *' );
    }
    let T4 = new Date();

    console.log( T2 - T1 );
    console.log( T3 - T2 );
    console.log( T4 - T3 );
})();

For example on this page, for 1000 iterations (results in ms, less is better):

104
96
622

As I exposed in my preceding message, I think the proper solution would be to be able to confidently do $content.find( '.mw-parser-output' ) when such targetting is needed.

Change #1076285 had a related patch set uploaded (by Gerrit Patch Uploader; author: Anne Haunime):

[mediawiki/core@master] Live preview: wrap parser output in a container, to be used as hook's parameter

https://gerrit.wikimedia.org/r/1076285

There is also the consideration that $content has to be a new element at each preview, to avoid multiple-binding issues. You had mentioned it in T349298#10170212, but it's something I had overlooked so far.

By the way, I would be interested to know situations where this "multiple-bindings" issue may occur.

The patch I submitted takes care of it, by adding a container dedicated to contain preview's content.

Classic previews:

#mw-content-text ← hook's $content
    #wikiPreview
        .previewnote
        .mw-parser-output

Live previews (before patch):

#mw-content-text
    #wikiPreview
        .previewnote
        .mw-parser-output ← hook's $content

Live previews (after patch):

#mw-content-text
    #wikiPreview
        .previewnote
        .mw-preview-content ← hook's $content
            .mw-parser-output

I really don't like the .filter( '.mw-parser-output *' ) proposal, as it feels wrong to run a filter on each and every element. Also, it would be easy to forget to use it.

Just to mention another solution, that makes use of jQuery's addBack():

$content.find( '.mw-parser-output' ).addBack( '.mw-parser-output' )

But I don't like it either…

And yet another alternative… that I don't like either:

( $content.is( '.mw-parser-output' ) ? $content : $content.find( '.mw-parser-output' ) )
    .find( 'ul' )

Also, when we want to additionally process special pages, these various codes above (filter, addBack...) wouldn't let simplify the code here, whereas with the suggested solution (wrap .mw-parser-output), we could simplify to the following:

if ( $content.find( '.mw-parser-output' ).length ) {
    return $content;
} else if ( mw.config.get( 'wgNamespaceNumber' ) === -1 ) {
    return $content;
} else {
    return false; // or $(), empty jQuery object
}

Which I like, as it clearly shows there are two different supported cases: parser outputs, and special pages.

Change #1076285 abandoned by Hashar:

[mediawiki/core@master] Live preview: wrap parser output in a container, to be used as hook's parameter

https://gerrit.wikimedia.org/r/1076285

Change #1076285 restored by Thcipriani:

[mediawiki/core@master] Live preview: wrap parser output in a container, to be used as hook's parameter

https://gerrit.wikimedia.org/r/1076285

[…] $content should not be the .mw-parser-output element itself. $content is a container, it should not be mixed up with what it contains.

My understanding is that the use case of these gadgets is: find elements created from wikitext that match a selector,, then enhance these in some way, and repeat this no matter where or when MediaWiki renders elements from wikitext. The wikipage.content exists exactly for this use case.

mw.hook( 'wikipage.content', function ( $content ) {
    myEnhancer( $content.find( '.mystuff' ) );
}

[…] It would be a great step forward, as it would allow to remove that workaround. […] Also, when we want to additionally process special pages, these various codes above (filter, addBack...) wouldn't let simplify the code here […].

Both of these scripts have a getPageContent function that zooms out from $content before finding elements. Can these use $content directly?

For a gadget that builds a skin-level feature for the page as a whole (e.g. TOC) I understand is simpler to re-generate than to compute a partial change. In those cases, you might want to ignore $content and use the hook only as a notification to re-render based on your own $('#mw-content-text') and ignore everything else. If you have to optimize it further, you could skip cases where $content.find('.mw-heading').length === 0`. That might be over-optimising, however.

I'm afraid I don't understand how this patch helps the two gadgets. It seems to make no difference whether the elements are wrapped in an additional container or not. I'd prefer live preview not deviate from regular page view more than necessary.

[…] there are two different supported cases: parser outputs, and special pages.

Special pages render wikitext as well. For example:

If your use case isn't applicable to headings on special pages, that's okay. You can skip that namespace. I'd recommend checking the namespace at a higher level, before starting anything related to the gadget in question:

if ( mw.config.get( 'wgCanonicalNamespace' ) === 'Special' ) {
  return;
}
mw.hook( 'wikipage.content', function.. );

Or:

if ( mw.config.get( 'wgCanonicalNamespace' ) !== 'Special' ) {
   mw.hook( 'wikipage.content', function.. );
}

This is similar to how you might skip File pages, Category pages, or User_talk page. They also use headings in somewhat unique ways. It's up to you.

It feels like we are over-complicating the core issue.

The goal for most gadget developers is simple: target rendered wikitext while avoiding interface elements.

The standard, performant way to do this is $content.find( '.mw-parser-output' ). This works perfectly in almost every context—except for Live Preview, where $content is the .mw-parser-output element.

This creates an inconsistent leaky abstraction. Developers are currently forced to write verbose, defensive wrappers just to handle this one specific workflow.

This patch ensures $content is consistently a container of the rendered wikitext (if there is one). This restores the "contract" of the hook and allows for clean, one-line implementations that work reliably across the entire site.

As a reminder, as I suggested previously, there would also be the better solution of adding a hook for parser content:

  • wikipage.content: Stays as the broad "notification" for any UI change.
  • wikipage.parserContent: Specifically provides the .mw-parser-output element, firing only when wikitext is actually rendered.