mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-07-21 12:06:35 +08:00
feat(core): doc database properties (#8520)
fix AF-1454
1. move inline tags editor to components
2. add progress component
3. adjust doc properties styles for desktop
4. subscribe bs database links and display in doc info
5. move update/create dates to doc info
6. a trivial e2e test
<div class='graphite__hidden'>
<div>🎥 Video uploaded on Graphite:</div>
<a href="https://app.graphite.dev/media/video/T2klNLEk0wxLh4NRDzhk/eed266c1-fdac-4f0e-baa9-4aa00d14a2e8.mp4">
<img src="https://app.graphite.dev/api/v1/graphite/video/thumbnail/T2klNLEk0wxLh4NRDzhk/eed266c1-fdac-4f0e-baa9-4aa00d14a2e8.mp4">
</a>
</div>
<video src="https://graphite-user-uploaded-assets-prod.s3.amazonaws.com/T2klNLEk0wxLh4NRDzhk/eed266c1-fdac-4f0e-baa9-4aa00d14a2e8.mp4">10月23日.mp4</video>
This commit is contained in:
@@ -1,10 +1,22 @@
|
||||
import { type Framework, WorkspaceScope } from '@toeverything/infra';
|
||||
import {
|
||||
DocsService,
|
||||
type Framework,
|
||||
WorkspaceScope,
|
||||
} from '@toeverything/infra';
|
||||
|
||||
import { DocsSearchService } from '../docs-search';
|
||||
import { DocInfoModal } from './entities/modal';
|
||||
import { DocDatabaseBacklinksService } from './services/doc-database-backlinks';
|
||||
import { DocInfoService } from './services/doc-info';
|
||||
|
||||
export { DocDatabaseBacklinkInfo } from './views/database-properties/doc-database-backlink-info';
|
||||
|
||||
export { DocInfoService };
|
||||
|
||||
export function configureDocInfoModule(framework: Framework) {
|
||||
framework.scope(WorkspaceScope).service(DocInfoService).entity(DocInfoModal);
|
||||
framework
|
||||
.scope(WorkspaceScope)
|
||||
.service(DocInfoService)
|
||||
.service(DocDatabaseBacklinksService, [DocsService, DocsSearchService])
|
||||
.entity(DocInfoModal);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import {
|
||||
DatabaseBlockDataSource,
|
||||
type DatabaseBlockModel,
|
||||
} from '@blocksuite/affine/blocks';
|
||||
import type { DocsService } from '@toeverything/infra';
|
||||
import { Service } from '@toeverything/infra';
|
||||
import { isEqual } from 'lodash-es';
|
||||
import { combineLatest, distinctUntilChanged, map, Observable } from 'rxjs';
|
||||
|
||||
import type { DocsSearchService } from '../../docs-search';
|
||||
import type { DatabaseRow, DatabaseValueCell } from '../types';
|
||||
import { signalToLiveData, signalToObservable } from '../utils';
|
||||
|
||||
const equalComparator = <T>(a: T, b: T) => {
|
||||
return isEqual(a, b);
|
||||
};
|
||||
|
||||
export class DocDatabaseBacklinksService extends Service {
|
||||
constructor(
|
||||
private readonly docsService: DocsService,
|
||||
private readonly docsSearchService: DocsSearchService
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
private async ensureDocLoaded(docId: string) {
|
||||
const docRef = this.docsService.open(docId);
|
||||
if (!docRef.doc.blockSuiteDoc.ready) {
|
||||
docRef.doc.blockSuiteDoc.load();
|
||||
}
|
||||
docRef.doc.setPriorityLoad(10);
|
||||
await docRef.doc.waitForSyncReady();
|
||||
return docRef;
|
||||
}
|
||||
|
||||
private adaptRowCells(dbModel: DatabaseBlockModel, rowId: string) {
|
||||
const dataSource = new DatabaseBlockDataSource(dbModel);
|
||||
|
||||
const hydratedRows$ = combineLatest([
|
||||
signalToObservable(dataSource.rows$),
|
||||
signalToObservable(dataSource.properties$),
|
||||
]).pipe(
|
||||
map(([rowIds, propertyIds]) => {
|
||||
const rowExists = rowIds.some(id => id === rowId);
|
||||
if (!rowExists) {
|
||||
return undefined;
|
||||
}
|
||||
return propertyIds
|
||||
.map<DatabaseValueCell>(id => {
|
||||
return {
|
||||
id,
|
||||
value$: signalToLiveData(
|
||||
dataSource.cellValueGet$(rowId, id)
|
||||
).distinctUntilChanged(equalComparator),
|
||||
property: {
|
||||
id,
|
||||
type$: signalToLiveData(dataSource.propertyTypeGet$(id)),
|
||||
name$: signalToLiveData(dataSource.propertyNameGet$(id)),
|
||||
data$: signalToLiveData(dataSource.propertyDataGet$(id)),
|
||||
},
|
||||
};
|
||||
})
|
||||
.filter((p: any): p is DatabaseValueCell => !!p);
|
||||
})
|
||||
);
|
||||
|
||||
return [hydratedRows$, dataSource] as const;
|
||||
}
|
||||
|
||||
// for each db doc backlink,
|
||||
private watchDatabaseRow$(backlink: {
|
||||
docId: string;
|
||||
rowId: string;
|
||||
databaseBlockId: string;
|
||||
databaseName: string | undefined;
|
||||
}) {
|
||||
return new Observable<DatabaseRow | undefined>(subscriber => {
|
||||
let disposed = false;
|
||||
let unsubscribe = () => {};
|
||||
const docRef = this.docsService.open(backlink.docId);
|
||||
const run = async () => {
|
||||
await this.ensureDocLoaded(backlink.docId);
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
const maybeDatabaseBlock = docRef.doc.blockSuiteDoc.getBlock(
|
||||
backlink.databaseBlockId
|
||||
);
|
||||
if (maybeDatabaseBlock?.flavour === 'affine:database') {
|
||||
const dbModel = maybeDatabaseBlock.model as DatabaseBlockModel;
|
||||
const [cells$, dataSource] = this.adaptRowCells(
|
||||
dbModel,
|
||||
backlink.rowId
|
||||
);
|
||||
const subscription = cells$.subscribe(cells => {
|
||||
if (cells) {
|
||||
subscriber.next({
|
||||
cells,
|
||||
id: backlink.rowId,
|
||||
doc: docRef.doc,
|
||||
docId: backlink.docId,
|
||||
databaseId: dbModel.id,
|
||||
databaseName: dbModel.title.yText.toString(),
|
||||
dataSource: dataSource,
|
||||
});
|
||||
} else {
|
||||
subscriber.next(undefined);
|
||||
}
|
||||
});
|
||||
unsubscribe = () => subscription.unsubscribe();
|
||||
} else {
|
||||
subscriber.next(undefined);
|
||||
}
|
||||
};
|
||||
|
||||
run().catch(e => {
|
||||
console.error(`failed to get database info:`, e);
|
||||
docRef.release();
|
||||
});
|
||||
|
||||
return () => {
|
||||
docRef.release();
|
||||
disposed = true;
|
||||
unsubscribe();
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// backlinks (docid:blockid:databaseBlockId)
|
||||
// -> related db rows (DatabaseRow[])
|
||||
watchDbBacklinkRows$(docId: string) {
|
||||
return this.docsSearchService.watchDatabasesTo(docId).pipe(
|
||||
distinctUntilChanged(equalComparator),
|
||||
map(rows =>
|
||||
rows.toSorted(
|
||||
(a, b) => a.databaseName?.localeCompare(b.databaseName ?? '') ?? 0
|
||||
)
|
||||
),
|
||||
map(backlinks =>
|
||||
backlinks.map(backlink => {
|
||||
return {
|
||||
...backlink,
|
||||
row$: this.watchDatabaseRow$(backlink),
|
||||
};
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { DatabaseBlockDataSource } from '@blocksuite/affine/blocks';
|
||||
import type { Doc, LiveData } from '@toeverything/infra';
|
||||
|
||||
// make database property type to be compatible with DocCustomPropertyInfo
|
||||
export type DatabaseProperty<Data = Record<string, unknown>> = {
|
||||
id: string;
|
||||
name$: LiveData<string | undefined>;
|
||||
type$: LiveData<string | undefined>;
|
||||
data$: LiveData<Data | undefined>;
|
||||
};
|
||||
|
||||
export interface DatabaseValueCell<
|
||||
T = unknown,
|
||||
Data = Record<string, unknown>,
|
||||
> {
|
||||
value$: LiveData<T>;
|
||||
property: DatabaseProperty<Data>;
|
||||
id: string;
|
||||
}
|
||||
|
||||
export interface DatabaseRow {
|
||||
cells: DatabaseValueCell[];
|
||||
id: string; // row id (block id)
|
||||
doc: Doc; // the doc that contains the database. required for editing etc.
|
||||
docId: string; // for rendering the doc reference
|
||||
dataSource: DatabaseBlockDataSource;
|
||||
databaseId: string;
|
||||
databaseName: string; // the title
|
||||
}
|
||||
|
||||
export interface DatabaseCellRendererProps {
|
||||
rowId: string;
|
||||
cell: DatabaseValueCell;
|
||||
dataSource: DatabaseBlockDataSource;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { DebugLogger } from '@affine/debug';
|
||||
import { BlockStdScope } from '@blocksuite/affine/block-std';
|
||||
import { PageEditorBlockSpecs } from '@blocksuite/affine/blocks';
|
||||
import type { Doc } from '@blocksuite/affine/store';
|
||||
import { LiveData } from '@toeverything/infra';
|
||||
import { useMemo } from 'react';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
const logger = new DebugLogger('doc-info');
|
||||
|
||||
interface ReadonlySignal<T> {
|
||||
subscribe: (fn: (value: T) => void) => () => void;
|
||||
}
|
||||
|
||||
export function signalToObservable<T>(
|
||||
signal: ReadonlySignal<T>
|
||||
): Observable<T> {
|
||||
return new Observable(subscriber => {
|
||||
const unsub = signal.subscribe(value => {
|
||||
subscriber.next(value);
|
||||
});
|
||||
return () => {
|
||||
unsub();
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function signalToLiveData<T>(
|
||||
signal: ReadonlySignal<T>,
|
||||
defaultValue: T
|
||||
): LiveData<T>;
|
||||
|
||||
export function signalToLiveData<T>(
|
||||
signal: ReadonlySignal<T>
|
||||
): LiveData<T | undefined>;
|
||||
|
||||
export function signalToLiveData<T>(
|
||||
signal: ReadonlySignal<T>,
|
||||
defaultValue?: T
|
||||
) {
|
||||
return LiveData.from(signalToObservable(signal), defaultValue);
|
||||
}
|
||||
|
||||
// todo(pengx17): use rc pool?
|
||||
export function createBlockStdScope(doc: Doc) {
|
||||
logger.debug('createBlockStdScope', doc.id);
|
||||
const std = new BlockStdScope({
|
||||
doc,
|
||||
extensions: PageEditorBlockSpecs,
|
||||
});
|
||||
return std;
|
||||
}
|
||||
|
||||
export function useBlockStdScope(doc: Doc) {
|
||||
return useMemo(() => createBlockStdScope(doc), [doc]);
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
import { CheckboxValue } from '@affine/core/components/doc-properties/types/checkbox';
|
||||
import type { LiveData } from '@toeverything/infra';
|
||||
import { useLiveData } from '@toeverything/infra';
|
||||
|
||||
import type { DatabaseCellRendererProps } from '../../../types';
|
||||
|
||||
export const CheckboxCell = ({
|
||||
cell,
|
||||
rowId,
|
||||
dataSource,
|
||||
}: DatabaseCellRendererProps) => {
|
||||
const value = useLiveData(cell.value$ as LiveData<boolean>);
|
||||
return (
|
||||
<CheckboxValue
|
||||
// todo(pengx17): better internal impl
|
||||
value={value ? 'true' : 'false'}
|
||||
onChange={v => {
|
||||
dataSource.cellValueChange(rowId, cell.property.id, v === 'true');
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,40 @@
|
||||
import { DateValue } from '@affine/core/components/doc-properties/types/date';
|
||||
import type { LiveData } from '@toeverything/infra';
|
||||
import { useLiveData } from '@toeverything/infra';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
import type { DatabaseCellRendererProps } from '../../../types';
|
||||
|
||||
const toInternalDateString = (date: unknown) => {
|
||||
if (typeof date !== 'string' && typeof date !== 'number') {
|
||||
return '';
|
||||
}
|
||||
return dayjs(date).format('YYYY-MM-DD');
|
||||
};
|
||||
|
||||
const fromInternalDateString = (date: string) => {
|
||||
return dayjs(date).toDate().getTime();
|
||||
};
|
||||
|
||||
export const DateCell = ({
|
||||
cell,
|
||||
rowId,
|
||||
dataSource,
|
||||
}: DatabaseCellRendererProps) => {
|
||||
const value = useLiveData(
|
||||
cell.value$ as LiveData<number | string | undefined>
|
||||
);
|
||||
const date = value ? toInternalDateString(value) : '';
|
||||
return (
|
||||
<DateValue
|
||||
value={date}
|
||||
onChange={v => {
|
||||
dataSource.cellValueChange(
|
||||
rowId,
|
||||
cell.property.id,
|
||||
fromInternalDateString(v)
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
import { cssVar } from '@toeverything/theme';
|
||||
import { cssVarV2 } from '@toeverything/theme/v2';
|
||||
import { style } from '@vanilla-extract/css';
|
||||
|
||||
export const link = style({
|
||||
textDecoration: 'none',
|
||||
color: cssVarV2('text/link'),
|
||||
whiteSpace: 'wrap',
|
||||
wordBreak: 'break-all',
|
||||
display: 'inline',
|
||||
});
|
||||
|
||||
export const textarea = style({
|
||||
border: 'none',
|
||||
height: '100%',
|
||||
width: '100%',
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
whiteSpace: 'wrap',
|
||||
wordBreak: 'break-all',
|
||||
padding: `6px`,
|
||||
paddingLeft: '5px',
|
||||
overflow: 'hidden',
|
||||
fontSize: cssVar('fontSm'),
|
||||
lineHeight: '22px',
|
||||
selectors: {
|
||||
'&::placeholder': {
|
||||
color: cssVar('placeholderColor'),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export const container = style({
|
||||
position: 'relative',
|
||||
outline: `1px solid transparent`,
|
||||
padding: `6px`,
|
||||
display: 'block',
|
||||
':focus-within': {
|
||||
outline: `1px solid ${cssVar('blue700')}`,
|
||||
boxShadow: cssVar('activeShadow'),
|
||||
backgroundColor: cssVarV2('layer/background/hoverOverlay'),
|
||||
},
|
||||
});
|
||||
|
||||
export const textInvisible = style({
|
||||
border: 'none',
|
||||
whiteSpace: 'wrap',
|
||||
wordBreak: 'break-all',
|
||||
overflow: 'hidden',
|
||||
visibility: 'hidden',
|
||||
fontSize: cssVar('fontSm'),
|
||||
lineHeight: '22px',
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
import { PropertyValue } from '@affine/component';
|
||||
import { AffinePageReference } from '@affine/core/components/affine/reference-link';
|
||||
import { resolveLinkToDoc } from '@affine/core/modules/navigation';
|
||||
import { useI18n } from '@affine/i18n';
|
||||
import type { LiveData } from '@toeverything/infra';
|
||||
import { useLiveData } from '@toeverything/infra';
|
||||
import {
|
||||
type ChangeEventHandler,
|
||||
type KeyboardEvent,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
|
||||
import type { DatabaseCellRendererProps } from '../../../types';
|
||||
import * as styles from './link.css';
|
||||
|
||||
export const LinkCell = ({
|
||||
cell,
|
||||
dataSource,
|
||||
rowId,
|
||||
}: DatabaseCellRendererProps) => {
|
||||
const isEmpty = useLiveData(
|
||||
cell.value$.map(value => typeof value !== 'string' || !value)
|
||||
);
|
||||
const link = useLiveData(cell.value$ as LiveData<string | undefined>) || '';
|
||||
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [tempValue, setTempValue] = useState<string>(link);
|
||||
|
||||
const ref = useRef<HTMLTextAreaElement>(null);
|
||||
const commitChange = useCallback(() => {
|
||||
dataSource.cellValueChange(rowId, cell.id, tempValue.trim());
|
||||
setEditing(false);
|
||||
setTempValue(tempValue.trim());
|
||||
}, [dataSource, rowId, cell.id, tempValue]);
|
||||
|
||||
const handleOnChange: ChangeEventHandler<HTMLTextAreaElement> = useCallback(
|
||||
e => {
|
||||
setTempValue(e.target.value);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const resolvedDocLink = useMemo(() => {
|
||||
const docInfo = resolveLinkToDoc(link);
|
||||
|
||||
if (docInfo) {
|
||||
const params = new URLSearchParams();
|
||||
if (docInfo.mode) {
|
||||
params.set('mode', docInfo.mode);
|
||||
}
|
||||
if (docInfo.blockIds) {
|
||||
params.set('blockIds', docInfo.blockIds.join(','));
|
||||
}
|
||||
if (docInfo.elementIds) {
|
||||
params.set('elementIds', docInfo.elementIds.join(','));
|
||||
}
|
||||
return {
|
||||
docId: docInfo.docId,
|
||||
params,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}, [link]);
|
||||
|
||||
const onKeydown = useCallback(
|
||||
(e: KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (e.key === 'Enter') {
|
||||
commitChange();
|
||||
} else if (e.key === 'Escape') {
|
||||
setEditing(false);
|
||||
setTempValue(link);
|
||||
}
|
||||
},
|
||||
[commitChange, link]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setTempValue(link);
|
||||
}, [link]);
|
||||
|
||||
const onClick = useCallback(() => {
|
||||
setEditing(true);
|
||||
setTimeout(() => {
|
||||
ref.current?.focus();
|
||||
});
|
||||
}, []);
|
||||
|
||||
const onLinkClick = useCallback((e: React.MouseEvent) => {
|
||||
// prevent click event from propagating to parent (editing)
|
||||
e.stopPropagation();
|
||||
setEditing(false);
|
||||
}, []);
|
||||
|
||||
const t = useI18n();
|
||||
|
||||
return (
|
||||
<PropertyValue
|
||||
className={styles.container}
|
||||
isEmpty={isEmpty}
|
||||
onClick={onClick}
|
||||
>
|
||||
{!editing ? (
|
||||
resolvedDocLink ? (
|
||||
<AffinePageReference
|
||||
pageId={resolvedDocLink.docId}
|
||||
params={resolvedDocLink.params}
|
||||
/>
|
||||
) : (
|
||||
<a
|
||||
href={link}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
onClick={onLinkClick}
|
||||
className={styles.link}
|
||||
>
|
||||
{link?.replace(/^https?:\/\//, '').trim()}
|
||||
</a>
|
||||
)
|
||||
) : (
|
||||
<>
|
||||
<textarea
|
||||
ref={ref}
|
||||
onKeyDown={onKeydown}
|
||||
className={styles.textarea}
|
||||
onBlur={commitChange}
|
||||
value={tempValue || ''}
|
||||
onChange={handleOnChange}
|
||||
data-empty={!tempValue}
|
||||
placeholder={t[
|
||||
'com.affine.page-properties.property-value-placeholder'
|
||||
]()}
|
||||
/>
|
||||
<div className={styles.textInvisible}>
|
||||
{tempValue}
|
||||
{tempValue?.endsWith('\n') || !tempValue ? <br /> : null}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</PropertyValue>
|
||||
);
|
||||
};
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import { NumberValue } from '@affine/core/components/doc-properties/types/number';
|
||||
import { useLiveData } from '@toeverything/infra';
|
||||
|
||||
import type { DatabaseCellRendererProps } from '../../../types';
|
||||
|
||||
export const NumberCell = ({
|
||||
cell,
|
||||
rowId,
|
||||
dataSource,
|
||||
}: DatabaseCellRendererProps) => {
|
||||
const value = useLiveData(cell.value$);
|
||||
return (
|
||||
<NumberValue
|
||||
value={value}
|
||||
onChange={v => {
|
||||
dataSource.cellValueChange(rowId, cell.property.id, v);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
import { Progress, PropertyValue } from '@affine/component';
|
||||
import type { LiveData } from '@toeverything/infra';
|
||||
import { useLiveData } from '@toeverything/infra';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import type { DatabaseCellRendererProps } from '../../../types';
|
||||
|
||||
export const ProgressCell = ({
|
||||
cell,
|
||||
dataSource,
|
||||
rowId,
|
||||
}: DatabaseCellRendererProps) => {
|
||||
const value = useLiveData(cell.value$ as LiveData<number>);
|
||||
const isEmpty = value === undefined;
|
||||
const [localValue, setLocalValue] = useState(value);
|
||||
|
||||
useEffect(() => {
|
||||
setLocalValue(value);
|
||||
}, [value]);
|
||||
|
||||
return (
|
||||
<PropertyValue isEmpty={isEmpty} hoverable={false}>
|
||||
<Progress
|
||||
value={localValue}
|
||||
onChange={v => {
|
||||
setLocalValue(v);
|
||||
}}
|
||||
onBlur={() => {
|
||||
dataSource.cellValueChange(rowId, cell.id, localValue);
|
||||
}}
|
||||
/>
|
||||
</PropertyValue>
|
||||
);
|
||||
};
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
import { PropertyValue } from '@affine/component';
|
||||
import type { BlockStdScope } from '@blocksuite/affine/block-std';
|
||||
import {
|
||||
DefaultInlineManagerExtension,
|
||||
RichText,
|
||||
} from '@blocksuite/affine/blocks';
|
||||
import type { Doc } from '@blocksuite/affine/store';
|
||||
import { type LiveData, useLiveData } from '@toeverything/infra';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import type * as Y from 'yjs';
|
||||
|
||||
import type { DatabaseCellRendererProps } from '../../../types';
|
||||
import { useBlockStdScope } from '../../../utils';
|
||||
|
||||
// todo(@pengx17): handle markdown/keyboard shortcuts
|
||||
const renderRichText = ({
|
||||
doc,
|
||||
std,
|
||||
text,
|
||||
}: {
|
||||
std: BlockStdScope;
|
||||
text: Y.Text;
|
||||
doc: Doc;
|
||||
}) => {
|
||||
const inlineManager = std.get(DefaultInlineManagerExtension.identifier);
|
||||
|
||||
if (!inlineManager) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const richText = new RichText();
|
||||
richText.yText = text;
|
||||
richText.undoManager = doc.history;
|
||||
richText.readonly = doc.readonly;
|
||||
richText.attributesSchema = inlineManager.getSchema() as any;
|
||||
richText.attributeRenderer = inlineManager.getRenderer();
|
||||
return richText;
|
||||
};
|
||||
|
||||
export const RichTextCell = ({
|
||||
cell,
|
||||
dataSource,
|
||||
}: DatabaseCellRendererProps) => {
|
||||
const std = useBlockStdScope(dataSource.doc);
|
||||
const text = useLiveData(cell.value$ as LiveData<Y.Text>);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
// todo(@pengx17): following is a workaround to y.Text that it is got renewed when the cell is updated externally. however it breaks the cursor position.
|
||||
useEffect(() => {
|
||||
if (ref.current) {
|
||||
ref.current.innerHTML = '';
|
||||
const richText = renderRichText({ doc: dataSource.doc, std, text });
|
||||
if (richText) {
|
||||
ref.current.append(richText);
|
||||
return () => {
|
||||
richText.remove();
|
||||
};
|
||||
}
|
||||
}
|
||||
return () => {};
|
||||
}, [dataSource.doc, std, text]);
|
||||
return <PropertyValue ref={ref}></PropertyValue>;
|
||||
};
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
import { style } from '@vanilla-extract/css';
|
||||
|
||||
export const tagInlineEditor = style({
|
||||
width: '100%',
|
||||
padding: `6px`,
|
||||
minHeight: 34,
|
||||
});
|
||||
|
||||
export const container = style({
|
||||
padding: '0px !important',
|
||||
});
|
||||
+259
@@ -0,0 +1,259 @@
|
||||
/* eslint-disable rxjs/finnish */
|
||||
|
||||
import { PropertyValue } from '@affine/component';
|
||||
import { type TagLike, TagsInlineEditor } from '@affine/component/ui/tags';
|
||||
import { paletteLineToTag, TagService } from '@affine/core/modules/tag';
|
||||
import type { DatabaseBlockDataSource } from '@blocksuite/affine/blocks';
|
||||
import type { SelectTag } from '@blocksuite/data-view';
|
||||
import { LiveData, useLiveData, useService } from '@toeverything/infra';
|
||||
import { nanoid } from 'nanoid';
|
||||
import { useCallback, useMemo } from 'react';
|
||||
|
||||
import type {
|
||||
DatabaseCellRendererProps,
|
||||
DatabaseValueCell,
|
||||
} from '../../../types';
|
||||
import * as styles from './select.css';
|
||||
|
||||
interface SelectPropertyData {
|
||||
options: SelectTag[];
|
||||
}
|
||||
|
||||
type SelectCellValue = string[] | string;
|
||||
|
||||
type SelectCell<T extends SelectCellValue> = DatabaseValueCell<
|
||||
T,
|
||||
SelectPropertyData
|
||||
>;
|
||||
|
||||
type SingleSelectCell = SelectCell<string>;
|
||||
type MultiSelectCell = SelectCell<string[]>;
|
||||
|
||||
const adapter = {
|
||||
getSelectedIds$(cell: SingleSelectCell | MultiSelectCell) {
|
||||
return cell.value$.map(ids => {
|
||||
if (!Array.isArray(ids)) {
|
||||
return typeof ids === 'string' ? [ids] : [];
|
||||
}
|
||||
return ids.filter(id => typeof id === 'string');
|
||||
});
|
||||
},
|
||||
|
||||
getSelectedTags$(cell: SingleSelectCell | MultiSelectCell) {
|
||||
return LiveData.computed(get => {
|
||||
const ids = get(adapter.getSelectedIds$(cell));
|
||||
const options = get(adapter.getTagOptions$(cell));
|
||||
return ids
|
||||
.map(
|
||||
id =>
|
||||
typeof id === 'string' && options.find(option => option.id === id)
|
||||
)
|
||||
.filter(option => !!option);
|
||||
});
|
||||
},
|
||||
|
||||
getTagOptions$(cell: SingleSelectCell | MultiSelectCell) {
|
||||
return LiveData.computed(get => {
|
||||
const data = get(cell.property.data$);
|
||||
return data?.options as SelectTag[];
|
||||
});
|
||||
},
|
||||
|
||||
updateOptions(
|
||||
cell: SingleSelectCell | MultiSelectCell,
|
||||
dataSource: DatabaseBlockDataSource,
|
||||
updater: (oldOptions: SelectTag[]) => SelectTag[]
|
||||
) {
|
||||
const oldData = dataSource.propertyDataGet(cell.property.id);
|
||||
return dataSource.propertyDataSet(cell.property.id, {
|
||||
...oldData,
|
||||
options: updater(oldData.options as SelectTag[]),
|
||||
});
|
||||
},
|
||||
|
||||
deselectTag(
|
||||
rowId: string,
|
||||
cell: SingleSelectCell | MultiSelectCell,
|
||||
dataSource: DatabaseBlockDataSource,
|
||||
tagId: string,
|
||||
multiple: boolean
|
||||
) {
|
||||
const ids = adapter.getSelectedIds$(cell).value;
|
||||
dataSource.cellValueChange(
|
||||
rowId,
|
||||
cell.property.id,
|
||||
multiple ? ids.filter(id => id !== tagId) : undefined
|
||||
);
|
||||
},
|
||||
|
||||
selectTag(
|
||||
rowId: string,
|
||||
cell: SingleSelectCell | MultiSelectCell,
|
||||
dataSource: DatabaseBlockDataSource,
|
||||
tagId: string,
|
||||
multiple: boolean
|
||||
) {
|
||||
const ids = adapter.getSelectedIds$(cell).value;
|
||||
dataSource.cellValueChange(
|
||||
rowId,
|
||||
cell.property.id,
|
||||
multiple ? [...ids, tagId] : tagId
|
||||
);
|
||||
},
|
||||
|
||||
createTag(
|
||||
cell: SingleSelectCell | MultiSelectCell,
|
||||
dataSource: DatabaseBlockDataSource,
|
||||
newTag: TagLike
|
||||
) {
|
||||
adapter.updateOptions(cell, dataSource, options => [
|
||||
...options,
|
||||
{
|
||||
id: newTag.id,
|
||||
value: newTag.value,
|
||||
color: newTag.color,
|
||||
},
|
||||
]);
|
||||
},
|
||||
|
||||
deleteTag(
|
||||
cell: SingleSelectCell | MultiSelectCell,
|
||||
dataSource: DatabaseBlockDataSource,
|
||||
tagId: string
|
||||
) {
|
||||
adapter.updateOptions(cell, dataSource, options =>
|
||||
options.filter(option => option.id !== tagId)
|
||||
);
|
||||
},
|
||||
|
||||
updateTag(
|
||||
cell: SingleSelectCell | MultiSelectCell,
|
||||
dataSource: DatabaseBlockDataSource,
|
||||
tagId: string,
|
||||
updater: (oldTag: SelectTag) => SelectTag
|
||||
) {
|
||||
adapter.updateOptions(cell, dataSource, options =>
|
||||
options.map(option => (option.id === tagId ? updater(option) : option))
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
const BlocksuiteDatabaseSelector = ({
|
||||
cell,
|
||||
dataSource,
|
||||
rowId,
|
||||
multiple,
|
||||
}: DatabaseCellRendererProps & { multiple: boolean }) => {
|
||||
const tagService = useService(TagService);
|
||||
const selectCell = cell as any as SingleSelectCell | MultiSelectCell;
|
||||
const selectedIds = useLiveData(adapter.getSelectedIds$(selectCell));
|
||||
const tagOptions = useLiveData(adapter.getTagOptions$(selectCell));
|
||||
|
||||
const onCreateTag = useCallback(
|
||||
(name: string, color: string) => {
|
||||
// bs database uses --affine-tag-xxx colors
|
||||
const newTag = {
|
||||
id: nanoid(),
|
||||
value: name,
|
||||
color: color,
|
||||
};
|
||||
adapter.createTag(selectCell, dataSource, newTag);
|
||||
return newTag;
|
||||
},
|
||||
[dataSource, selectCell]
|
||||
);
|
||||
const onDeleteTag = useCallback(
|
||||
(tagId: string) => {
|
||||
adapter.deleteTag(selectCell, dataSource, tagId);
|
||||
},
|
||||
[dataSource, selectCell]
|
||||
);
|
||||
const onDeselectTag = useCallback(
|
||||
(tagId: string) => {
|
||||
adapter.deselectTag(rowId, selectCell, dataSource, tagId, multiple);
|
||||
},
|
||||
[selectCell, dataSource, rowId, multiple]
|
||||
);
|
||||
|
||||
const onSelectTag = useCallback(
|
||||
(tagId: string) => {
|
||||
adapter.selectTag(rowId, selectCell, dataSource, tagId, multiple);
|
||||
},
|
||||
[rowId, selectCell, dataSource, multiple]
|
||||
);
|
||||
|
||||
const tagColors = useMemo(() => {
|
||||
return tagService.tagColors.map(([name, color]) => ({
|
||||
id: name,
|
||||
value: paletteLineToTag(color), // map from palette line to tag color
|
||||
name,
|
||||
}));
|
||||
}, [tagService.tagColors]);
|
||||
|
||||
const onTagChange = useCallback(
|
||||
(tagId: string, property: string, value: string) => {
|
||||
adapter.updateTag(selectCell, dataSource, tagId, old => {
|
||||
return {
|
||||
...old,
|
||||
[property]: value,
|
||||
};
|
||||
});
|
||||
},
|
||||
[dataSource, selectCell]
|
||||
);
|
||||
|
||||
return (
|
||||
<TagsInlineEditor
|
||||
tagMode="db-label"
|
||||
className={styles.tagInlineEditor}
|
||||
tags={tagOptions}
|
||||
selectedTags={selectedIds}
|
||||
onCreateTag={onCreateTag}
|
||||
onDeleteTag={onDeleteTag}
|
||||
onDeselectTag={onDeselectTag}
|
||||
onSelectTag={onSelectTag}
|
||||
tagColors={tagColors}
|
||||
onTagChange={onTagChange}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export const SelectCell = ({
|
||||
cell,
|
||||
dataSource,
|
||||
rowId,
|
||||
}: DatabaseCellRendererProps) => {
|
||||
const isEmpty = useLiveData(
|
||||
cell.value$.map(value => Array.isArray(value) && value.length === 0)
|
||||
);
|
||||
return (
|
||||
<PropertyValue isEmpty={isEmpty} className={styles.container}>
|
||||
<BlocksuiteDatabaseSelector
|
||||
cell={cell}
|
||||
dataSource={dataSource}
|
||||
rowId={rowId}
|
||||
multiple={false}
|
||||
/>
|
||||
</PropertyValue>
|
||||
);
|
||||
};
|
||||
|
||||
export const MultiSelectCell = ({
|
||||
cell,
|
||||
dataSource,
|
||||
rowId,
|
||||
}: DatabaseCellRendererProps) => {
|
||||
const isEmpty = useLiveData(
|
||||
cell.value$.map(value => Array.isArray(value) && value.length === 0)
|
||||
);
|
||||
return (
|
||||
<PropertyValue isEmpty={isEmpty} className={styles.container}>
|
||||
<BlocksuiteDatabaseSelector
|
||||
cell={cell}
|
||||
dataSource={dataSource}
|
||||
rowId={rowId}
|
||||
multiple={true}
|
||||
/>
|
||||
</PropertyValue>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,74 @@
|
||||
import type { I18nString } from '@affine/i18n';
|
||||
import {
|
||||
CheckBoxCheckLinearIcon,
|
||||
DateTimeIcon,
|
||||
LinkIcon,
|
||||
MultiSelectIcon,
|
||||
NumberIcon,
|
||||
ProgressIcon,
|
||||
SingleSelectIcon,
|
||||
TextIcon,
|
||||
} from '@blocksuite/icons/rc';
|
||||
|
||||
import type { DatabaseCellRendererProps } from '../../types';
|
||||
import { CheckboxCell } from './cells/checkbox';
|
||||
import { DateCell } from './cells/date';
|
||||
import { LinkCell } from './cells/link';
|
||||
import { NumberCell } from './cells/number';
|
||||
import { ProgressCell } from './cells/progress';
|
||||
import { RichTextCell } from './cells/rich-text';
|
||||
import { MultiSelectCell, SelectCell } from './cells/select';
|
||||
|
||||
export const DatabaseRendererTypes = {
|
||||
'rich-text': {
|
||||
Icon: TextIcon,
|
||||
Renderer: RichTextCell,
|
||||
name: 'com.affine.page-properties.property.text',
|
||||
},
|
||||
checkbox: {
|
||||
Icon: CheckBoxCheckLinearIcon,
|
||||
Renderer: CheckboxCell,
|
||||
name: 'com.affine.page-properties.property.checkbox',
|
||||
},
|
||||
date: {
|
||||
Icon: DateTimeIcon,
|
||||
Renderer: DateCell,
|
||||
name: 'com.affine.page-properties.property.date',
|
||||
},
|
||||
number: {
|
||||
Icon: NumberIcon,
|
||||
Renderer: NumberCell,
|
||||
name: 'com.affine.page-properties.property.number',
|
||||
},
|
||||
link: {
|
||||
Icon: LinkIcon,
|
||||
Renderer: LinkCell,
|
||||
name: 'com.affine.page-properties.property.link',
|
||||
},
|
||||
progress: {
|
||||
Icon: ProgressIcon,
|
||||
Renderer: ProgressCell,
|
||||
name: 'com.affine.page-properties.property.progress',
|
||||
},
|
||||
select: {
|
||||
Icon: SingleSelectIcon,
|
||||
Renderer: SelectCell,
|
||||
name: 'com.affine.page-properties.property.select',
|
||||
},
|
||||
'multi-select': {
|
||||
Icon: MultiSelectIcon,
|
||||
Renderer: MultiSelectCell,
|
||||
name: 'com.affine.page-properties.property.multi-select',
|
||||
},
|
||||
} as Record<
|
||||
string,
|
||||
{
|
||||
Icon: React.FC<React.SVGProps<SVGSVGElement>>;
|
||||
Renderer: React.FC<DatabaseCellRendererProps>;
|
||||
name: I18nString;
|
||||
}
|
||||
>;
|
||||
|
||||
export const isSupportedDatabaseRendererType = (type?: string): boolean => {
|
||||
return type ? type in DatabaseRendererTypes : false;
|
||||
};
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
import { cssVar } from '@toeverything/theme';
|
||||
import { cssVarV2 } from '@toeverything/theme/v2';
|
||||
import { globalStyle, style } from '@vanilla-extract/css';
|
||||
|
||||
export const root = style({
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
});
|
||||
|
||||
export const section = style({
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: 4,
|
||||
});
|
||||
|
||||
export const cell = style({
|
||||
display: 'flex',
|
||||
gap: 4,
|
||||
});
|
||||
|
||||
export const divider = style({
|
||||
margin: '8px 0',
|
||||
});
|
||||
|
||||
export const spacer = style({
|
||||
flex: 1,
|
||||
});
|
||||
|
||||
export const docRefLink = style({
|
||||
maxWidth: '50%',
|
||||
fontSize: cssVar('fontSm'),
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
whiteSpace: 'nowrap',
|
||||
color: cssVarV2('text/tertiary'),
|
||||
});
|
||||
|
||||
export const cellList = style({
|
||||
padding: '0 2px',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: 4,
|
||||
});
|
||||
|
||||
globalStyle(`${docRefLink} .affine-reference-title`, {
|
||||
border: 'none',
|
||||
});
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
import {
|
||||
Divider,
|
||||
PropertyCollapsibleContent,
|
||||
PropertyCollapsibleSection,
|
||||
PropertyName,
|
||||
} from '@affine/component';
|
||||
import { AffinePageReference } from '@affine/core/components/affine/reference-link';
|
||||
import { useI18n } from '@affine/i18n';
|
||||
import type { DatabaseBlockDataSource } from '@blocksuite/affine/blocks';
|
||||
import { DatabaseTableViewIcon } from '@blocksuite/icons/rc';
|
||||
import {
|
||||
DocService,
|
||||
LiveData,
|
||||
useLiveData,
|
||||
useService,
|
||||
} from '@toeverything/infra';
|
||||
import { Fragment, useMemo } from 'react';
|
||||
import type { Observable } from 'rxjs';
|
||||
|
||||
import { DocDatabaseBacklinksService } from '../../services/doc-database-backlinks';
|
||||
import type { DatabaseRow, DatabaseValueCell } from '../../types';
|
||||
import { DatabaseRendererTypes } from './constant';
|
||||
import * as styles from './doc-database-backlink-info.css';
|
||||
|
||||
type CellConfig =
|
||||
(typeof DatabaseRendererTypes)[keyof typeof DatabaseRendererTypes];
|
||||
|
||||
const DatabaseBacklinkCellName = ({
|
||||
cell,
|
||||
config,
|
||||
}: {
|
||||
cell: DatabaseValueCell;
|
||||
config: CellConfig;
|
||||
}) => {
|
||||
const propertyName = useLiveData(cell.property.name$);
|
||||
const t = useI18n();
|
||||
return (
|
||||
<PropertyName
|
||||
icon={<config.Icon />}
|
||||
name={propertyName ?? (config.name ? t.t(config.name) : t['unnamed']())}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const DatabaseBacklinkCell = ({
|
||||
cell,
|
||||
dataSource,
|
||||
rowId,
|
||||
}: {
|
||||
cell: DatabaseValueCell;
|
||||
dataSource: DatabaseBlockDataSource;
|
||||
rowId: string;
|
||||
}) => {
|
||||
const cellType = useLiveData(cell.property.type$);
|
||||
|
||||
const config = cellType ? DatabaseRendererTypes[cellType] : undefined;
|
||||
|
||||
// do not render title cell!
|
||||
if (!config || cellType === 'title') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<li
|
||||
key={cell.id}
|
||||
className={styles.cell}
|
||||
data-testid="database-backlink-cell"
|
||||
>
|
||||
<DatabaseBacklinkCellName cell={cell} config={config} />
|
||||
<config.Renderer cell={cell} dataSource={dataSource} rowId={rowId} />
|
||||
</li>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* A row in the database backlink info.
|
||||
* Note: it is being rendered in a list. The name might be confusing.
|
||||
*/
|
||||
const DatabaseBacklinkRow = ({
|
||||
defaultOpen = false,
|
||||
row$,
|
||||
}: {
|
||||
defaultOpen: boolean;
|
||||
row$: Observable<DatabaseRow | undefined>;
|
||||
}) => {
|
||||
const row = useLiveData(
|
||||
useMemo(() => LiveData.from(row$, undefined), [row$])
|
||||
);
|
||||
const sortedCells = useMemo(() => {
|
||||
return row?.cells.toSorted((a, b) => {
|
||||
return (a.property.name$.value ?? '').localeCompare(
|
||||
b.property.name$.value ?? ''
|
||||
);
|
||||
});
|
||||
}, [row?.cells]);
|
||||
const t = useI18n();
|
||||
|
||||
if (!row || !sortedCells) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<PropertyCollapsibleSection
|
||||
title={row.databaseName + ' ' + t['properties']()}
|
||||
defaultCollapsed={!defaultOpen}
|
||||
icon={<DatabaseTableViewIcon />}
|
||||
suffix={
|
||||
<AffinePageReference className={styles.docRefLink} pageId={row.docId} />
|
||||
}
|
||||
>
|
||||
<PropertyCollapsibleContent
|
||||
className={styles.cellList}
|
||||
collapsible={false}
|
||||
>
|
||||
{sortedCells.map(cell => {
|
||||
return (
|
||||
<DatabaseBacklinkCell
|
||||
key={cell.id}
|
||||
cell={cell}
|
||||
dataSource={row.dataSource}
|
||||
rowId={row.id}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</PropertyCollapsibleContent>
|
||||
</PropertyCollapsibleSection>
|
||||
);
|
||||
};
|
||||
|
||||
export const DocDatabaseBacklinkInfo = ({
|
||||
defaultOpen = [],
|
||||
}: {
|
||||
defaultOpen?: {
|
||||
docId: string;
|
||||
blockId: string;
|
||||
}[];
|
||||
}) => {
|
||||
const doc = useService(DocService).doc;
|
||||
const docDatabaseBacklinks = useService(DocDatabaseBacklinksService);
|
||||
const rows = useLiveData(
|
||||
useMemo(
|
||||
() =>
|
||||
LiveData.from(docDatabaseBacklinks.watchDbBacklinkRows$(doc.id), []),
|
||||
[docDatabaseBacklinks, doc.id]
|
||||
)
|
||||
);
|
||||
|
||||
if (!rows.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.root}>
|
||||
{rows.map(({ docId, rowId, row$ }) => (
|
||||
<Fragment key={`${docId}-${rowId}`}>
|
||||
<DatabaseBacklinkRow
|
||||
defaultOpen={defaultOpen?.some(
|
||||
backlink => backlink.docId === docId && backlink.blockId === rowId
|
||||
)}
|
||||
row$={row$}
|
||||
/>
|
||||
<Divider size="thinner" className={styles.divider} />
|
||||
</Fragment>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -8,7 +8,8 @@ import {
|
||||
WorkspaceEngineBeforeStart,
|
||||
} from '@toeverything/infra';
|
||||
import { isEmpty, omit } from 'lodash-es';
|
||||
import { type Observable, switchMap } from 'rxjs';
|
||||
import { map, type Observable, switchMap } from 'rxjs';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { DocsIndexer } from '../entities/docs-indexer';
|
||||
|
||||
@@ -509,6 +510,76 @@ export class DocsSearchService extends Service {
|
||||
);
|
||||
}
|
||||
|
||||
watchDatabasesTo(docId: string) {
|
||||
const DatabaseAdditionalSchema = z.object({
|
||||
databaseName: z.string().optional(),
|
||||
});
|
||||
return this.indexer.blockIndex
|
||||
.search$(
|
||||
{
|
||||
type: 'boolean',
|
||||
occur: 'must',
|
||||
queries: [
|
||||
{
|
||||
type: 'match',
|
||||
field: 'refDocId',
|
||||
match: docId,
|
||||
},
|
||||
{
|
||||
type: 'match',
|
||||
field: 'parentFlavour',
|
||||
match: 'affine:database',
|
||||
},
|
||||
// Ignore if it is a link to the current document.
|
||||
{
|
||||
type: 'boolean',
|
||||
occur: 'must_not',
|
||||
queries: [
|
||||
{
|
||||
type: 'match',
|
||||
field: 'docId',
|
||||
match: docId,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
fields: ['docId', 'blockId', 'parentBlockId', 'additional'],
|
||||
pagination: {
|
||||
limit: 100,
|
||||
},
|
||||
}
|
||||
)
|
||||
.pipe(
|
||||
map(({ nodes }) => {
|
||||
return nodes.map(node => {
|
||||
const additional =
|
||||
typeof node.fields.additional === 'string'
|
||||
? node.fields.additional
|
||||
: node.fields.additional[0];
|
||||
|
||||
return {
|
||||
docId:
|
||||
typeof node.fields.docId === 'string'
|
||||
? node.fields.docId
|
||||
: node.fields.docId[0],
|
||||
rowId:
|
||||
typeof node.fields.blockId === 'string'
|
||||
? node.fields.blockId
|
||||
: node.fields.blockId[0],
|
||||
databaseBlockId:
|
||||
typeof node.fields.parentBlockId === 'string'
|
||||
? node.fields.parentBlockId
|
||||
: node.fields.parentBlockId[0],
|
||||
databaseName: DatabaseAdditionalSchema.safeParse(additional).data
|
||||
?.databaseName as string | undefined,
|
||||
};
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
async getDocTitle(docId: string) {
|
||||
const doc = await this.indexer.docIndex.get(docId);
|
||||
const title = doc?.get('title');
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { DocsService } from '@toeverything/infra';
|
||||
import { Entity, LiveData } from '@toeverything/infra';
|
||||
|
||||
import type { TagStore } from '../stores/tag';
|
||||
import { tagColorMap } from './utils';
|
||||
import { tagToPaletteLine } from './utils';
|
||||
|
||||
export class Tag extends Entity<{ id: string }> {
|
||||
id = this.props.id;
|
||||
@@ -20,7 +20,7 @@ export class Tag extends Entity<{ id: string }> {
|
||||
|
||||
value$ = this.tagOption$.map(tag => tag?.value || '');
|
||||
|
||||
color$ = this.tagOption$.map(tag => tagColorMap(tag?.color ?? '') || '');
|
||||
color$ = this.tagOption$.map(tag => tagToPaletteLine(tag?.color ?? '') || '');
|
||||
|
||||
createDate$ = this.tagOption$.map(tag => tag?.createDate || Date.now());
|
||||
|
||||
|
||||
@@ -1,16 +1,25 @@
|
||||
// hack: map var(--affine-tag-xxx) colors to var(--affine-palette-line-xxx)
|
||||
export const tagColorMap = (color: string) => {
|
||||
const mapping: Record<string, string> = {
|
||||
'var(--affine-tag-red)': 'var(--affine-palette-line-red)',
|
||||
'var(--affine-tag-teal)': 'var(--affine-palette-line-green)',
|
||||
'var(--affine-tag-blue)': 'var(--affine-palette-line-blue)',
|
||||
'var(--affine-tag-yellow)': 'var(--affine-palette-line-yellow)',
|
||||
'var(--affine-tag-pink)': 'var(--affine-palette-line-magenta)',
|
||||
'var(--affine-tag-white)': 'var(--affine-palette-line-grey)',
|
||||
'var(--affine-tag-gray)': 'var(--affine-palette-line-grey)',
|
||||
'var(--affine-tag-orange)': 'var(--affine-palette-line-orange)',
|
||||
'var(--affine-tag-purple)': 'var(--affine-palette-line-purple)',
|
||||
'var(--affine-tag-green)': 'var(--affine-palette-line-green)',
|
||||
};
|
||||
return mapping[color] || color;
|
||||
const tagToPaletteLineMap: Record<string, string> = {
|
||||
'var(--affine-tag-red)': 'var(--affine-palette-line-red)',
|
||||
'var(--affine-tag-teal)': 'var(--affine-palette-line-green)',
|
||||
'var(--affine-tag-blue)': 'var(--affine-palette-line-blue)',
|
||||
'var(--affine-tag-yellow)': 'var(--affine-palette-line-yellow)',
|
||||
'var(--affine-tag-pink)': 'var(--affine-palette-line-magenta)',
|
||||
'var(--affine-tag-white)': 'var(--affine-palette-line-grey)',
|
||||
'var(--affine-tag-gray)': 'var(--affine-palette-line-grey)',
|
||||
'var(--affine-tag-orange)': 'var(--affine-palette-line-orange)',
|
||||
'var(--affine-tag-purple)': 'var(--affine-palette-line-purple)',
|
||||
'var(--affine-tag-green)': 'var(--affine-palette-line-green)',
|
||||
};
|
||||
|
||||
const paletteLineToTagMap: Record<string, string> = Object.fromEntries(
|
||||
Object.entries(tagToPaletteLineMap).map(([key, value]) => [value, key])
|
||||
);
|
||||
|
||||
// hack: map var(--affine-tag-xxx) colors to var(--affine-palette-line-xxx)
|
||||
export const tagToPaletteLine = (color: string) => {
|
||||
return tagToPaletteLineMap[color] || color;
|
||||
};
|
||||
|
||||
export const paletteLineToTag = (color: string) => {
|
||||
return paletteLineToTagMap[color] || color;
|
||||
};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
export { Tag } from './entities/tag';
|
||||
export { tagColorMap } from './entities/utils';
|
||||
export { paletteLineToTag, tagToPaletteLine } from './entities/utils';
|
||||
export { TagService } from './service/tag';
|
||||
export { DeleteTagConfirmModal } from './view/delete-tag-modal';
|
||||
export { useDeleteTagConfirmModal } from './view/delete-tag-modal';
|
||||
|
||||
import {
|
||||
DocsService,
|
||||
|
||||
@@ -1,64 +1,77 @@
|
||||
import { ConfirmModal, toast } from '@affine/component';
|
||||
import { toast, useConfirmModal } from '@affine/component';
|
||||
import { Trans, useI18n } from '@affine/i18n';
|
||||
import { useLiveData, useService } from '@toeverything/infra';
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { useCallback } from 'react';
|
||||
|
||||
import { TagService } from '../service/tag';
|
||||
|
||||
export const DeleteTagConfirmModal = ({
|
||||
open,
|
||||
onOpenChange,
|
||||
selectedTagIds,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
selectedTagIds: string[];
|
||||
}) => {
|
||||
/**
|
||||
* Show a confirm modal AND delete the tags
|
||||
*/
|
||||
export const useDeleteTagConfirmModal = () => {
|
||||
const { openConfirmModal } = useConfirmModal();
|
||||
|
||||
const t = useI18n();
|
||||
const tagService = useService(TagService);
|
||||
const tags = useLiveData(tagService.tagList.tags$);
|
||||
const selectedTags = useMemo(() => {
|
||||
return tags.filter(tag => selectedTagIds.includes(tag.id));
|
||||
}, [selectedTagIds, tags]);
|
||||
const tagName = useLiveData(selectedTags[0]?.value$ || '');
|
||||
|
||||
const handleDelete = useCallback(() => {
|
||||
selectedTagIds.forEach(tagId => {
|
||||
tagService.tagList.deleteTag(tagId);
|
||||
});
|
||||
const confirm = useCallback(
|
||||
(tagIdsToDelete: string[]) => {
|
||||
let closed = false;
|
||||
const { resolve, promise } = Promise.withResolvers<boolean>();
|
||||
const tagsToDelete = tags.filter(tag => tagIdsToDelete.includes(tag.id));
|
||||
const tagName = tagsToDelete[0]?.value$.value;
|
||||
const handleClose = (state: boolean) => {
|
||||
if (!closed) {
|
||||
closed = true;
|
||||
resolve(state);
|
||||
|
||||
toast(
|
||||
selectedTagIds.length > 1
|
||||
? t['com.affine.delete-tags.count']({ count: selectedTagIds.length })
|
||||
: t['com.affine.tags.delete-tags.toast']()
|
||||
);
|
||||
|
||||
onOpenChange(false);
|
||||
}, [onOpenChange, selectedTagIds, t, tagService]);
|
||||
|
||||
return (
|
||||
<ConfirmModal
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
title={t['com.affine.delete-tags.confirm.title']()}
|
||||
description={
|
||||
selectedTags.length === 1 ? (
|
||||
<Trans
|
||||
i18nKey={'com.affine.delete-tags.confirm.description'}
|
||||
values={{ tag: tagName }}
|
||||
components={{ 1: <strong /> }}
|
||||
/>
|
||||
) : (
|
||||
t['com.affine.delete-tags.confirm.multi-tag-description']({
|
||||
count: selectedTags.length.toString(),
|
||||
})
|
||||
)
|
||||
}
|
||||
confirmText={t['Delete']()}
|
||||
confirmButtonOptions={{
|
||||
variant: 'error',
|
||||
}}
|
||||
onConfirm={handleDelete}
|
||||
/>
|
||||
if (state) {
|
||||
tagIdsToDelete.forEach(tagId => {
|
||||
tagService.tagList.deleteTag(tagId);
|
||||
});
|
||||
toast(
|
||||
tagIdsToDelete.length > 1
|
||||
? t['com.affine.delete-tags.count']({
|
||||
count: tagIdsToDelete.length,
|
||||
})
|
||||
: t['com.affine.tags.delete-tags.toast']()
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
openConfirmModal({
|
||||
title: t['com.affine.delete-tags.confirm.title'](),
|
||||
description:
|
||||
tagIdsToDelete.length === 1 ? (
|
||||
<Trans
|
||||
i18nKey={'com.affine.delete-tags.confirm.description'}
|
||||
values={{ tag: tagName }}
|
||||
components={{ 1: <strong /> }}
|
||||
/>
|
||||
) : (
|
||||
t['com.affine.delete-tags.confirm.multi-tag-description']({
|
||||
count: tagIdsToDelete.length.toString(),
|
||||
})
|
||||
),
|
||||
confirmText: t['Delete'](),
|
||||
confirmButtonOptions: {
|
||||
variant: 'error',
|
||||
},
|
||||
onConfirm: () => {
|
||||
handleClose(true);
|
||||
},
|
||||
onCancel: () => {
|
||||
handleClose(true);
|
||||
},
|
||||
onOpenChange: state => {
|
||||
handleClose(state);
|
||||
},
|
||||
});
|
||||
return promise;
|
||||
},
|
||||
[openConfirmModal, t, tagService.tagList, tags]
|
||||
);
|
||||
|
||||
return confirm;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user