You are here

class TableOfContentsExtension in Markdown 8.2

Plugin annotation


@MarkdownExtension(
  id = "commonmark-table-of-contents",
  label = @Translation("Table Of Contents"),
  description = @Translation("Automatically inserts a table of contents into your document with links to the various headings."),
  libraries = {
    @ComposerPackage(
      id = "league/commonmark",
      object = "\League\CommonMark\Extension\TableOfContents\TableOfContentsExtension",
      customLabel = "commonmark-table-of-contents",
      url = "https://commonmark.thephpleague.com/extensions/table-of-contents/",
      requirements = {
         @InstallableRequirement(
            id = "parser:commonmark",
            callback = "::getVersion",
            constraints = {"Version" = "^1.3 || ^2.0"},
         ),
         @InstallableRequirement(
            id = "extension:commonmark-heading-permalink",
            callback = "::getVersion",
            constraints = {"Version" = "^1.3 || ^2.0"},
         ),
      },
    ),
  },
)

Hierarchy

Expanded class hierarchy of TableOfContentsExtension

File

src/Plugin/Markdown/CommonMark/Extension/TableOfContentsExtension.php, line 40

Namespace

Drupal\markdown\Plugin\Markdown\CommonMark\Extension
View source
class TableOfContentsExtension extends BaseExtension implements PluginFormInterface, SettingsInterface {
  use FeatureDetectionTrait;
  use SettingsTrait;

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings($pluginDefinition) {

    /* @var \Drupal\markdown\Annotation\InstallablePlugin $pluginDefinition */
    $settings = [
      'html_class' => 'table-of-contents',
      'max_heading_level' => 6,
      'min_heading_level' => 1,
      'normalize' => 'relative',
      'position' => 'top',
      'style' => 'bullet',
    ];

    // Support placeholder feature if it exists (1.5.0+).
    // @see https://github.com/thephpleague/commonmark/pull/466
    if (static::featureExists('placeholder')) {
      $settings['position'] = 'placeholder';
      $settings['placeholder'] = '[TOC]';
    }
    return $settings;
  }

  /**
   * Feature callback for whether TableOfContents supports a placeholder.
   *
   * @return bool
   *   TRUE or FALSE
   */
  protected static function featurePlaceholder() {
    return defined('\\League\\CommonMark\\Extension\\TableOfContents\\TableOfContentsBuilder::POSITION_PLACEHOLDER');
  }

