typesense / docusaurus-theme-search-typesense

A fork of the awesome @docusaurus/theme-search-algolia library customized to work with Typesense
https://typesense.org/docs/guide/docsearch.html
MIT License
63 stars 15 forks source link

DocsPreferredVersionContextProvider error when launching page. #10

Open Babilinski opened 2 years ago

Babilinski commented 2 years ago

Description

Docusaurus site versions 2.0.0-beta.16 and 2.0.0-beta.15 do not work with the typesense search plugin. Starting page after configuring the website results in the following error .

This page crashed.
Can't find docs preferred context, maybe you forgot to use the "DocsPreferredVersionContextProvider"?

Steps to reproduce

After creating a new docusaurus site using the command on their getting started page:

npx create-docusaurus@latest my-website classic

Adding "docusaurus-theme-search-typesense": "^0.3.0", to the dependencies section in the package.json file

Installing the plugin using

 npm install --legacy-peer-deps

and configuring my config.js file I launch my website using npm run start and see the following error

This page crashed.
Can't find docs preferred context, maybe you forgot to use the "DocsPreferredVersionContextProvider"?

Expected Behavior

Website should load and search bar should be present.

Actual Behavior

Website crashes

Metadata

Typsense Version: docusaurus-theme-search-typesense": "^0.3.0"

OS: Windows and Mac

Babilinski commented 2 years ago

This is the config file for the docusaurus site

// @ts-check
// Note: type annotations allow type checking and IDEs autocompletion

const lightCodeTheme = require('prism-react-renderer/themes/github');
const darkCodeTheme = require('prism-react-renderer/themes/dracula');

/** @type {import('@docusaurus/types').Config} */
const config = {
  title: 'My Site',
  tagline: 'Dinosaurs are cool',
  url: 'https://your-docusaurus-test-site.com',
  baseUrl: '/',
  onBrokenLinks: 'throw',
  onBrokenMarkdownLinks: 'warn',
  favicon: 'img/favicon.ico',
  organizationName: 'facebook', // Usually your GitHub org/user name.
  projectName: 'docusaurus', // Usually your repo name.
  themes: ['docusaurus-theme-search-typesense'],
  presets: [
    [
      'classic',
      /** @type {import('@docusaurus/preset-classic').Options} */
      ({
        docs: {
          sidebarPath: require.resolve('./sidebars.js'),
          // Please change this to your repo.
          editUrl: 'https://github.com/facebook/docusaurus/tree/main/packages/create-docusaurus/templates/shared/',
        },
        blog: {
          showReadingTime: true,
          // Please change this to your repo.
          editUrl:
            'https://github.com/facebook/docusaurus/tree/main/packages/create-docusaurus/templates/shared/',
        },
        theme: {
          customCss: require.resolve('./src/css/custom.css'),
        },
      }),
    ],
  ],

  themeConfig:
    /** @type {import('@docusaurus/preset-classic').ThemeConfig} */
    ({
      navbar: {
        title: 'My Site',
        logo: {
          alt: 'My Site Logo',
          src: 'img/logo.svg',
        },
        items: [
          {
            type: 'doc',
            docId: 'intro',
            position: 'left',
            label: 'Tutorial',
          },
          {to: '/blog', label: 'Blog', position: 'left'},
          {
            href: 'https://github.com/facebook/docusaurus',
            label: 'GitHub',
            position: 'right',
          },
        ],
      },
      footer: {
        style: 'dark',
        links: [
          {
            title: 'Docs',
            items: [
              {
                label: 'Tutorial',
                to: '/docs/intro',
              },
            ],
          },
          {
            title: 'Community',
            items: [
              {
                label: 'Stack Overflow',
                href: 'https://stackoverflow.com/questions/tagged/docusaurus',
              },
              {
                label: 'Discord',
                href: 'https://discordapp.com/invite/docusaurus',
              },
              {
                label: 'Twitter',
                href: 'https://twitter.com/docusaurus',
              },
            ],
          },
          {
            title: 'More',
            items: [
              {
                label: 'Blog',
                to: '/blog',
              },
              {
                label: 'GitHub',
                href: 'https://github.com/facebook/docusaurus',
              },
            ],
          },
        ],
        copyright: `Copyright © ${new Date().getFullYear()} My Project, Inc. Built with Docusaurus.`,
      },
      typesense: {
      typesenseCollectionName: 'typesense', // Replace with your own doc site's name. Should match the collection name in the scraper settings.

      typesenseServerConfig: {
        nodes: [
          {
            host: 'host.docker.internal',
            port: 8108,
            protocol: 'http',
          },
        ],
        apiKey: 'xyz', //insert admin key here
      },

      // Optional: Typesense search parameters: https://typesense.org/docs/0.21.0/api/documents.md#search-parameters
      typesenseSearchParameters: {},

      // Optional
      contextualSearch: false, //should be true, but turned it off to see if this was the source of the "context" bug
    },
      prism: {
        theme: lightCodeTheme,
        darkTheme: darkCodeTheme,
      },
    }),
};

