Template encapsulation happens in three steps.

  1. findWrappableTemplateRanges

    Locate start and end metas. Walk upwards towards the root from both and find a common ancestor A. The subtree rooted at A is now effectively the scope of the dom template ouput.

  2. findTopLevelNonOverlappingRanges

    Mark all nodes in a range and walk up to root from each range start to determine overlaps, nesting. Merge overlapping and nested ranges to find the subset of top-level non-overlapping ranges which will be wrapped as individual units.

    range.startElem, range.endElem are the start/end meta tags for a transclusion range.start, range.end are the start/end DOM nodes after the range is expanded, merged with other ranges, etc. In the simple cases, they will be identical to startElem, endElem.

  3. encapsulateTemplates

    For each non-overlapping range,

    • compute a data-mw according to the DOM spec
    • replace the start / end meta markers with transclusion type and data-mw on the first DOM node
    • add about ids on all top-level nodes of the range

This is a simple high-level overview of the 3 steps to help understand this code.

FIXME: At some point, more of the details should be extracted and documented in pseudo-code as an algorithm.