|
| 1 | +import { Entity, LiveData } from '@toeverything/infra'; |
| 2 | +import Fuse from 'fuse.js'; |
| 3 | + |
| 4 | +import type { TagService } from '../../tag'; |
| 5 | +import type { QuickSearchSession } from '../providers/quick-search-provider'; |
| 6 | +import type { QuickSearchGroup } from '../types/group'; |
| 7 | +import type { QuickSearchItem } from '../types/item'; |
| 8 | +import { highlighter } from '../utils/highlighter'; |
| 9 | +import { QuickSearchTagIcon } from '../views/tag-icon'; |
| 10 | + |
| 11 | +const group: QuickSearchGroup = { |
| 12 | + id: 'tags', |
| 13 | + label: { |
| 14 | + key: 'com.affine.cmdk.affine.category.affine.tags', |
| 15 | + }, |
| 16 | + score: 10, |
| 17 | +}; |
| 18 | + |
| 19 | +export class TagsQuickSearchSession |
| 20 | + extends Entity |
| 21 | + implements QuickSearchSession<'tags', { tagId: string }> |
| 22 | +{ |
| 23 | + constructor(private readonly tagService: TagService) { |
| 24 | + super(); |
| 25 | + } |
| 26 | + |
| 27 | + query$ = new LiveData(''); |
| 28 | + |
| 29 | + items$: LiveData<QuickSearchItem<'tags', { tagId: string }>[]> = |
| 30 | + LiveData.computed(get => { |
| 31 | + const query = get(this.query$); |
| 32 | + |
| 33 | + // has performance issues with `tagList.tagMetas$` |
| 34 | + const tags = get(this.tagService.tagList.tags$).map(tag => ({ |
| 35 | + id: tag.id, |
| 36 | + title: get(tag.value$), |
| 37 | + color: get(tag.color$), |
| 38 | + })); |
| 39 | + |
| 40 | + const fuse = new Fuse(tags, { |
| 41 | + keys: ['title'], |
| 42 | + includeMatches: true, |
| 43 | + includeScore: true, |
| 44 | + ignoreLocation: true, |
| 45 | + threshold: 0.0, |
| 46 | + }); |
| 47 | + |
| 48 | + const result = fuse.search(query); |
| 49 | + |
| 50 | + return result.map<QuickSearchItem<'tags', { tagId: string }>>( |
| 51 | + ({ item, matches, score = 1 }) => { |
| 52 | + const normalizedRange = ([start, end]: [number, number]) => |
| 53 | + [ |
| 54 | + start, |
| 55 | + end + |
| 56 | + 1 /* in fuse, the `end` is different from the `substring` */, |
| 57 | + ] as [number, number]; |
| 58 | + const titleMatches = matches |
| 59 | + ?.filter(match => match.key === 'title') |
| 60 | + .flatMap(match => match.indices.map(normalizedRange)); |
| 61 | + |
| 62 | + const Icon = () => QuickSearchTagIcon({ color: item.color }); |
| 63 | + |
| 64 | + return { |
| 65 | + id: 'tag:' + item.id, |
| 66 | + source: 'tags', |
| 67 | + label: { |
| 68 | + title: (highlighter( |
| 69 | + item.title, |
| 70 | + '<b>', |
| 71 | + '</b>', |
| 72 | + titleMatches ?? [] |
| 73 | + ) ?? |
| 74 | + item.title) || { |
| 75 | + key: 'Untitled', |
| 76 | + }, |
| 77 | + }, |
| 78 | + group, |
| 79 | + score: 1 - score, |
| 80 | + icon: Icon, |
| 81 | + matches: titleMatches, |
| 82 | + payload: { tagId: item.id }, |
| 83 | + }; |
| 84 | + } |
| 85 | + ); |
| 86 | + }); |
| 87 | + |
| 88 | + query(query: string) { |
| 89 | + this.query$.next(query); |
| 90 | + } |
| 91 | +} |
0 commit comments