Commit c2f5d149 authored by Stephen Mulvihill's avatar Stephen Mulvihill Committed by Vladimir Roudakov
Browse files

Issue #3262302 by smulvih2, VladimirAus: Exclude text above [toc] token when building TOC

parent e94a7f93
Loading
Loading
Loading
Loading
+23 −1
Original line number Diff line number Diff line
@@ -34,6 +34,7 @@ use Drupal\toc_api\Entity\TocType;
 *     "type" = "default",
 *     "auto" = FALSE,
 *     "block" = FALSE,
 *     "exclude_above" = FALSE,
 *   },
 * )
 */
@@ -54,6 +55,7 @@ class TocFilter extends FilterBase {
      '#options' => $types,
      '#default_value' => $this->settings['type'] ?: 'default',
    ];

    $form['auto'] = [
      '#title' => $this->t('Automatically include table of contents'),
      '#description' => $this->t('If set, a table of contents will be added when a <code>[toc]</code> token is not present in the content.'),
@@ -65,12 +67,21 @@ class TocFilter extends FilterBase {
      ],
      '#default_value' => $this->settings['auto'],
    ];

    $form['block'] = [
      '#title' => $this->t('Display table of contents in a block.'),
      '#description' => $this->t('Please make sure to place the <a href=":href">TOC filter</a> block on your site.', [':href' => URL::fromRoute('block.admin_display')->toString()]),
      '#type' => 'checkbox',
      '#default_value' => $this->settings['block'],
    ];

    $form['exclude_above'] = [
      '#title' => $this->t('Exclude text above the TOC'),
      '#description' => $this->t('If selected, the text above the <code>[toc]</code> token will not be considered when building the TOC.'),
      '#type' => 'checkbox',
      '#default_value' => $this->settings['exclude_above'],
    ];

    return $form;
  }

@@ -149,6 +160,12 @@ class TocFilter extends FilterBase {
    /** @var \Drupal\toc_api\TocInterface $toc */
    $toc = $toc_manager->create('toc_filter', $text, $options);

    if ($this->settings['exclude_above']) {
      // Remove text before the [toc] token when building TOC
      $toc_text = strstr($text, $match[0]);
      $toc_exclude_above = $toc_manager->create('toc_filter', $toc_text, $options);
    }

    // If table of content is not visible, return the unprocessed result w/o
    // the [toc] token.
    if (!$toc->isVisible()) {
@@ -162,9 +179,14 @@ class TocFilter extends FilterBase {
    if ($toc->isBlock()) {
      $text = str_replace($match[0], '', $text);
    }
    else {
      if ($this->settings['exclude_above']) {
        $text = str_replace($match[0], $toc_builder->renderToc($toc_exclude_above), $text);
      }
      else {
        $text = str_replace($match[0], $toc_builder->renderToc($toc), $text);
      }
    }

    return $result->setProcessedText($text);
  }