Skip to content
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
5 changes: 3 additions & 2 deletions plugins/global-search/src/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import { describe, expect, it } from "vitest"
import { App } from "./App"

describe("App", () => {
it("should render", () => {
it("should render search interface", () => {
render(<App />)
expect(screen.getByText(/Welcome!/gi)).toBeInTheDocument()
expect(screen.getByPlaceholderText(/Search/i)).toBeInTheDocument()
expect(screen.getByLabelText(/Search for anything in your Framer project/i)).toBeInTheDocument()
})
})
13 changes: 5 additions & 8 deletions plugins/global-search/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ import { framer } from "framer-plugin"
import { useEffect, useState } from "react"
import { ErrorBoundary } from "react-error-boundary"
import { DevToolsScene } from "./components/DevToolsScene"
import { SearchScene } from "./components/SearchScene"
import { IndexerProvider } from "./utils/indexer/IndexerProvider"

framer.showUI({
position: "top right",
width: 400,
height: 600,
resizable: true,
width: 280,
height: 64,
})

export function App() {
Expand All @@ -34,11 +34,8 @@ export function App() {
)}
>
<IndexerProvider>
{activeScene === "dev-tools" ? (
<DevToolsScene />
) : (
<div>Welcome! This is under development. Select "Open Dev Tools" to get started.</div>
)}
{activeScene === "dev-tools" && <DevToolsScene />}
{activeScene === "search" && <SearchScene />}
</IndexerProvider>
</ErrorBoundary>
)
Expand Down
11 changes: 10 additions & 1 deletion plugins/global-search/src/components/DevToolsScene.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useMemo, useState } from "react"
import { framer } from "framer-plugin"
import { useEffect, useMemo, useState } from "react"
import { cn } from "../utils/className"
import { type IndexEntry } from "../utils/indexer/types"
import { useIndexer } from "../utils/indexer/useIndexer"
Expand Down Expand Up @@ -28,6 +29,14 @@ export function DevToolsScene() {
[entries, filterQuery]
)

useEffect(() => {
framer.showUI({
height: Infinity,
width: Infinity,
resizable: true,
})
}, [])