  /**
   * {@inheritdoc}
   */
  public function settingsKey() {
    return 'table_of_contents';
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $element, FormStateInterface $form_state) {

    /** @var \Drupal\markdown\Form\SubformStateInterface $form_state */
    $element += $this
      ->createSettingElement('html_class', [
      '#type' => 'textfield',
      '#title' => $this
        ->t('HTML Class'),
      '#description' => $this
        ->t("Sets the <code>&lt;ul&gt;</code> or <code>&lt;ol&gt;</code> tag's class attribute."),
    ], $form_state);
    $headings = array_combine(range(1, 6), array_map(function ($value) {
      return "h{$value}";
    }, range(1, 6)));
    $element += $this
      ->createSettingElement('min_heading_level', [
      '#type' => 'select',
      '#title' => $this
        ->t('Minimum Heading Level'),
      '#description' => $this
        ->t('Headings larger than this will be ignored, e.g. if set to <code>h2</code> then <code>h1</code> headings will be ignored.'),
      '#options' => $headings,
    ], $form_state);
    $element += $this
      ->createSettingElement('max_heading_level', [
      '#type' => 'select',
      '#title' => $this
        ->t('Maximum Heading Level'),
      '#description' => $this
        ->t('Headings smaller than this will be ignored, e.g. if set to <code>h5</code> then <code>h6</code> headings will be ignored.'),
      '#options' => $headings,
    ], $form_state);
    $element += $this
      ->createSettingElement('normalize', [
      '#type' => 'select',
      '#title' => $this
        ->t('Normalize'),
      '#description' => $this
        ->t('Strategy used when generating a (potentially-nested) list of headings.'),
      '#options' => [
        'as-is' => $this
          ->t('As Is'),
        'flat' => $this
          ->t('Flat'),
        'relative' => $this
          ->t('Relative'),
      ],
    ], $form_state);
    $positions = [
      'top' => $this
        ->t('Top'),
      'before-headings' => $this
        ->t('Before Headings'),
    ];
    if (static::featureExists('placeholder')) {
      $positions = [
        'placeholder' => $this
          ->t('Placeholder'),
      ] + $positions;
    }
    $element += $this
      ->createSettingElement('position', [
      '#type' => 'select',
      '#title' => $this
        ->t('Position'),
      '#description' => $this
        ->t('Where to place table of contents.'),
      '#options' => $positions,
    ], $form_state);
    $element += $this
      ->createSettingElement('placeholder', [
      '#access' => static::featureExists('placeholder'),
      '#title' => $this
        ->t('Placeholder'),
      '#type' => 'textfield',
      '#description' => $this
        ->t('The placeholder value that will be replaced with the Table of Contents. Any lines in your document that match this placeholder value will be replaced by the Table of Contents.'),
    ], $form_state);
    $form_state
      ->addElementState($element['placeholder'], 'visible', 'position', [
      'value' => 'placeholder',
    ]);
    $element += $this
      ->createSettingElement('style', [
      '#type' => 'select',
      '#title' => $this
        ->t('Style'),
      '#description' => $this
        ->t('HTML list style type to use when rendering the table of contents.'),
      '#options' => [
        'bullet' => $this
          ->t('Unordered (Bulleted)'),
        'ordered' => $this
          ->t('Ordered (Numbered)'),
      ],
    ], $form_state);
    return $element;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AnnotatedPluginBase::$originalPluginId protected property The original plugin_id that was called, not a fallback identifier.
AnnotatedPluginBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
AnnotatedPluginBase::getConfigurationOverrides public function Retrieves the configuration overrides for the plugin. Overrides AnnotatedPluginInterface::getConfigurationOverrides
AnnotatedPluginBase::getDescription public function Retrieves the description of the plugin, if set. Overrides AnnotatedPluginInterface::getDescription
AnnotatedPluginBase::getOriginalPluginId public function Retrieves the original plugin identifier. Overrides AnnotatedPluginInterface::getOriginalPluginId
AnnotatedPluginBase::getProvider public function Returns the provider (extension name) of the plugin. Overrides AnnotatedPluginInterface::getProvider
AnnotatedPluginBase::getWeight public function Returns the weight of the plugin (used for sorting). Overrides AnnotatedPluginInterface::getWeight
AnnotatedPluginBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides PluginBase::__construct
AnnotatedPluginBase::__toString public function
BaseExtension::enabledByDefault public function Indicates the default "enabled" state. Overrides EnabledPluginTrait::enabledByDefault
BaseExtension::getConfiguration public function Gets this plugin's configuration. Overrides InstallablePluginBase::getConfiguration 1
BaseExtension::isBundled public function Indicates whether the extension is automatically installed with the parser. Overrides ExtensionInterface::isBundled
BaseExtension::register public function Allows the extension to register itself with the CommonMark Environment. Overrides ExtensionInterface::register 4
BaseExtension::requiredBy public function Retrieves identifiers of extensions that are required by this extension. Overrides ExtensionInterface::requiredBy
BaseExtension::requires public function Retrieves identifiers of extensions that this extension requires. Overrides ExtensionInterface::requires
BaseExtension::validateSettings public static function Validates extension settings.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
DependencyTrait::$dependencies protected property The object's dependencies.
DependencyTrait::addDependencies protected function Adds multiple dependencies.
DependencyTrait::addDependency protected function Adds a dependency.
EnabledPluginTrait::isEnabled public function
FeatureDetectionTrait::$features protected static property An array of test features.
FeatureDetectionTrait::featureExists protected static function Determines whether a feature exists.
InstallablePluginBase::$config protected property The config for this plugin.
InstallablePluginBase::buildLibrary public function Builds a display for a library. Overrides InstallablePluginInterface::buildLibrary
InstallablePluginBase::buildStatus public function Builds a display status based on the current state of the plugin. Overrides InstallablePluginInterface::buildStatus
InstallablePluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
InstallablePluginBase::config public function Retrieves the config instance for this plugin. Overrides InstallablePluginInterface::config
InstallablePluginBase::createConfig protected static function
InstallablePluginBase::defaultConfiguration public function Gets default configuration for this plugin. Overrides AnnotatedPluginBase::defaultConfiguration 1
InstallablePluginBase::getAvailableInstalls public function Retrieves available installs.
InstallablePluginBase::getConfigurationName protected function Returns the configuration name for the plugin.
InstallablePluginBase::getConfigurationSortOrder protected function Determines the configuration sort order by weight. 1
InstallablePluginBase::getContainer public function Retrieves the container.
InstallablePluginBase::getDeprecated public function Retrieves the deprecation message, if any. Overrides InstallablePluginInterface::getDeprecated
InstallablePluginBase::getExperimental public function Retrieves the experimental message. Overrides InstallablePluginInterface::getExperimental
InstallablePluginBase::getInstalledId public function Retrieves the composer package name of the installable library, if any. Overrides InstallablePluginInterface::getInstalledId
InstallablePluginBase::getInstalledLibrary public function Retrieves the installed library used by the plugin. Overrides InstallablePluginInterface::getInstalledLibrary
InstallablePluginBase::getLabel public function Displays the human-readable label of the plugin. Overrides AnnotatedPluginBase::getLabel
InstallablePluginBase::getLink public function Retrieves the plugin as a link using its label and URL. Overrides InstallablePluginInterface::getLink
InstallablePluginBase::getObject public function @TODO: Refactor to use variadic parameters. Overrides InstallablePluginInterface::getObject
InstallablePluginBase::getObjectClass public function Retrieves the class name of the object defined by the installed library. Overrides InstallablePluginInterface::getObjectClass
InstallablePluginBase::getPluginDependencies protected function 1
InstallablePluginBase::getPreferredLibrary public function Retrieves the preferred library of the plugin. Overrides InstallablePluginInterface::getPreferredLibrary
InstallablePluginBase::getSortedConfiguration public function Retrieves the configuration for the plugin, but sorted. Overrides InstallablePluginInterface::getSortedConfiguration
InstallablePluginBase::getUrl public function Retrieves the URL of the plugin, if set. Overrides InstallablePluginInterface::getUrl
InstallablePluginBase::getVersion public function The current version of the plugin. Overrides InstallablePluginInterface::getVersion
InstallablePluginBase::getVersionConstraint public function
InstallablePluginBase::hasMultipleLibraries public function Indicates whether plugin has multiple installs to check. Overrides InstallablePluginInterface::hasMultipleLibraries
InstallablePluginBase::isInstalled public function Indicates whether the plugin is installed. Overrides InstallablePluginInterface::isInstalled
InstallablePluginBase::isPreferred public function Indicates whether the plugin is using the preferred library. Overrides InstallablePluginInterface::isPreferred
InstallablePluginBase::isPreferredLibraryInstalled public function Indicates whether the preferred library is installed. Overrides InstallablePluginInterface::isPreferredLibraryInstalled
InstallablePluginBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides AnnotatedPluginBase::setConfiguration 3
InstallablePluginBase::showInUi public function Indicates whether the plugin should be shown in the UI. Overrides InstallablePluginInterface::showInUi
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
MoreInfoTrait::moreInfo protected function Appends existing content with a "More Info" link.
ParserAwareTrait::$parser protected property A Markdown Parser instance.
ParserAwareTrait::getParser public function 1
ParserAwareTrait::setParser public function
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginDependencyTrait::calculatePluginDependencies protected function Calculates and adds dependencies of a specific plugin instance.
PluginDependencyTrait::getPluginDependencies protected function Calculates and returns dependencies of a specific plugin instance. Aliased as: getPluginDependenciesTrait
PluginDependencyTrait::moduleHandler protected function Wraps the module handler.
PluginDependencyTrait::themeHandler protected function Wraps the theme handler.
RendererTrait::$renderer protected static property The Renderer service.
RendererTrait::renderer protected function Retrieves the Renderer service.
SettingsTrait::createSettingElement protected function Creates a setting element.
SettingsTrait::getDefaultSetting public function
SettingsTrait::getSetting public function
SettingsTrait::getSettingOverrides public function
SettingsTrait::getSettings public function
SettingsTrait::settingExists public function 2
SettingsTrait::submitConfigurationForm public function
SettingsTrait::validateConfigurationForm public function 2
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
TableOfContentsExtension::buildConfigurationForm public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm
TableOfContentsExtension::defaultSettings public static function Provides the default settings for the plugin. Overrides SettingsTrait::defaultSettings
TableOfContentsExtension::featurePlaceholder protected static function Feature callback for whether TableOfContents supports a placeholder.
TableOfContentsExtension::settingsKey public function The array key name to use when the settings are nested in another array. Overrides SettingsTrait::settingsKey