npm.io
4.0.0 • Published 2d ago

@diplodoc/tabs-extension

Licence
MIT
Version
4.0.0
Deps
2
Size
579 kB
Vulns
0
Weekly
0
Stars
2

english | русский


NPM version Quality Gate Status Coverage Maintainability Rating Reliability Rating Security Rating

Diplodoc tabs extension

This is an extension of the Diplodoc platform, which allows adding switchable tabs in the documentation.

The extension contains some parts:

Quickstart

Attach the plugin to the transformer:

import tabsExtension from '@diplodoc/tabs-extension';
import transform from '@diplodoc/transform';

const {result} = await transform(
  `
{% list tabs %}

- Tab 1
- Tab 2
- Tab 3

{% endlist %}
`,
  {
    plugins: [tabsExtension.transform({bundle: false})],
  },
);

Prepared runtime

It is necessary to add runtime scripts to make tabs interactive on your page.
You can add assets files which were generated by the MarkdownIt transform plugin.

<html>
  <head>
    <!-- Read more about '_assets/tabs-extension.js' and '_assets/tabs-extension.css' in 'Transform plugin' section -->
    <script src="_assets/tabs-extension.js" async></script>
    <link rel="stylesheet" href="_assets/tabs-extension.css" />
  </head>
  <body>
    ${result.html}
  </body>
</html>

Or you can just include runtime's source code in your bundle.

import '@diplodoc/tabs-extension/runtime';
import '@diplodoc/tabs-extension/runtime/styles.css';

MarkdownIt transform plugin

Plugin for @diplodoc/transform package.

Options:

  • runtimeJsPath - name on runtime script which will be exposed in results script section.
    Default: _assets/tabs-extension.js

  • runtimeCssPath - name on runtime css file which will be exposed in results style section.
    (Default: _assets/tabs-extension.css)

  • bundle - boolean flag to enable/disable copying of bundled runtime to target directory.
    Where target directory is <transformer output option>/<plugin runtime option>
    Default: true

  • containerClasses - additional classes which will be added to tab's container node. It allows to customize the tabs view.
    Example: my-own-class and-other-class
    Default: undefined

Colon directive syntax

Legacy {% list tabs %} remains the standalone default. Opt in at factory creation with transform({directiveSyntax: 'enabled'}) to accept both forms, or use directiveSyntax: 'only' for colon directives only. The default 'disabled' retains the legacy-only, core-rule host contract; enabling a directive requires a Markdown-it host with the block and inline capabilities used by @diplodoc/directive.

:::tabs {variant=radio group="shared"}

- First

  First body.

- Second {selected}

  Second body.

:::

The body uses the same Markdown lists and selected markers as legacy tabs. variant is regular (the default), radio, dropdown, or accordion; group, if present, must be nonempty. A valid but disabled variant falls back to regular. Titles, destinations, unknown or repeated attributes, #id and .class are unsupported. Invalid parameters remain ordinary Markdown. An optional onDiagnostic({line, reason}) reports rejected parameters with a one-based line; it is not a general Markdown validator and does not promise a diagnostic for every malformed or unclosed marker. Directive attributes do not require general Markdown attributes to be enabled.

Observe item source titles

Pass onItemSource(snapshot) to transform to observe each accepted tab item before its markup is generated, in both legacy and colon syntax. The callback receives a frozen snapshot with rawName, a copied inlineMap, and a nullable containerMap bounded by the owner's opening and closing token maps. Line maps refer to the current normalized Markdown input and use zero-based, exclusive end lines; they are not guaranteed offsets into an original file. Character spans are zero-based UTF-16 offsets in rawName, with exclusive ends.

For kind: 'ok', markers identifies the first custom anchor, the first literal {selected} used for activation in the original title, and the first literal removed from the display title after the anchor is removed. These ranges can overlap or differ. kind: 'unsupported' reports missing-title or discontinuous-display-marker; consumers should conservatively preserve the affected source. Maps can be null and a consumer must establish an unambiguous mapping to its own source before editing it. The callback may be called again on later or nested parses and its exceptions propagate to the caller.

Inspect legacy boundaries

The pure @diplodoc/tabs-extension/plugin entry exports recognizeTabsBoundary(tokens, index) alongside transform. Pass original normalized block tokens before semantic core plugins run. The helper returns a readonly observation with a copied line map and raw source marker, or undefined when the candidate is not a recognized legacy boundary. An opening reports whether a variant or group was authored; an authored group includes its raw spelling and the value decoded by the existing Tabs parser. Unknown, repeated, or ambiguous parameters are reported as unsupported. Missing group and variant are distinct from explicitly authored defaults.