const stats = useMemo(
() => ({
total: entries.length,
Expand Down
23 changes: 23 additions & 0 deletions plugins/global-search/src/components/SearchInput.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import type { DetailedHTMLProps } from "react"
import { cn } from "../utils/className"
import { IconSearch } from "./ui/IconSearch"

type SearchInputProps = DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>

export function SearchInput({ className, ...props }: SearchInputProps) {
return (
<label className="flex items-center gap-2 text-framer-text-tertiary flex-1 border border-amber-500 rounded-md -ml-1 pl-2">
<span className="sr-only">Search for anything in your Framer project</span>
<IconSearch aria-hidden />
<input
type="text"
className={cn(
"flex-1 bg-transparent border-none outline-none focus-visible:outline-none focus-visible:ring-0 text-xs selection:bg-amber-500",
className
)}
placeholder="Search..."
{...props}
/>
</label>
)
}
203 changes: 203 additions & 0 deletions plugins/global-search/src/components/SearchScene.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
import { framer, type MenuItem } from "framer-plugin"
import { startTransition, useCallback, useEffect, useMemo, useState } from "react"
import { assertNever } from "../utils/assert"
import { type ReadonlyGroupedResults } from "../utils/filter/group-results"
import type { Range } from "../utils/filter/ranges"
import { type CollectionItemResult, type NodeResult, type Result } from "../utils/filter/types"
import { useFilter } from "../utils/filter/useFilter"
import type { RootNodeType } from "../utils/indexer/types"
import { useIndexer } from "../utils/indexer/useIndexer"
import { entries } from "../utils/object"
import { SearchInput } from "./SearchInput"
import { IconEllipsis } from "./ui/IconEllipsis"
import { Menu } from "./ui/Menu"

export function SearchScene() {
const { index } = useIndexer()
const [query, setQuery] = useState("")
const { searchOptions, optionsMenuItems } = useOptionsMenuItems()
const { results } = useFilter(query, searchOptions, index)

const handleQueryChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
startTransition(() => {
setQuery(event.target.value)
})
}, [])

const hasResults = useMemo(() => {
for (const [, resultForRootNodeType] of entries(results)) {
if (!resultForRootNodeType) continue

for (const resultsForRootId of Object.values(resultForRootNodeType)) {
if (resultsForRootId.length > 0) return true
}
}
return false
}, [results])

useEffect(() => {
if (query && hasResults) {
framer.showUI({
height: 320,
})
} else if (query && !hasResults) {
framer.showUI({
height: 140,
})
} else {
framer.showUI({
height: 64,
})
}
}, [query, hasResults])

return (
<main className="flex flex-col h-full">
<div className="flex gap-2 border-b border-framer-divider border-t py-3 mx-3">
<SearchInput value={query} onChange={handleQueryChange} />
<Menu items={optionsMenuItems}>
<IconEllipsis />
</Menu>
</div>
<div className="flex-1 overflow-y-auto px-4 flex flex-col">
{query && hasResults ? <SearchResultsByRootType results={results} /> : <NoResults />}
</div>
</main>
)
}

// All components below this line are temporary and will be removed when the search results are implemented
// Having them ensures it's easier to verify the indexer and filterer are working as expected
Comment thread
elmarburke marked this conversation as resolved.

function NoResults() {
return (
<div className="flex-1 flex justify-center items-center">
<div className="text-center text-amber-500">No results found.</div>
</div>
)
}

function SearchResultsByRootType({ results }: { results: ReadonlyGroupedResults }) {
return Object.entries(results).map(([rootNodeType, resultsByRootId]) => (
<RootNodeTypeSection key={rootNodeType} resultsByRootId={resultsByRootId} />
))
}

function RootNodeTypeSection({ resultsByRootId }: { resultsByRootId: { readonly [id: string]: readonly Result[] } }) {
return (
<div className="flex flex-col gap-2 mb-4 text-amber-500">
{Object.entries(resultsByRootId).map(([rootNodeId, results]) => (
<SearchResultGroup key={rootNodeId} results={results} />
))}
</div>
)
}

function SearchResultGroup({ results }: { results: readonly Result[] }) {
const [first] = results

if (!first) return null

return (
<div>
<div className="text-lg text-amber-800">
{first.entry.rootNodeName} ({first.entry.rootNodeType} {first.entry.rootNode.id})
</div>
<ul className="flex flex-col gap-2">
{results.map(result => (
<SearchResult key={result.id} result={result} />
))}
</ul>
</div>
)
}

function SearchResult({ result }: { result: Result }) {
if (result.type === "CollectionItem") {
return <CollectionItemSearchResult result={result} />
} else if (result.type === "Node") {
return <NodeSearchResult result={result} />
}

assertNever(result)
}

function NodeSearchResult({ result }: { result: NodeResult }) {
if (!result.entry.text) return null

return <SearchResultRanges text={result.entry.text} ranges={result.ranges} resultId={result.id} />
}

function CollectionItemSearchResult({ result }: { result: CollectionItemResult }) {
if (!result.text) return null

return <SearchResultRanges text={result.text} ranges={result.ranges} resultId={result.id} />
}

function SearchResultRanges({ text, ranges, resultId }: { text: string; ranges: readonly Range[]; resultId: string }) {
return ranges.map(range => (
<li key={`${resultId}-${range.join("-")}`} className="text-ellipsis overflow-hidden whitespace-nowrap">
<HighlightedTextWithContext text={text} range={range} /> ({resultId})
</li>
))
}

function HighlightedTextWithContext({ text, range }: { text: string; range: Range }) {
const [start, end] = range
const before = text.slice(0, start)
const match = text.slice(start, end)
const after = text.slice(end)

return (
<>
{before}
<span className="font-bold">{match}</span>
{after}
</>
)
}

/**
* Contains if you can filter by a root node type.
*
* During current state of the plugin, not all types are indexed yet.
*/
const optionsEnabled = {
ComponentNode: true,
WebPageNode: true,
Collection: true,
} as const satisfies Record<RootNodeType, boolean>

const defaultSearchOptions = entries(optionsEnabled)
.filter(([, enabled]) => enabled)
.map(([rootNode]) => rootNode)

const optionsMenuLabels = {
ComponentNode: "Components",
WebPageNode: "Pages",
Collection: "Collections",
} as const satisfies Record<RootNodeType, string>

function useOptionsMenuItems() {
const [searchOptions, setSearchOptions] = useState<readonly RootNodeType[]>(defaultSearchOptions)

const optionsMenuItems = useMemo((): MenuItem[] => {
return entries(optionsEnabled).map(([rootNode, enabled]) => ({
id: rootNode,
label: optionsMenuLabels[rootNode],
enabled,
checked: searchOptions.includes(rootNode),
onAction: () => {
setSearchOptions(prev => {
if (prev.includes(rootNode)) {
return prev.filter(option => option !== rootNode)
}

return [...prev, rootNode]
})
},
}))
}, [searchOptions])

return { searchOptions, optionsMenuItems }
}
18 changes: 18 additions & 0 deletions plugins/global-search/src/components/ui/IconEllipsis.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
export function IconEllipsis() {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="13"
fill="none"
viewBox="0 0 16 13"
aria-label="Ellipsis"
>
<title>Ellipsis</title>
<path
d="M 2.999 5 C 3.827 5 4.499 5.672 4.499 6.5 C 4.499 7.328 3.827 8 2.999 8 C 2.171 8 1.499 7.328 1.499 6.5 C 1.499 5.672 2.171 5 2.999 5 Z M 7.999 5 C 8.827 5 9.499 5.672 9.499 6.5 C 9.499 7.328 8.827 8 7.999 8 C 7.171 8 6.499 7.328 6.499 6.5 C 6.499 5.672 7.171 5 7.999 5 Z M 12.999 5 C 13.827 5 14.499 5.672 14.499 6.5 C 14.499 7.328 13.827 8 12.999 8 C 12.171 8 11.499 7.328 11.499 6.5 C 11.499 5.672 12.171 5 12.999 5 Z"
fill="currentColor"
/>
</svg>
)
}
12 changes: 12 additions & 0 deletions plugins/global-search/src/components/ui/IconSearch.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import type { SVGProps } from "react"