module.exports = config;
Babilinski commented 2 years ago

This is the packge.json file

{
  "name": "my-website",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "docusaurus": "docusaurus",
    "start": "docusaurus start",
    "build": "docusaurus build",
    "swizzle": "docusaurus swizzle",
    "deploy": "docusaurus deploy",
    "clear": "docusaurus clear",
    "serve": "docusaurus serve",
    "write-translations": "docusaurus write-translations",
    "write-heading-ids": "docusaurus write-heading-ids"
  },
  "dependencies": {
    "@docusaurus/core": "2.0.0-beta.16",
    "@docusaurus/preset-classic": "2.0.0-beta.16",
    "@mdx-js/react": "^1.6.22",
    "docusaurus-theme-search-typesense": "^0.3.0",
    "clsx": "^1.1.1",
    "prism-react-renderer": "^1.2.1",
    "react": "^17.0.1",
    "react-dom": "^17.0.1"
  },
  "browserslist": {
    "production": [
      ">0.5%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
jasonbosco commented 2 years ago

@Babilinski I've run into this issue once before when using npm link to test the plugin locally, but I've not seen it when installing from npm (strange I know).

I've reached out to the docusaurus team to see if they have any thoughts on this.

Josh-Cena commented 2 years ago

Hi, this is very likely a dependency deduplicating problem. You have theme-classic and theme-typesense that both depend on theme-common, and the latter exports the DocsPreferredVersionContextProvider. If the packages fail to deduplicate, there will be two copies of theme-common in the node_modules tree, and theme-typesense will import an empty context that's not filled by theme-classic.

Could you try deleting node_modules and lock file and reinstalling?

jasonbosco commented 2 years ago

@Josh-Cena Thank you for that pointer about duplicate instances in the node_modules tree. I tried to clear node_modules and the lock file in both theme-typesense and in my docusaurus testground. But I still saw the same error.

I then moved @docusaurus/core and @docusaurus/theme-common from dependencies to peerDependencies in the theme's package.json and the error went away and the search bar was rendered as expected! I only added those two packages to dependencies instead of peerDependencies because I saw that's how the Algolia theme was structured. Is it ok to move them to peer dependencies or could something else in the plugin architecture break with this change?

Side note: @Babilinski I've published this change in 0.4.0-0. Could you give it a shot now?

Josh-Cena commented 2 years ago

I suspect it's fine. It's indeed bad practice to rely on package hoisting, but we don't want the users to install theme-common either.

Moving theme-common to peer dependencies is not ideal, maybe even worse. Yarn berry dictates that every peer dependency be provided by its direct ancestor (as a hard dependency, or relaying it as peer dependency), not some other random package in the tree. Which means if a user installs both preset-classic and theme-typesense, the two packages either both declare theme-common as hard dependency, or they require the user to install theme-common. There unfortunately doesn't exist a good way (that I can think of) to fix this behavior without introducing errors elsewhere.

Is theme-common hoisted to the root in your repro? Or is it in node_modules/@docusaurus/theme-classic/node_modules/@docusaurus/theme-common or something like that?

jasonbosco commented 2 years ago

I see theme-common in the root node_modules directory:

$ tree -d -L 1 node_modules/@docusaurus/
node_modules/@docusaurus/
|-- core
|-- cssnano-preset
|-- logger
|-- mdx-loader
|-- module-type-aliases
|-- plugin-content-blog
|-- plugin-content-docs
|-- plugin-content-pages
|-- plugin-debug
|-- plugin-google-analytics
|-- plugin-google-gtag
|-- plugin-sitemap
|-- preset-classic
|-- react-loadable
|-- theme-classic
|-- theme-common
|-- theme-search-algolia
|-- theme-translations
|-- types
|-- utils
|-- utils-common
`-- utils-validation

22 directories
Josh-Cena commented 2 years ago

I mean, it's certainly at the root (that's the default behavior of package managers), but it could also be non-deduped in theme-typesense...

jasonbosco commented 2 years ago

By "it could also be non-deduped in theme-typesense" I'm guessing you meant add theme-common as a direct dependency of theme-typesense?

If so, given that adding theme-common to dependencies in theme-typesense causes the DocsPreferredVersionContextProvider error (when used with other themes), I was wondering if we should ask users to directly install theme-common in their docusaurus site, so it's shared between all themes? But you mentioned:

we don't want the users to install theme-common either

Any particular reason we don't want users to do this?

Josh-Cena commented 2 years ago

Because the fewer packages we ask users to install, the better :D I would need to inspect this later.

augustluhrs commented 2 years ago

Hello! I work with @Babilinski and can confirm that the above fix got our theme to work correctly. thanks so much!

jmccann commented 2 years ago

Just want to be sure what the workarounds for this are currently.

It seems I could "fork" this project and modify some of its dependencies that should work with 2.0.0-beta.16? Is that the only workaround for now? (per https://github.com/typesense/docusaurus-theme-search-typesense/issues/10#issuecomment-1054952305) ... seems this approach isn't a good long term solution though?

Are there any other thoughts/tricks I can do in my site's own package.json to get around this?

Josh-Cena commented 2 years ago

Could people encountering this issue give their package manager? It could be due to differing behaviors between package managers.

jasonbosco commented 2 years ago

I was able to replicate the original issue with both yarn and npm.

jmccann commented 2 years ago

I'm using yarn

Didn't notice that a pre-release v0.4.0-0 was released.

I tried it just now, with 2.0.0-beta.17, and got the same error.

Error from Browser Console ``` The above error occurred in the component: DocSearch@webpack-internal:///./node_modules/docusaurus-theme-search-typesense/src/theme/SearchBar/index.js:23:662 SearchBar@webpack-internal:///./node_modules/docusaurus-theme-search-typesense/src/theme/SearchBar/index.js:29:2210 div div nav Navbar@webpack-internal:///./node_modules/@docusaurus/theme-classic/lib-next/theme/Navbar/index.js:41:3250 MobileSecondaryMenuProvider@webpack-internal:///./node_modules/@docusaurus/theme-common/lib/utils/mobileSecondaryMenu.js:14:236 DocsPreferredVersionContextProviderUnsafe@webpack-internal:///./node_modules/@docusaurus/theme-common/lib/utils/docsPreferredVersion/DocsPreferredVersionProvider.js:27:808 DocsPreferredVersionContextProvider@webpack-internal:///./node_modules/@docusaurus/theme-common/lib/utils/docsPreferredVersion/DocsPreferredVersionProvider.js:27:523 ScrollControllerProvider@webpack-internal:///./node_modules/@docusaurus/theme-common/lib/utils/scrollUtils.js:16:502 ```
jmccann commented 2 years ago

FYI, I saw 0.4.0-2 was released and tried it out ... seems to be working so far for me.

romdej commented 2 years ago

I confirm, version 0.4.0-2 seems to fix the problem. I reproduced the bug with the previous versions. For information, if it helps, I use Yarn berry and workspaces.

thgossler commented 2 years ago

I have this problem now with 0.6.0 on Docusaurus 2.0.1 in dev mode (npm run start) from PowerShell 7 on Windows 11 (see attached screenshot for the error in the browser console). I'm using npm.

When I comment-out theme 'docusaurus-theme-search-typesense' in docusaurus.config.json then there is no error, but also no search box.

I have tried it by forcibly upgrading to Docusaurus 2.1.0, didn't change anything.

Any suggestions?

ConsoleError
thgossler commented 1 year ago

Could anyone please look into this and give a hint? I cannot make any progress understanding the root cause.

jasonbosco commented 1 year ago

@thgossler v0.6.0 worked fine for me on Docusaurus 2.0.1 when running locally... could you share a minimal Docusaurus project that replicates this issue?

thgossler commented 1 year ago

min-setups.zip

There are 3 minimal projects in the zip file.

  1. min-2.0.0-beta.21-0.4.0-working
  2. min-2.0.1-0.6.0-working
  3. min-2.1.0-0.6.0-notworking

In fact, it is now also working on 2.0.1 for me. Thanks, @jasonbosco, to point this out again! I guess I had messed around a bit too much during npm updates to latest. A clean update with the following commands from 1. to 2. was working.

npm i @docusaurus/core@2.0.1 @docusaurus/plugin-pwa@2.0.1 @docusaurus/preset-classic@2.0.1 @docusaurus/theme-search-algolia@2.0.1
npm i docusaurus-theme-search-typesense@0.6.0

But, then just executing the following update command in 2. leads to the mentioned error again. Should be reproducible by:

jasonbosco commented 1 year ago

Thank you for putting that together. I just tried v0.6.0 of the typesense theme on docusaurus 2.1.0 and it seems to work fine for me. Here's the project: https://github.com/typesense/docusaurus-typesense-testground

In any case, I've published 0.7.0-0 of docusaurus-theme-search-typesense which explicitly lists docusaurus 2.1.0 as a dependency. Let me know if that works for you.

thgossler commented 1 year ago

Thanks! I will try it and let you know.

thgossler commented 1 year ago

Seems not to have helped.

What I have tried:

Same error occurs.

I believe it is not simply a dependency issue, it seems to be some incompatibility with the latest docusaurus version 2.1.0.

jasonbosco commented 1 year ago

Hmm, I tried it with the testground repo I have here and it works fine for me there: https://github.com/typesense/docusaurus-typesense-testground

Could you try cloning that and running it locally?

thgossler commented 1 year ago

Yes, this works, but not in context of my project.

I have no idea what could cause this problem in my project, see my note above with the attached ZIP file which can be used to reproduce the error.

Any hint would be highly appreciated!