This observes one edge at a time, including unclosed openings. It does not pair boundaries, validate nesting or body eligibility, allocate a default group ID, render tokens, or modify the input. A caller that rewrites source must verify matching scopes and renderer equivalence separately; line maps refer to the parser's normalized input, not original byte offsets.

API

Syntax

You can synchronize the opening of tabs between different tabs groups on the page. To do this, you just need to add optional property group=<group_key> in list tab command. The active tabs with the same keys in one tabs group will be synchronized.

Example:

{% list tabs group=group_1 %}

- Tab 1
- Tab 2
- Tab 3

{% endlist %}

{% list tabs group=group_1 %}

- Tab 1
- Tab 2
- Tab 3

{% endlist %}

Additionally, you can use different render modes with:

{% list tabs <regular | radio | dropdown | accordion> %}

  - Tab 1

    Text 1.

    * You can use list
    * And **other** features.

  - Tab 2

    Text 2.

{% endlist %}

The keys for the tabs are generated automatically. They are based on the tab's names using the github anchors style.

You can set your own keys for tabs with this statement:

{% list tabs group=group_1 %}

- Tab 1 {#my-tab-1}
- Tab 2 {#my-tab-2}

{% endlist %}

React component for easy installation

import {TabsRuntime} from '@diplodoc/tabs-extension/react';

// ...
render() {
    return (
        <>
          <TabsRuntime
              saveTabsToLocalStorage={true}
              saveTabsToQueryStateMode='page'
              router={router} // optional
          />
        </>
    );
}

Or you can use React hook for smart control

You can use the React hook to handle active tab changing or to select opened tabs programmatically.

import type { UseDiplodocTabsCallback, Tab } from '@diplodoc/tabs-extension/react';

import React, { useEffect, useCallback } from 'react';
import { useDiplodocTabs } from '@diplodoc/tabs-extension/react';

export const App: React.FC = () => {
    // Callback function to handle tab selection
    const selectTabHandler = useCallback<UseDiplodocTabsCallback>(
        (tab: Tab, currentTabId?: string) => {
            const { group, key } = tab;
            // Group could be empty
            if (group) {
                // Handle tab selection in a specific group
                console.log(`Selected tab with group: ${group} and key: ${key}`);
            } else {
                // Handle tab selection without a specific group
                console.log(`Selected tab with key: ${key}`);
            }
        },
        [],
    );

    // Initialize the tabs hook with an optional callback
    const {
      selectTab,
      selectTabById,
      configure,
      restoreTabs,
      getTabsFromLocalStorage,
      getTabsFromSearchQuery,
      onPageChanged
    } = useDiplodocTabs(selectTabHandler);

    // useEffect to configure and setup state management
    useEffect(() => {
        // Configure the tabs when you want
        configure({
            // Enable saving tabs to local storage or not
            saveTabsToLocalStorage: true,

            // Enable saving tabs to the URL query state tied to the page
            // 'all' - all tabs selection in all pages will be saved in URLSearchQuery
            // 'page' (recommended) - all tabs selection in the current page will be saved in URLSearchQuery
            // 'none' - no tabs selection will be saved in URLSearchQuery
            saveTabsToQueryStateMode: 'page',
        });

        // Notify the tabs manager that the page has changed
        // IMPORTANT: Must be called when page changed, and before restore tabs (to keep saveTabsToQueryStateMode: 'page' working correctly)
        onPageChanged();

        // Restore tabs from local storage and query state
        restoreTabs({
            ...getTabsFromLocalStorage(), // Get tabs from local storage
            // URLSearchQuery is primary before localStorage, because it can be provided
            // queryExample: ?tabs=g0_cs,g1_macos_radio
            // if not variant (third param) specified, it will be search regular tab (out of the box)
            ...getTabsFromSearchQuery(), // Get tabs from search query
        });

    }, [
      configure,
      restoreTabs,
      getTabsFromLocalStorage,
      getTabsFromSearchQuery,
      onPageChanged
    ]);

    // useEffect to programmatically select tabs
    useEffect(() => {
        // Select a tab by group and key
        selectTab({ group: 'group_1', key: 'my-key' });

        // Alternatively, select a tab by key
        // selectTabById('my-key-2');
    }, [selectTab, selectTabById]);

    return (
        /* Your component JSX here */
    );
}

Documentation

For contributors

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.

MarkdownIt compatibility

Tabs 4 requires Markdown-it 15.0.3 or newer within major 15. It uses the native Markdown-it declarations and creates tokens through the active parser state. Both legacy and colon markup are supported according to the plugin options.

The installed-package compatibility tests use TypeScript 6.0.3 with NodeNext module resolution and skipLibCheck: false, including CommonJS and ESM hosts.