Skip to content

Auto generate sidebar according to the docs folder structure #3464

Closed

Description

@felipecrs

🚀 Feature

Auto generate sidebar according to the docs folder structure.

Have you read the Contributing Guidelines on issues?

Yes

Motivation

For me, it seems to be redundant to manage both the sidebars file and the docs folder structure, since the sidebars can be inferred from it.

Also, every time I add a new md file, I have to add it to the sidebar. This might not be a problem for fully manual work, but it's a problem when the md files can be generated automatically so we don't know beforehand what would be their IDs.

Pitch

Let's consider a docs folder like this:

- README.md
- api/
  - a.md
  - b.md
- cli/
  - a.md
  - b.md

We would need to set a sidebars like that to properly show this:

module.exports = {
  "sidebar": [
    "README",
    {
      "type": "category",
      "label": "API",
      "items": [
        "api/a",
        "api/b",
      ]
    },
    {
      "type": "category",
      "label": "CLI",
      "items": [
        "cli/a",
        "cli/b"
      ]
    }
  ]
};

This could be inferred automatically rather than requiring the user to maintain a separate file. Further customizations could be made through Front Matter in each doc. In case a folder requires personalization, a README.md could also be created for it.

Activity

  1. added
    feature
    status: needs triage
    on Sep 19, 2020
  2. added
    proposal
    on Sep 22, 2020
  3. fanny commented on Sep 22, 2020

    @fanny
    Contributor

    We could have the both options. It seems a good proposal for me.

  4. removed
    status: needs triage
    on Sep 22, 2020
  5. slorber commented on Sep 23, 2020

    @slorber
  6. felipecrs commented on Sep 23, 2020

    @felipecrs
    ContributorAuthor

    How do we keep retro-compatibility?

    If this ends up with a new option in the docusaurus.config.js, such as inferSidebarsFromFolder, we could simply make it default to false.

    Also what if we want b before of a?

    Perhaps prefixing numbers in the files: 1-b.md, 2-a.md.

  7. slorber commented on Sep 28, 2020

    @slorber
    Collaborator

    Perhaps prefixing numbers in the files: 1-b.md, 2-a.md.

    Why not, but you'd rather add slug frontmatter to have nice url paths

    I guess the category labels should be inferred from the folder names. So this means folder names should also have a number prefix for ordering.

    That also means it's not possible to have docs without sidebar, nor multiple sidebars, nor refs or external links in sidebars, so this option is limited compared to have a proper sidebars file.


    Wonder if it's really worth it. It may as well be quite confusing and add some complexity for no real gains except replacing centralised config boilerplate by number prefixes and frontmatter boilerrplate.

    Do you really see yourself using such a feature? If so, I'd like to ask you a commitment first.

    For example:

    • show me a Docusaurus site with a sidebars file (browsable online + github repository).
    • make a git branch and show me the exact docs FS structure and frontmatter you'd like to use to be able to get the first site running without the sidebar (I don't expect the site to be running obviously, as the feature is not implemented)
  8. removed
    proposal
    on Sep 28, 2020
  9. arinthros commented on Sep 29, 2020

    @arinthros

    I wrote a script for one of our monorepos that generates markdown from jsdoc comments, keeping the folder structure, and then auto-generates the sidebars.js while preserving any custom entries. It needs a few tweaks like alphabetizing and removing non-existent files, but it should give you a starting point for your project.

    https://gist.github.com/arinthros/526df3ef12383d26903c1c8588211cca

    The sidebar structure looks like this

    - General Info
    - Package One
      - Custom Doc
      - API Reference (auto generated folder)
        - someFunction
        - anotherFunction
    - PackageTwo
      ...
    
  10. felipecrs commented on Sep 29, 2020

    @felipecrs
    ContributorAuthor
  11. felipecrs commented on Sep 29, 2020

    @felipecrs
    ContributorAuthor

    I guess the category labels should be inferred from the folder names. So this means folder names should also have a number prefix for ordering.

    Not only. As per my initial proposal, further customizations for the categories could be made through an index.md in the root of each folder/category.

    That also means it's not possible to have docs without sidebar, nor multiple sidebars, nor refs or external links in sidebars, so this option is limited compared to have a proper sidebars file.

    I was not thinking this way. I think we must add this feature in a way that you are free to use both methods (manual or auto-generated sidebars). Something like:

    // sidebars.js
    module.exports = {
      sidebar: [
        "introduction",
        "API": './api/'
      ]
    } 

    Notice that in API category, I referenced a folder, this means it's supposed to be auto-generated. But probably we think of a more clean way.

    Do you really see yourself using such a feature? If so, I'd like to ask you a commitment first.

    Yes, but I totally understand that you should not waste time to implement a feature if you have a single user. Perhaps some kind of votation could help? (I'm just imagining)

    show me a Docusaurus site with a sidebars file (browsable online + github repository).

    https://felipesantos.dev/megatar
    https://github.com/felipecrs/megatar/tree/master/website

    Not a production-grade example though.

    make a git branch and show me the exact docs FS structure and frontmatter you'd like to use to be able to get the first site running without the sidebar (I don't expect the site to be running obviously, as the feature is not implemented)

    The master branch is already a good example:

    - docs
      - index.md # auto-generated by website/scripts/import-readme.md
      - api # auto-generated by docusaurus-plugin-typedoc
        - globals.md
        - Classes
          - Image.md
          - SaveImage.md
    

    The sidebars labels are already customized because of the title Front Matter in each of the files.

  12. slorber commented on Sep 30, 2020

    @slorber
    Collaborator

    Thanks for the infos.

    I need to work on i18n, not sure there's a huge need for this right now, and we need to figure out a good API surface for this feature first, so unless someone wants to help design/implement this will wait, but we can keep the discussion about API design.

    An idea could be to use a special kind of category type, somehow quite similar to your proposal but maybe more explicit.

    module.exports = {
      docs: [
        {
          type: 'autogenerated',
          label: 'Docusaurus',
          folderPath: './docs/docusaurus'
        },
      ],
    };
    

    image


    One important thing to consider is that it should work well with versioning. If we copy the sidebars.js to the versioned folders, it should still work so we should avoid relative paths/imports in this sidebars file, so creating "utils" to generate a sidebars slice from a relative path is likely not a good idea (related to #3285 (comment)).

  13. felipecrs commented on Sep 30, 2020

    @felipecrs
    ContributorAuthor

    Awesome, your design is more refined than what I proposed. LGTM.

  14. Clindbergh commented on Oct 19, 2020

    @Clindbergh

    An idea could be to use a special kind of category type, somehow quite similar to your proposal but maybe more explicit.

    module.exports = {
      docs: [
        {
          type: 'autogenerated',
          label: 'Docusaurus',
          folderPath: './docs/docusaurus'
        },
      ],
    };
    

    image

    Above example would be generated from this directory:

    Docsaurus/
    ├─ intro.md
    ├─ design.md
    ├─ contribute.md
    

    [tree credits], where all .md files have a title set, correct?

    If later Design Principles itself becomes a folder (which will be then be an autogenerated category), e.g.

    Docsaurus/
    ├─ intro.md
    ├─ design-principles/
    │  ├─ kiss.md
    ├─ contribute.md
    

    or if the category is an i18n name or something like Why Docsaurus?, we have a problem. Thus, I suggest to a _category_.md (like __init.py) file defining how the details of the category, e.g.

    Docsaurus/
    ├─ _category_.md
    ├─ intro.md
    ├─ design-principles/
    │  ├─ _category_.md
    │  ├─ kiss.md
    ├─ contribute.md
    

    This would make the Docs only mode much more useful.

  15. 11 remaining items

  16. slorber commented on Apr 13, 2021

    @slorber
    Collaborator

    Asking for feedbacks

    I've made some progress on this feature and would like to have your feedbacks.

    Sidebar configuration:

    You can use a new sidebar item type autogenerated, and it will generate a sidebar slice :

    module.exports = {
      mySidebar: [
        'my-doc-1'
        {
          type: 'category',
          label: 'Some category',
          items: [
            'my-doc-2'
            {
              type: 'autogenerated',
              dirName: 'api', // generate sidebar slice from docs/api (or versioned_docs/version/api)
            },
          ],
        },
      ],
    };

    By default, a Docusaurus site will auto-generate from its website/docs folder.

    The default/fallback sidebar config in case sidebars.js is absent:

    module.exports = {
      defaultSidebar: [
        {
          type: "autogenerated",
          dirName: "." // generate sidebar slice from docs (or versioned_docs/version)
        }
      ]
    };

    A "sidebar slice" will generate a list of sidebar items (be replaced with), and you can "concat" 2 sidebar slices under a single sidebar category if you want:

    module.exports = {
      mySidebar: [
        {
          type: "category",
          label: "Guides",
          items: [
            {
              type: "autogenerated",
              dirName: "guides/tutorial"
            },
            {
              type: "autogenerated",
              dirName: "guides/i18n"
            }
          ]
        }
      ]
    };

    Category metadata file

    Docusaurus will look for a _category_.json or _category_.yml file in autogenerated dirs, on which you will be able to provide sidebar category item attributes like collapsible, label

    When we'll implement category index files, we'll read this metadata directly on the Category/index.md frontmatter too.

    Sidebar ordering

    A new category and doc metadata/frontmatter sidebar_position will be used in priority

    By default, Docusaurus will look for number prefix patterns in filenames and dirnames, and try to use those when there is no explicit sidebar_position

    The number prefixes will be stripped to keep clean slugs/urls, titles and ids, so that in most cases you don't need to provide custom frontmatter. You can opt-out from extracting the number prefix from filenames if your doc really needs to start with a number (strip_number_prefixes: false).

    Provide your own generator

    Docusaurus has a default way to generate a sidebar from the FS. We could allow users to provide their own generator function by using docs plugin like sidebarGenerator: ({item, version, docs}) => ([]).

    It would be a hook/function that would receive the "autogenerated" sidebar items we found, and would have to return the sidebar slice that would replace the autogenerated item. It would receive the version and all available docs metadatas.

    Signature

    export type SidebarItemsGenerator = (generatorArgs: {
      item: SidebarItemAutogenerated;
      version: VersionMetadata;
      docs: DocMetadataBase[];
    }) => Promise<SidebarItem[]>;

    Feedback questions

    About the new sidebar item autogenerated:

    • Is autogenerated a good name for this?

    About position metadata:

    • Should we allow float numbers or limit to ints? Can float be useful to "interleave" a new doc anywhere between 2 existing docs?
    • What should be the name of the docs/category sidebar metadata/frontmatter used for ordering. Is sidebar_position appropriate?
    • Is the position used only to order inside the current sidebar slice, or it is used to order the category in general (ie if a category contains 2 sidebar slices, the items of the 2 sidebar slices could be interleaved?)
    • Should we allow to add a position metadata to docs/categories also in the regular sidebars.js docs and categories? (non auto-generated items).
    • My opinion is that the position metadata should only sort "inside a sidebar slice", or it could be confusing: you could position manually a doc in a sidebar, and have it unexpectedly repositioned differently after the sidebar has been sorted.

    About number prefixes:

    • What are the most common patterns for prefixing dirs/filenames with numbers? Do you have doc links to share?

    About sidebarGenerator custom generator function:

    • What is the minimal version/docs metadata we should provide? (we probably don't want to create a too large API surface here or it can be complicated to avoid breaking changes)
    • Should we allow any custom metadata on the autogenerated item, so that you could use it on the fn?
    • Should we inject all available docs of the version, or only a subset (ie filtered by a dir? which means the "dirPath" option is always required?)
    • Should we provide dir paths / docs paths relative to the version docs root website/docs or relative to the dirPath folder?

    Worth mentioning:

    • We only generate categories for folders containing actual docs
    • Using number prefixes can be annoying for linking with relative md file paths, as changing the prefix means changing the markdown link
  17. slorber commented on Apr 14, 2021

    @slorber
    Collaborator

    Let me know if anyone has any feedback or concern with my implementation, names or anything.

    The PR is ready to merge, just need to add the doc now so will likely merge it tomorrow.

  18. felipecrs commented on Apr 14, 2021

    @felipecrs
    ContributorAuthor

    The proposed design seems very good to my perspective. I don't have any concerns.

  19. arinthros commented on Apr 14, 2021

    @arinthros

    @slorber I read through this the other day, and had some time to process. Overall I think this is a great approach, well done. I don't think we would have a use case for numerical sort ordering of auto-generated content, we prefer the default alphabetical ordering of file names/titles so it's easier to find in the nav. But maybe there are others who would use numbering?

    Is autogenerated a good name for this?

    Sounds good to me. It's explicit about its purpose.

    Is the position used only to order inside the current sidebar slice, or it is used to order the category in general (ie if a category contains 2 sidebar slices, the items of the 2 sidebar slices could be interleaved?)

    I would think the numbering would be scoped to the slice, so not interleaved. I think the complexity of interleaving could be its own feature - or some sort of param boolean to enable or merge sort order. How would conflicts be handled?

    Should we allow to add a position metadata to docs/categories also in the regular sidebars.js docs and categories? (non auto-generated items).
    My opinion is that the position metadata should only sort "inside a sidebar slice", or it could be confusing: you could position manually a doc in a sidebar, and have it unexpectedly repositioned differently after the sidebar has been sorted.

    Agreed. Re-sorting a manually sorted list could lead to unintended confusion/bugs.

  20. arinthros commented on Apr 14, 2021

    @arinthros

    If we want a custom sort order, we would manually do that in the sidebar.js file and use slices for the rest. So maybe slices would ignore plucked files, kind of how object spread works in React?

    const { title, url, ...rest } = props

  21. slorber commented on Apr 15, 2021

    @slorber
    Collaborator

    Thanks for the feedbacks, so it seems my implementation is good enough to merge.

    @arinthros

    If we want a custom sort order, we would manually do that in the sidebar.js file and use slices for the rest. So maybe slices would ignore plucked files, kind of how object spread works in React?

    const { title, url, ...rest } = props

    For now we don't "deduplicate" items, so basically you can do that and end-up with the sidebar slice being generated twice:

    module.exports = {
      mySidebar: [
        {
          type: "autogenerated",
          dirName: "tutorials"
        },
        {
          type: "autogenerated",
          dirName: "tutorials"
        }
      ]
    };

    I don't think we shuld do anything clever regarding this kind of situation.

    We could add a way to include/exclude some docs by using glob patterns:

    module.exports = {
      mySidebar: [
        {
          type: "autogenerated",
          dirName: "tutorials"
          include: "**/easy-*.md"
        },
        {
          type: "autogenerated",
          dirName: "tutorials"
          include: "**/easy-*.md"
        }
      ]
    };

    I don't think this is needed now, but that can be added later if this is requested.

  22. 0Grit commented on Nov 11, 2021

    @0Grit

    @slorber is there a way to specify items within an autogenerated slice by file?

    Possibly use the items key inside of a _category_.yml?

    I want just the top level of my slice to be autogenerated to avoid confusion for others maintaining another section of our docs that want to use autogenerated slices all the way down.

  23. Josh-Cena commented on Nov 11, 2021

    @Josh-Cena
    Collaborator

    @0Grit See #5689. This is another enhancement request.

  24. slorber commented on Nov 12, 2021

    @slorber
    Collaborator

    yes #5689 is a good place to discuss that.

    @0Grit I'd appreciate to understand better your use-case: why deeply nested auto-generation is confusing and why do you want to opt-out of it? Why do you want to keep subfolders in the autogenerated folder?

  25. 0Grit commented on Nov 12, 2021

    @0Grit

    @slorber I have a perception that git diffs will be cleaner and rebases will also have less merge conflicts if I'm encoding my documentation structure in a file versus using the file-system concept to set the doc structure.

  26. 0Grit commented on Nov 12, 2021

    @0Grit

    Documentation structure as code versus documentation structure as filesystem. It is easier to change the contents of a limited number of files versus moving files around the filesystem and having to modify lots of __category_.yml files.

  27. 0Grit commented on Nov 12, 2021

    @0Grit

    This is my personal preference having experiences with this sort of thing in the past. Other people on the team including maintainer of our docs repository currently prefer the autogeneration.

  28. slorber commented on Nov 12, 2021

    @slorber
    Collaborator

    @0Grit it's still hard to understand to me.

    If you just auto-generate on a single level, why don't you just not auto-generate and declare an explicit sidebar category instead?
    Subcategories can still be auto-generated if needed.

    You can put all your docs flat in a single folder and create your sidebar tree manually: no file move needed

  29. 0Grit commented on Nov 12, 2021

    @0Grit

    @slorber Yes, your recommendation, is what I was going to end up doing.
    I didn't want to need to change sidebar.js to do it.
    I also thought it might be nice to be able to specify my sidebar in a more modular fashion with __category__.yml or some other file as desired.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions