From 8f541eb321490d1eec7df66eb131a7ac70cd0ee0 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 22 Mar 2026 12:09:58 -0400 Subject: [PATCH] feat: Add command bar search to public shares (#11846) Replace the SearchPopover in the shared sidebar with a command bar that opens via Cmd+K or a search button. Search results are scoped to the share and navigate to shared document paths with highlight support. Co-authored-by: Claude Opus 4.6 --- .../CommandBar/SharedCommandBar.tsx | 92 ++++++ .../CommandBar/SharedSearchActions.tsx | 97 ++++++ app/components/SearchPopover.tsx | 289 ------------------ app/components/Sidebar/Shared.tsx | 52 +++- app/scenes/Shared/index.tsx | 2 + shared/i18n/locales/en_US/translation.json | 2 - 6 files changed, 232 insertions(+), 302 deletions(-) create mode 100644 app/components/CommandBar/SharedCommandBar.tsx create mode 100644 app/components/CommandBar/SharedSearchActions.tsx delete mode 100644 app/components/SearchPopover.tsx diff --git a/app/components/CommandBar/SharedCommandBar.tsx b/app/components/CommandBar/SharedCommandBar.tsx new file mode 100644 index 0000000000..125733f650 --- /dev/null +++ b/app/components/CommandBar/SharedCommandBar.tsx @@ -0,0 +1,92 @@ +import { useKBar, KBarPositioner, KBarAnimator, KBarSearch } from "kbar"; +import { observer } from "mobx-react"; +import * as React from "react"; +import { useTranslation } from "react-i18next"; +import { Portal } from "react-portal"; +import styled from "styled-components"; +import breakpoint from "styled-components-breakpoint"; +import { depths, s } from "@shared/styles"; +import CommandBarResults from "./CommandBarResults"; +import SharedSearchActions from "./SharedSearchActions"; + +/** + * A simplified command bar for public shares that only provides search. + */ +function SharedCommandBar() { + const { t } = useTranslation(); + + return ( + + + + + + + + + + ); +} + +type Props = { + children?: React.ReactNode; +}; + +const KBarPortal: React.FC = ({ children }: Props) => { + const { showing } = useKBar((state) => ({ + showing: state.visualState !== "hidden", + })); + + if (!showing) { + return null; + } + + return {children}; +}; + +const Positioner = styled(KBarPositioner)` + z-index: ${depths.commandBar}; +`; + +const SearchInput = styled(KBarSearch)` + position: relative; + padding: 16px 12px; + margin: 0 8px; + width: calc(100% - 16px); + outline: none; + border: none; + background: ${s("menuBackground")}; + color: ${s("text")}; + + &:not(:last-child) { + border-bottom: 1px solid ${s("inputBorder")}; + } + + &:disabled, + &::placeholder { + color: ${s("placeholder")}; + opacity: 1; + } +`; + +const Animator = styled(KBarAnimator)` + max-width: 600px; + max-height: 75vh; + width: 90vw; + background: ${s("menuBackground")}; + color: ${s("text")}; + border-radius: 8px; + overflow: hidden; + box-shadow: rgb(0 0 0 / 40%) 0px 16px 60px; + transition: max-width 0.2s ease-in-out; + + ${breakpoint("desktopLarge")` + max-width: 740px; + `}; + + @media print { + display: none; + } +`; + +export default observer(SharedCommandBar); diff --git a/app/components/CommandBar/SharedSearchActions.tsx b/app/components/CommandBar/SharedSearchActions.tsx new file mode 100644 index 0000000000..3669234e54 --- /dev/null +++ b/app/components/CommandBar/SharedSearchActions.tsx @@ -0,0 +1,97 @@ +import { useKBar } from "kbar"; +import { observer } from "mobx-react"; +import { DocumentIcon } from "outline-icons"; +import * as React from "react"; +import Icon from "@shared/components/Icon"; +import useShare from "@shared/hooks/useShare"; +import { Minute } from "@shared/utils/time"; +import { createAction } from "~/actions"; +import { DocumentSection } from "~/actions/sections"; +import useCommandBarActions from "~/hooks/useCommandBarActions"; +import useStores from "~/hooks/useStores"; +import history from "~/utils/history"; +import { sharedModelPath } from "~/utils/routeHelpers"; +import type { SearchResult } from "~/types"; + +interface CacheEntry { + timestamp: number; + results: SearchResult[]; +} + +const cacheTTL = Minute.ms * 5; + +/** + * Registers search result actions in the command bar scoped to a public share. + */ +function SharedSearchActions() { + const { documents } = useStores(); + const { shareId } = useShare(); + const searchCache = React.useRef>(new Map()); + const [results, setResults] = React.useState([]); + + const { searchQuery } = useKBar((state) => ({ + searchQuery: state.searchQuery, + })); + + React.useEffect(() => { + if (!searchQuery || !shareId) { + setResults([]); + return; + } + + const now = Date.now(); + const cachedEntry = searchCache.current.get(searchQuery); + const isExpired = cachedEntry + ? now - cachedEntry.timestamp > cacheTTL + : true; + + if (cachedEntry && !isExpired) { + setResults(cachedEntry.results); + return; + } + + const currentQuery = searchQuery; + void documents.search({ query: searchQuery, shareId }).then((res) => { + searchCache.current.set(currentQuery, { timestamp: now, results: res }); + setResults(res); + }); + }, [documents, searchQuery, shareId]); + + const actions = React.useMemo( + () => + results.map((result) => + createAction({ + id: `shared-search-${result.document.id}`, + name: result.document.titleWithDefault, + analyticsName: "Open shared search result", + section: DocumentSection, + icon: result.document.icon ? ( + + ) : ( + + ), + perform: () => { + if (shareId) { + history.push({ + pathname: sharedModelPath(shareId, result.document.url), + search: searchQuery + ? `?q=${encodeURIComponent(searchQuery)}` + : undefined, + }); + } + }, + }) + ), + [results, shareId, searchQuery] + ); + + useCommandBarActions(actions, [actions.map((a) => a.id).join("")]); + + return null; +} + +export default observer(SharedSearchActions); diff --git a/app/components/SearchPopover.tsx b/app/components/SearchPopover.tsx deleted file mode 100644 index 592518878c..0000000000 --- a/app/components/SearchPopover.tsx +++ /dev/null @@ -1,289 +0,0 @@ -import debounce from "lodash/debounce"; -import { observer } from "mobx-react"; -import * as React from "react"; -import { useTranslation } from "react-i18next"; -import styled from "styled-components"; -import Empty from "~/components/Empty"; -import { Outline } from "~/components/Input"; -import InputSearch from "~/components/InputSearch"; -import Placeholder from "~/components/List/Placeholder"; -import PaginatedList from "~/components/PaginatedList"; -import { - Popover, - PopoverAnchor, - PopoverContent, -} from "~/components/primitives/Popover"; -import { id as bodyContentId } from "~/components/SkipNavContent"; -import useKeyDown from "~/hooks/useKeyDown"; -import useStores from "~/hooks/useStores"; -import { preventDefault } from "~/utils/events"; -import type { SearchResult } from "~/types"; -import SearchListItem from "./SearchListItem"; - -interface Props extends React.HTMLAttributes { - shareId: string; - className?: string; -} - -function SearchPopover({ shareId, className }: Props) { - const { t } = useTranslation(); - const { documents } = useStores(); - const focusRef = React.useRef(null); - const searchInputRef = React.useRef(null); - const firstSearchItem = React.useRef(null); - - const [open, setOpen] = React.useState(false); - const [query, setQuery] = React.useState(""); - const [searchResults, setSearchResults] = React.useState< - SearchResult[] | undefined - >(); - - // Cache search results by query string to avoid redundant API calls - const cacheRef = React.useRef(new Map()); - const queryRef = React.useRef(query); - queryRef.current = query; - - // When the query changes, restore cached results (including empty) or keep - // previous results visible until new results arrive to avoid layout shift - React.useEffect(() => { - if (!query) { - setSearchResults(undefined); - return; - } - - const cached = cacheRef.current.get(query); - if (cached !== undefined) { - setSearchResults(cached); - if (cached.length) { - setOpen(true); - } - } - }, [query]); - - const performSearch = React.useCallback( - async ({ - query: searchQuery, - offset = 0, - ...options - }: Record) => { - if (!searchQuery?.length) { - return undefined; - } - - // Return cached results for first-page lookups - if (offset === 0 && cacheRef.current.has(searchQuery)) { - return cacheRef.current.get(searchQuery)!; - } - - // Force offset to 0 for new queries — PaginatedList's reset() sets - // offset via setState but fetchResults still uses the stale value - // from its closure - if (!cacheRef.current.has(searchQuery)) { - offset = 0; - } - - const response = await documents.search({ - query: searchQuery, - shareId, - offset, - ...options, - }); - - // Build complete result set in cache: replace for new queries, append - // for pagination of an existing query - const existing = cacheRef.current.get(searchQuery); - cacheRef.current.set( - searchQuery, - existing ? [...existing, ...response] : response - ); - - // Only update state if this query is still current to prevent stale - // results from overwriting newer results after a race condition - if (queryRef.current === searchQuery) { - setSearchResults(cacheRef.current.get(searchQuery)!); - setOpen(true); - } - - return response; - }, - [documents, shareId] - ); - - const debouncedSetQuery = React.useMemo( - () => - debounce((value: string) => { - setQuery(value); - setOpen(!!value); - }, 250), - [] - ); - - const handleSearchInputChange = React.useCallback( - (event: React.ChangeEvent) => { - debouncedSetQuery(event.target.value.trim()); - }, - [debouncedSetQuery] - ); - - React.useEffect(() => () => debouncedSetQuery.cancel(), [debouncedSetQuery]); - - const handleEscapeList = React.useCallback( - () => searchInputRef.current?.focus(), - [] - ); - - const handleSearchInputFocus = React.useCallback(() => { - focusRef.current = searchInputRef.current; - }, []); - - const handleKeyDown = React.useCallback( - (ev: React.KeyboardEvent) => { - if (ev.nativeEvent.isComposing) { - return; - } - - if (ev.key === "Enter") { - if (searchResults) { - setOpen(true); - } - return; - } - - if (ev.key === "ArrowDown" && !ev.shiftKey) { - if (ev.currentTarget.value.length) { - const atEnd = - ev.currentTarget.value.length === ev.currentTarget.selectionStart; - - if (atEnd) { - setOpen(true); - } - if (open || atEnd) { - ev.preventDefault(); - firstSearchItem.current?.focus(); - } - } - return; - } - - if (ev.key === "ArrowUp") { - if (open) { - setOpen(false); - if (!ev.shiftKey) { - ev.preventDefault(); - } - } - if (ev.currentTarget.value && ev.currentTarget.selectionEnd === 0) { - ev.currentTarget.selectionStart = 0; - ev.currentTarget.selectionEnd = ev.currentTarget.value.length; - ev.preventDefault(); - } - return; - } - - if (ev.key === "Escape" && open) { - setOpen(false); - ev.preventDefault(); - } - }, - [open, searchResults] - ); - - const handleSearchItemClick = React.useCallback(() => { - setOpen(false); - setQuery(""); - if (searchInputRef.current) { - searchInputRef.current.value = ""; - focusRef.current = document.getElementById(bodyContentId); - } - }, []); - - useKeyDown("/", (ev) => { - if ( - searchInputRef.current && - searchInputRef.current !== document.activeElement - ) { - searchInputRef.current.focus(); - ev.preventDefault(); - } - }); - - return ( - - - - - { - const target = event.target as Element | null; - if (target === searchInputRef.current) { - event.preventDefault(); - } - }} - > - - role="listbox" - options={{ - query, - snippetMinWords: 10, - snippetMaxWords: 11, - limit: 10, - }} - items={searchResults} - fetch={performSearch} - onEscape={handleEscapeList} - empty={ - {t("No results for {{query}}", { query })} - } - loading={} - renderItem={(item, index) => ( - - )} - /> - - - ); -} - -const NoResults = styled(Empty)` - padding: 0 12px; - margin: 6px 0; -`; - -const PlaceholderList = styled(Placeholder)` - padding: 6px 12px; -`; - -const StyledInputSearch = styled(InputSearch)` - ${Outline} { - border-radius: 16px; - } -`; - -export default observer(SearchPopover); diff --git a/app/components/Sidebar/Shared.tsx b/app/components/Sidebar/Shared.tsx index 84e8165ffc..e9787332dd 100644 --- a/app/components/Sidebar/Shared.tsx +++ b/app/components/Sidebar/Shared.tsx @@ -1,10 +1,15 @@ +import { useKBar } from "kbar"; import { observer } from "mobx-react"; +import { SearchIcon } from "outline-icons"; +import { useCallback, useEffect } from "react"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; +import { s } from "@shared/styles"; +import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper"; +import { metaDisplay } from "@shared/utils/keyboard"; import type Share from "~/models/Share"; import Flex from "~/components/Flex"; import Scrollable from "~/components/Scrollable"; -import SearchPopover from "~/components/SearchPopover"; import useCurrentUser from "~/hooks/useCurrentUser"; import useStores from "~/hooks/useStores"; import history from "~/utils/history"; @@ -17,8 +22,6 @@ import Section from "./components/Section"; import { SharedCollectionLink } from "./components/SharedCollectionLink"; import { SharedDocumentLink } from "./components/SharedDocumentLink"; import SidebarButton from "./components/SidebarButton"; -import { useEffect } from "react"; -import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper"; type Props = { share: Share; @@ -29,6 +32,7 @@ function SharedSidebar({ share }: Props) { const user = useCurrentUser({ rejectOnEmpty: false }); const { ui, documents, collections } = useStores(); const { t } = useTranslation(); + const { query } = useKBar(); const teamAvailable = !!team?.name; const rootNode = share.tree; @@ -38,6 +42,10 @@ function SharedSidebar({ share }: Props) { ? ProsemirrorHelper.isEmptyData(collection?.data) : false; + const handleOpenSearch = useCallback(() => { + query.toggle(); + }, [query]); + useEffect(() => { ui.tocVisible = share.showTOC; }, []); @@ -64,9 +72,11 @@ function SharedSidebar({ share }: Props) { )} - - - + + + {t("Search")} + {metaDisplay}K +
{share.collectionId ? ( @@ -102,14 +112,34 @@ const TopSection = styled(Flex)` flex-shrink: 0; `; -const SearchWrapper = styled.div` +const SearchButton = styled.button` + display: flex; + align-items: center; + gap: 8px; width: 100%; + padding: 6px 12px; + margin: 8px 0; + border: 1px solid ${s("inputBorder")}; + border-radius: 16px; + background: ${s("background")}; + color: ${s("textTertiary")}; + cursor: var(--pointer); + font-size: 14px; + + &:hover { + border-color: ${s("inputBorderFocused")}; + color: ${s("textSecondary")}; + } `; -const StyledSearchPopover = styled(SearchPopover)` - width: 100%; - transition: width 100ms ease-out; - margin: 8px 0; +const SearchLabel = styled.span` + flex-grow: 1; + text-align: left; +`; + +const Shortcut = styled.span` + flex-shrink: 0; + font-size: 13px; `; export default observer(SharedSidebar); diff --git a/app/scenes/Shared/index.tsx b/app/scenes/Shared/index.tsx index 032ab9998f..bc8f6257ee 100644 --- a/app/scenes/Shared/index.tsx +++ b/app/scenes/Shared/index.tsx @@ -11,6 +11,7 @@ import Collection from "~/models/Collection"; import Document from "~/models/Document"; import type Share from "~/models/Share"; import Error404 from "~/scenes/Errors/Error404"; +import SharedCommandBar from "~/components/CommandBar/SharedCommandBar"; import { DocumentContextProvider } from "~/components/DocumentContext"; import Layout from "~/components/Layout"; import Sidebar from "~/components/Sidebar/Shared"; @@ -270,6 +271,7 @@ function SharedScene() { ) : null} + diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index cb03a58f0e..3450069eb8 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -427,8 +427,6 @@ "Current version": "Current version", "{{userName}} edited": "{{userName}} edited", "Revision options": "Revision options", - "Results": "Results", - "No results for {{query}}": "No results for {{query}}", "Manage": "Manage", "All members": "All members", "Everyone in the workspace": "Everyone in the workspace",