Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: format next and docusaurus plugins #568

Merged
merged 1 commit into from
Dec 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"indentStyle": "space"
},
"files": {
"include": ["plugin-vitepress"],
"include": ["plugin-vitepress", "plugin-nextra", "plugin-docusaurus"],
"maxSize": 1000000000
},
"javascript": {
Expand Down
42 changes: 21 additions & 21 deletions packages/plugin-docusaurus/src/client/theme/SearchBar/index.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
import { autocomplete } from "@algolia/autocomplete-js"
import "@algolia/autocomplete-theme-classic/dist/theme.min.css"
import { autocomplete } from '@algolia/autocomplete-js'
import '@algolia/autocomplete-theme-classic/dist/theme.min.css'
// eslint-disable-next-line @typescript-eslint/ban-ts-comment, @typescript-eslint/prefer-ts-expect-error
// @ts-ignore Will fail in CJS compilation
import { GlobalVersion, useActiveVersion, useVersions } from "@docusaurus/plugin-content-docs/client"
import { useColorMode, useDocsPreferredVersion } from "@docusaurus/theme-common"
import useBaseUrl from "@docusaurus/useBaseUrl"
import useDocusaurusContext from "@docusaurus/useDocusaurusContext"
import { usePluginData } from "@docusaurus/useGlobalData"
import useIsBrowser from "@docusaurus/useIsBrowser"
import { AnyDocument, create, load, Orama, RawData, search as oramaSearch } from "@orama/orama"
import { Highlight } from "@orama/highlight"
import { ungzip } from "pako"
import { createElement, Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react"
import { render } from "react-dom"
import { GlobalVersion, useActiveVersion, useVersions } from '@docusaurus/plugin-content-docs/client'
import { useColorMode, useDocsPreferredVersion } from '@docusaurus/theme-common'
import useBaseUrl from '@docusaurus/useBaseUrl'
import useDocusaurusContext from '@docusaurus/useDocusaurusContext'
import { usePluginData } from '@docusaurus/useGlobalData'
import useIsBrowser from '@docusaurus/useIsBrowser'
import { AnyDocument, create, load, Orama, RawData, search as oramaSearch } from '@orama/orama'
import { Highlight } from '@orama/highlight'
import { ungzip } from 'pako'
import { createElement, Fragment, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { render } from 'react-dom'
// @ts-expect-error Resolve at runtime
import { SearchNoResults } from "@theme/SearchNoResults"
import { SearchNoResults } from '@theme/SearchNoResults'
// @ts-expect-error Resolve at runtime
import { SearchResults } from "@theme/SearchResults"
import { SearchResults } from '@theme/SearchResults'
// @ts-expect-error Resolve at runtime
import { SearchResult } from "@theme/SearchResult"
import { Hit, INDEX_FILE, PLUGIN_NAME, PluginData, schema } from "../../../server/types.js"
import { SearchResult } from '@theme/SearchResult'
import { Hit, INDEX_FILE, PLUGIN_NAME, PluginData, schema } from '../../../server/types.js'

const highlighter = new Highlight({
CSSClass: 'aa-ItemContentHighlight',
HTMLTag: 'span',
HTMLTag: 'span'
})

export default function SearchBar(): JSX.Element {
Expand Down Expand Up @@ -83,7 +83,7 @@ export default function SearchBar(): JSX.Element {
{
sourceId: 'orama',
async getItems() {
if(!term) {
if (!term) {
return []
}

Expand All @@ -97,7 +97,7 @@ export default function SearchBar(): JSX.Element {
...hit,
document: {
...hit.document,
sectionContent: highlighter.highlight(hit.document.sectionContent, term).trim(20),
sectionContent: highlighter.highlight(hit.document.sectionContent, term).trim(20)
}
}
})
Expand Down Expand Up @@ -171,7 +171,7 @@ export default function SearchBar(): JSX.Element {
return
}

loadDatabase(version).catch(error => {
loadDatabase(version).catch((error) => {
console.error('Cannot load search index.', error)
})
}, [isBrowser, searchData, searchBaseUrl, version])
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Result } from "@orama/orama"
import { SectionSchema } from "../../../server/types.js"
import { Result } from '@orama/orama'
import { SectionSchema } from '../../../server/types.js'

interface SearchResultProps {
hit: Result<SectionSchema>
Expand All @@ -13,8 +13,10 @@ export function SearchResult({ hit }: SearchResultProps): JSX.Element {
<div className="aa-ItemContentTitle">
<h5 style={{ marginBottom: 0 }}>{hit.document.sectionTitle as string}</h5>
</div>
<div className="aa-ItemContentDescription"
dangerouslySetInnerHTML={{ __html: hit.document.sectionContent }}></div>
<div
className="aa-ItemContentDescription"
dangerouslySetInnerHTML={{ __html: hit.document.sectionContent }}
></div>
</div>
</div>
</a>
Expand Down
14 changes: 7 additions & 7 deletions packages/plugin-docusaurus/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export function defaultToSectionSchema(
sectionTitle = (pageRoute.split('/').pop() ?? '')
.replace(/(-)+/g, ' ')
.split(' ')
.map(word => word && `${word[0].toUpperCase()}${word.substring(1)}`)
.map((word) => word && `${word[0].toUpperCase()}${word.substring(1)}`)
.join(' ')
}

Expand Down Expand Up @@ -105,7 +105,7 @@ async function generateDocument(

// Convert all the documents to a
const sections = Object.values(db.data.docs.docs)
.map(node => {
.map((node) => {
return defaultToSectionSchema(node, permalink.slice(1), title, version)
})
.filter(isIndexable)
Expand Down Expand Up @@ -150,7 +150,7 @@ async function buildDevSearchData(siteDir: string, outDir: string, allContent: a

await insertMultiple(_db, documents)

const serialized = (await save(_db))
const serialized = await save(_db)

await writeFile(indexPath(outDir, version), await gzip(JSON.stringify(serialized)))
}
Expand Down Expand Up @@ -187,11 +187,11 @@ function docusaurusOramaPlugin(context: LoadContext, options: PluginOptions): Pl
async contentLoaded({ actions, allContent }) {
const isDevelopment = process.env.NODE_ENV === 'development'
const loadedVersions = (allContent['docusaurus-plugin-content-docs']?.default as LoadedContent)?.loadedVersions
versions = loadedVersions.map(v => v.versionName)
versions = loadedVersions.map((v) => v.versionName)

// Build all versions
await Promise.all(
versions.map(version => buildDevSearchData(context.siteDir, context.generatedFilesDir, allContent, version))
versions.map((version) => buildDevSearchData(context.siteDir, context.generatedFilesDir, allContent, version))
)

for (const name of versions) {
Expand All @@ -202,7 +202,7 @@ function docusaurusOramaPlugin(context: LoadContext, options: PluginOptions): Pl
actions.setGlobalData({
searchData: Object.fromEntries(
await Promise.all(
versions.map(async version => {
versions.map(async (version) => {
return [version, await readFile(indexPath(context.generatedFilesDir, version))]
})
)
Expand All @@ -214,7 +214,7 @@ function docusaurusOramaPlugin(context: LoadContext, options: PluginOptions): Pl
},
async postBuild({ outDir }: { outDir: string }) {
await Promise.all(
versions.map(async version => {
versions.map(async (version) => {
return cp(indexPath(context.generatedFilesDir, version), indexPath(outDir, version))
})
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export async function retrieveTranslationMessages(docusaurusContext: LoadContext
const localesToTry = codeTranslationLocalesToTry(docusaurusContext.i18n.currentLocale)

const existingLocalePath = localesToTry
.map(locale => path.join(translationsDir, `${locale}.json`))
.map((locale) => path.join(translationsDir, `${locale}.json`))
.find(fs.existsSync)

return existingLocalePath ? retrieveObjectContent(existingLocalePath) : Promise.resolve({})
Expand Down
27 changes: 21 additions & 6 deletions packages/plugin-docusaurus/test/integration.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { create, load, search } from "@orama/orama"
import { create, load, search } from '@orama/orama'
import assert from 'node:assert'
import { exec, ExecException } from 'node:child_process'
import { existsSync } from 'node:fs'
Expand Down Expand Up @@ -93,25 +93,40 @@ await test('generated DBs have indexed pages content', async () => {
await load(database, data)

// Search results seem reasonable
const indexSearchResult = await search(database, { term: 'index', properties: ['sectionTitle', 'sectionContent', 'type'] })
const indexSearchResult = await search(database, {
term: 'index',
properties: ['sectionTitle', 'sectionContent', 'type']
})
assert.ok(indexSearchResult.count === 1)
assert.ok(indexSearchResult.hits[0].document.pageRoute === '/#main')

const catSearchResult = await search(database, { term: 'cat', properties: ['sectionTitle', 'sectionContent', 'type'] })
const catSearchResult = await search(database, {
term: 'cat',
properties: ['sectionTitle', 'sectionContent', 'type']
})
assert.ok(catSearchResult.count === 1)
assert.ok(catSearchResult.hits[0].document.pageRoute === '/animals_cat')

const dogSearchResult = await search(database, { term: 'dog', properties: ['sectionTitle', 'sectionContent', 'type'] })
const dogSearchResult = await search(database, {
term: 'dog',
properties: ['sectionTitle', 'sectionContent', 'type']
})
assert.ok(dogSearchResult.count === 2)
assert.ok(dogSearchResult.hits[0].document.pageRoute === '/animals_dog#dog')

const domesticSearchResult = await search(database, { term: 'domestic', properties: ['sectionTitle', 'sectionContent', 'type'] })
const domesticSearchResult = await search(database, {
term: 'domestic',
properties: ['sectionTitle', 'sectionContent', 'type']
})
assert.ok(domesticSearchResult.count === 2)
assert.ok(domesticSearchResult.hits[0].document.pageRoute === '/animals_cat')
assert.ok(domesticSearchResult.hits[1].document.pageRoute === '/animals_dog#dog')

// We do not have content about turtles
const turtleSearchResult = await search(database, { term: 'turtle', properties: ['sectionTitle', 'sectionContent', 'type'] })
const turtleSearchResult = await search(database, {
term: 'turtle',
properties: ['sectionTitle', 'sectionContent', 'type']
})
assert.ok(turtleSearchResult.count === 0)
})

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export function HighlightedDocument({ hit, trim = 200 }: HighlightedDocumentProp
let highlightedText = ''
let currentIndex = 0

positions.forEach(position => {
positions.forEach((position) => {
const start = position.start
const length = position.length
highlightedText +=
Expand Down
16 changes: 8 additions & 8 deletions packages/plugin-nextra/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ const defaultProps: OramaSearchProps = {
boost: {
title: 2,
description: 1,
content: 1,
},
content: 1
}
}

export function OramaSearch(props = defaultProps) {
Expand All @@ -49,7 +49,7 @@ function OramaSearchPlugin({ router, ...props }) {
useEffect(() => {
setIndexing(true)

createOramaIndex(basePath, locale).then(index => {
createOramaIndex(basePath, locale).then((index) => {
indexes[locale] = index
setIndexing(false)
})
Expand All @@ -59,7 +59,7 @@ function OramaSearchPlugin({ router, ...props }) {
useEffect(() => {
if (!(locale in indexes)) {
setIndexing(true)
createOramaIndex(basePath, locale).then(index => {
createOramaIndex(basePath, locale).then((index) => {
indexes[locale] = index
setIndexing(false)
})
Expand All @@ -72,8 +72,8 @@ function OramaSearchPlugin({ router, ...props }) {
searchWithHighlight(indexes[locale], {
term: searchTerm,
limit: props.limitResults,
boost: props.boost,
}).then(results => {
boost: props.boost
}).then((results) => {
setResults(results)
setGroupedResults(groupDocumentsBy(results.hits, 'title'))
})
Expand Down Expand Up @@ -119,7 +119,7 @@ function OramaSearchPlugin({ router, ...props }) {
type="search"
placeholder="Search documentation..."
className="nx-block nx-w-full nx-appearance-none nx-rounded-lg nx-px-3 nx-py-2 nx-transition-colors nx-text-base nx-leading-tight md:nx-text-sm nx-bg-black/[.05] dark:nx-bg-gray-50/10 focus:nx-bg-white dark:focus:nx-bg-dark placeholder:nx-text-gray-500 dark:placeholder:nx-text-gray-400 contrast-more:nx-border contrast-more:nx-border-current"
onChange={e => setSearchTerm(e.target.value)}
onChange={(e) => setSearchTerm(e.target.value)}
value={searchTerm}
onFocus={() => setHasFocus(true)}
onBlur={() => {
Expand Down Expand Up @@ -151,7 +151,7 @@ function OramaSearchPlugin({ router, ...props }) {
<>
<div ref={wrapperRef}>
<ul>
{Object.keys(groupedResults).map(title => (
{Object.keys(groupedResults).map((title) => (
<li key={title} className="nx-bg-primary-600">
<div className="nx-mx-2.5 nx-mb-2 nx-mt-6 nx-select-none nx-border-b nx-border-black/10 nx-px-2.5 nx-pb-1.5 nx-text-xs nx-font-semibold nx-uppercase nx-text-gray-500 first:nx-mt-0 dark:nx-border-white/20 dark:nx-text-gray-300 contrast-more:nx-border-gray-600 contrast-more:nx-text-gray-900 contrast-more:dark:nx-border-gray-50 contrast-more:dark:nx-text-gray-50">
{title}
Expand Down
12 changes: 6 additions & 6 deletions packages/plugin-nextra/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const defaultSchema = {
id: 'string',
title: 'string',
url: 'string',
content: 'string',
content: 'string'
} as const

export async function createOramaIndex(basePath, locale): Promise<NextraOrama> {
Expand All @@ -35,13 +35,13 @@ export async function createOramaIndex(basePath, locale): Promise<NextraOrama> {
schema: defaultSchema,
components: {
tokenizer: {
stemming: false,
},
stemming: false
}
},
plugins: [
{
name: 'match-highlight',
afterInsert: highlightAfterInsertHook,
afterInsert: highlightAfterInsertHook
}
]
})
Expand All @@ -58,7 +58,7 @@ export async function createOramaIndex(basePath, locale): Promise<NextraOrama> {
id: url,
title,
url,
content,
content
})

const sectionData = data[path].data
Expand All @@ -72,7 +72,7 @@ export async function createOramaIndex(basePath, locale): Promise<NextraOrama> {
id: `${url}#${hash}`,
title,
url: `${url}#${hash}`,
content,
content
})
}
}
Expand Down