export function IconSearch(props: SVGProps<SVGSVGElement>) {
return (
<svg xmlns="http://www.w3.org/2000/svg" width={11.4} height={11.1} fill="none" overflow="visible" {...props}>
<path
fill="currentColor"
d="M5 0a5 5 0 014.1 7.8l2 2a.8.8 0 01-1 1.1l-2-2A5 5 0 115 0zM1.5 5a3.5 3.5 0 107 0 3.5 3.5 0 00-7 0z"
/>
</svg>
)
}
44 changes: 44 additions & 0 deletions plugins/global-search/src/components/ui/Menu.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { framer, type MenuItem } from "framer-plugin"
import { memo, type ReactNode, useCallback, useRef } from "react"

interface MenuProps {
items: MenuItem[]
children: ReactNode
}

export const Menu = memo(function Menu({ items, children }: MenuProps) {
const buttonRef = useRef<HTMLButtonElement>(null)

const toggleMenu = useCallback(
async (event: React.MouseEvent<HTMLButtonElement> | React.KeyboardEvent<HTMLButtonElement>) => {
if (!buttonRef.current) return
if ("key" in event && event.key !== "Enter" && event.key !== " ") return

const buttonBounds = buttonRef.current.getBoundingClientRect()

await framer.showContextMenu(items, {
location: { x: buttonBounds.right - 5, y: buttonBounds.bottom },
placement: "bottom-left",
width: 200,
})
},
[items]
)

return (
<div className="relative">
<button
type="button"
ref={buttonRef}
onMouseDown={toggleMenu}
onKeyDown={toggleMenu}
className="border border-amber-500 group size-6 text-white rounded-md flex-shrink-0 flex items-center justify-center bg-transparent p-0 focus-visible:outline-none hover:text-framer-text-base focus-visible:text-framer-text-base disabled:opacity-50 disabled:pointer-events-none disabled:cursor-default visible"
aria-haspopup="true"
>
<div className="flex items-center justify-center w-fit h-fit flex-shrink-0 bg-transparent text-framer-text-tertiary group-hover:text-framer-text-base group-focus-visible:text-framer-text-base">
{children}
</div>
</button>
</div>
)
})
8 changes: 8 additions & 0 deletions plugins/global-search/src/utils/assert.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export function assert(condition: unknown, ...message: unknown[]): asserts condition {
if (condition) return
throw Error(`Assertion error: ${message.join(", ")}`)
}

export function assertNever(x: never): never {
throw new Error(`Unexpected value: ${String(x)}`)
}
Loading
Loading