Skip to content

Commit

Permalink
refactor(core): new quick search service
Browse files Browse the repository at this point in the history
  • Loading branch information
EYHN committed Jun 14, 2024
1 parent c80be85 commit fa3fae8
Show file tree
Hide file tree
Showing 60 changed files with 1,644 additions and 2,005 deletions.
3 changes: 2 additions & 1 deletion packages/common/infra/src/framework/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@ export * from './error';
export { createEvent, OnEvent } from './event';
export { Framework } from './framework';
export { createIdentifier } from './identifier';
export type { FrameworkProvider, ResolveOptions } from './provider';
export type { ResolveOptions } from './provider';
export { FrameworkProvider } from './provider';
export type { GeneralIdentifier } from './types';
6 changes: 6 additions & 0 deletions packages/common/infra/src/framework/react/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ export const FrameworkStackContext = React.createContext<FrameworkProvider[]>([
Framework.EMPTY.provider(),
]);

export function useFramework(): FrameworkProvider {
const stack = useContext(FrameworkStackContext);

return stack[stack.length - 1]; // never null, because the default value
}

export function useService<T extends Service>(
identifier: GeneralIdentifier<T>
): T {
Expand Down
1 change: 0 additions & 1 deletion packages/common/infra/src/modules/doc/entities/record.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ export type DocMode = 'edgeless' | 'page';
*/
export class DocRecord extends Entity<{ id: string }> {
id: string = this.props.id;
meta: Partial<DocMeta> | null = null;
constructor(private readonly docsStore: DocsStore) {
super();
}
Expand Down
22 changes: 22 additions & 0 deletions packages/common/infra/src/modules/doc/services/docs.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { Unreachable } from '@affine/env/constant';

import { Service } from '../../../framework';
import { initEmptyPage } from '../../../initialization';
import { ObjectPool } from '../../../utils';
import type { Doc } from '../entities/doc';
import type { DocMode } from '../entities/record';
import { DocRecordList } from '../entities/record-list';
import { DocScope } from '../scopes/doc';
import type { DocsStore } from '../stores/docs';
Expand Down Expand Up @@ -46,4 +50,22 @@ export class DocsService extends Service {

return { doc: obj, release };
}

createDoc(
options: {
mode?: DocMode;
title?: string;
} = {}
) {
const doc = this.store.createBlockSuiteDoc();
initEmptyPage(doc, options.title);
const docRecord = this.list.doc$(doc.id).value;
if (!docRecord) {
throw new Unreachable();
}
if (options.mode) {
docRecord.setMode(options.mode);
}
return docRecord;
}
}
4 changes: 4 additions & 0 deletions packages/common/infra/src/modules/doc/stores/docs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ export class DocsStore extends Store {
return this.workspaceService.workspace.docCollection.getDoc(id);
}

createBlockSuiteDoc() {
return this.workspaceService.workspace.docCollection.createDoc();
}

watchDocIds() {
return new Observable<string[]>(subscriber => {
const emit = () => {
Expand Down
1 change: 1 addition & 0 deletions packages/frontend/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"dayjs": "^1.11.10",
"foxact": "^0.2.33",
"fractional-indexing": "^3.2.0",
"fuse.js": "^7.0.0",
"graphql": "^16.8.1",
"history": "^5.3.0",
"idb": "^8.0.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
useLitPortalFactory,
} from '@affine/component';
import { useJournalInfoHelper } from '@affine/core/hooks/use-journal';
import { QuickSearchService } from '@affine/core/modules/cmdk';
import { PeekViewService } from '@affine/core/modules/peek-view';
import { WorkbenchService } from '@affine/core/modules/workbench';
import {
Expand All @@ -19,6 +18,7 @@ import {
type DocMode,
DocService,
DocsService,
useFramework,
useLiveData,
useService,
} from '@toeverything/infra';
Expand Down Expand Up @@ -79,9 +79,9 @@ interface BlocksuiteEditorProps {
const usePatchSpecs = (page: Doc, shared: boolean, mode: DocMode) => {
const [reactToLit, portals] = useLitPortalFactory();
const peekViewService = useService(PeekViewService);
const quickSearchService = useService(QuickSearchService);
const docService = useService(DocService);
const docsService = useService(DocsService);
const framework = useFramework();
const referenceRenderer: ReferenceReactRenderer = useMemo(() => {
return function customReference(reference) {
const pageId = reference.delta.attributes?.reference?.pageId;
Expand All @@ -105,7 +105,7 @@ const usePatchSpecs = (page: Doc, shared: boolean, mode: DocMode) => {
patched = patchPeekViewService(patched, peekViewService);
}
if (!page.readonly) {
patched = patchQuickSearchService(patched, quickSearchService);
patched = patchQuickSearchService(patched, framework);
}
if (shared) {
patched = patchForSharedPage(patched);
Expand All @@ -118,9 +118,9 @@ const usePatchSpecs = (page: Doc, shared: boolean, mode: DocMode) => {
confirmModal,
docService,
docsService,
framework,
page.readonly,
peekViewService,
quickSearchService,
reactToLit,
referenceRenderer,
shared,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,16 @@ import {
type ToastOptions,
type useConfirmModal,
} from '@affine/component';
import type {
QuickSearchService,
SearchCallbackResult,
} from '@affine/core/modules/cmdk';
import { DocsSearchService } from '@affine/core/modules/docs-search';
import { resolveLinkToDoc } from '@affine/core/modules/navigation';
import type { PeekViewService } from '@affine/core/modules/peek-view';
import type { ActivePeekView } from '@affine/core/modules/peek-view/entities/peek-view';
import {
DocsQuickSearchSession,
type QuickSearchItem,
QuickSearchService,
RecentDocsQuickSearchSession,
} from '@affine/core/modules/quicksearch';
import { DebugLogger } from '@affine/debug';
import type { BlockSpec, WidgetElement } from '@blocksuite/block-std';
import {
Expand All @@ -25,7 +29,8 @@ import {
ReferenceNodeConfig,
type RootService,
} from '@blocksuite/blocks';
import type { DocMode, DocService, DocsService } from '@toeverything/infra';
import { LinkIcon } from '@blocksuite/icons';
import type { DocMode, FrameworkProvider } from '@toeverything/infra';
import { html, LitElement, type TemplateResult } from 'lit';
import { customElement } from 'lit/decorators.js';
import { literal } from 'lit/static-html.js';
Expand Down Expand Up @@ -335,7 +340,7 @@ export function patchDocModeService(

export function patchQuickSearchService(
specs: BlockSpec[],
service: QuickSearchService
framework: FrameworkProvider
) {
const rootSpec = specs.find(
spec => spec.schema.model.flavour === 'affine:page'
Expand All @@ -350,39 +355,81 @@ export function patchQuickSearchService(
pageService => {
pageService.quickSearchService = {
async searchDoc(options) {
let searchResult: SearchCallbackResult | null = null;
let searchResult: { docId: string } | { userInput: string } | null =
null;
if (options.skipSelection) {
const query = options.userInput;
if (!query) {
logger.error('No user input provided');
} else {
const searchedDoc = service.quickSearch
.getSearchedDocs(query)
.at(0);
const searchedDoc = (
await framework.get(DocsSearchService).search(query)
).at(0);
if (searchedDoc) {
searchResult = {
docId: searchedDoc.doc.id,
blockId: searchedDoc.blockId,
action: 'insert',
query,
docId: searchedDoc.docId,
};
}
}
} else {
searchResult = await service.quickSearch.search(options.userInput);
searchResult = await new Promise(resolve =>
framework.get(QuickSearchService).quickSearch.show(
[
framework.get(RecentDocsQuickSearchSession),
framework.get(DocsQuickSearchSession),
(query: string) => {
if (
(query.startsWith('http://') ||
query.startsWith('https://')) &&
resolveLinkToDoc(query) === null
) {
return [
{
id: 'link',
source: 'link',
icon: LinkIcon,
label: {
key: 'com.affine.cmdk.affine.insert-link',
},
payload: { url: query },
} as QuickSearchItem<'link', { url: string }>,
];
}
return [];
},
],
result => {
if (result === null) {
resolve(null);
return;
}
if (
result.source === 'docs' ||
result.source === 'recent-doc'
) {
resolve({
docId: result.payload.docId,
});
} else if (result.source === 'link') {
resolve({
userInput: result.payload.url,
});
}
},
{
defaultQuery: options.userInput,
label: {
key: 'com.affine.cmdk.insert-links',
},
placeholder: {
key: 'com.affine.cmdk.docs.placeholder',
},
}
)
);
}

if (searchResult) {
if ('docId' in searchResult) {
return searchResult;
} else {
return {
userInput: searchResult.query,
action: 'insert',
};
}
}
return null;
return searchResult;
},
};
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export const PageOperationCell = ({
}, [page.id, page.title, setTrashModal]);

const onOpenInSplitView = useCallback(() => {
workbench.openPage(page.id, { at: 'tail' });
workbench.openDoc(page.id, { at: 'tail' });
}, [page.id, workbench]);

const onToggleFavoritePage = useCallback(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export const OperationMenuButton = ({ ...props }: OperationMenuButtonProps) => {
}, [pageId, removeFromAllowList]);

const handleOpenInSplitView = useCallback(() => {
workbench.openPage(pageId, { at: 'tail' });
workbench.openDoc(pageId, { at: 'tail' });
}, [pageId, workbench]);

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
registerAffineUpdatesCommands,
} from '../commands';
import { usePageHelper } from '../components/blocksuite/block-suite-page-list/utils';
import { QuickSearchService } from '../modules/cmdk';
import { CMDKQuickSearchService } from '../modules/quicksearch/services/cmdk';
import { useLanguageHelper } from './affine/use-language-helper';
import { useActiveBlocksuiteEditor } from './use-block-suite-editor';
import { useNavigateHelper } from './use-navigate-helper';
Expand All @@ -33,7 +33,7 @@ function hasLinkPopover(editor: AffineEditorContainer | null) {
}

function registerCMDKCommand(
qsService: QuickSearchService,
service: CMDKQuickSearchService,
editor: AffineEditorContainer | null
) {
return registerAffineCommand({
Expand All @@ -51,7 +51,7 @@ function registerCMDKCommand(
if (hasLinkPopover(editor)) {
return;
}
qsService.quickSearch.toggle();
service.toggle();
},
});
}
Expand All @@ -65,15 +65,15 @@ export function useRegisterWorkspaceCommands() {
const pageHelper = usePageHelper(currentWorkspace.docCollection);
const navigationHelper = useNavigateHelper();
const [editor] = useActiveBlocksuiteEditor();
const quickSearch = useService(QuickSearchService);
const cmdkQuickSearchService = useService(CMDKQuickSearchService);

useEffect(() => {
const unsub = registerCMDKCommand(quickSearch, editor);
const unsub = registerCMDKCommand(cmdkQuickSearchService, editor);

return () => {
unsub();
};
}, [editor, quickSearch]);
}, [cmdkQuickSearchService, editor]);

// register AffineUpdatesCommands
useEffect(() => {
Expand Down
Loading

0 comments on commit fa3fae8

Please sign in to comment.