Files
AFFiNE/packages/common/reader/__tests__/reader.spec.ts
T
Raphael Fakhri d70977f0ef fix(core): index doc references inside table cells (#15713)
## Description

Closes #15468.

A doc linked with `@` inside a table block (`/table`, not a database
view) never appears in Bidirectional Links on either doc. The indexer's
`affine:table` branch in `@affine/reader` only collects cell text, so
the block document has no `refDocId`/`ref`, and the backlink query on
`refDocId` finds nothing. The `affine:database` branch already collects
inline references from rich-text cells.

This change reads the inline references from each `prop:cells.*.text`
value with the existing `getTextDeltasFromCellValue` and
`collectInlineReferences` helpers, and sets `refDocId` and `ref` on the
table block, the same way the database branch does.

Scope: this fixes the TypeScript crawler, which the web app (IndexedDB
storage) uses and which the desktop and mobile apps use as the fallback.
The native crawler in `affine_doc_loader` (`read/block.rs`,
`affine:table` branch) has the same gap, and this PR leaves it
unchanged.

Test: `should index references from table cells` in
`packages/common/reader/__tests__/reader.spec.ts` fails without the fix
(`expected undefined to deeply equal [ 'target-doc' ]`) and passes with
it.

## Checklist

- [x] I have signed the [AFFiNE Contributor License
Agreement](https://cla-assistant.io/toeverything/AFFiNE) — required
before merge; the `license/cla` check must be green ([how it
works](https://github.com/toeverything/AFFiNE/blob/canary/docs/BUILDING.md#sign-the-cla-first))
- [x] The PR targets the `canary` branch and its title follows
[Conventional Commits](https://www.conventionalcommits.org/)
- [x] Tests are added or updated where it makes sense
- [x] `yarn lint` and `yarn typecheck` pass locally
- [x] If the PR code includes AI-generated edits, I have carefully
reviewed it to ensure that the scope of the PR is consistent with what
is claimed in the title and description, and that there are no redundant
or invalid implementations.
- [x] I agree that maintainers may close the PR without discussion if
they consider the code quality to be too low.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

- **Bug Fixes**
- Table cell text is now included when reading document blocks, and
references within cells are captured for indexing.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-23 23:02:27 +08:00

344 lines
8.5 KiB
TypeScript

import { readFileSync } from 'node:fs';
import path from 'node:path';
import { expect, test } from 'vitest';
import {
applyUpdate,
Array as YArray,
Doc as YDoc,
Map as YMap,
Text as YText,
} from 'yjs';
import {
parsePageDoc,
readAllBlocksFromDoc,
readAllDocIdsFromRootDoc,
readAllDocsFromRootDoc,
} from '../src';
const rootDocSnapshot = readFileSync(
path.join(import.meta.dirname, './__fixtures__/test-root-doc.snapshot.bin')
);
const docSnapshot = readFileSync(
path.join(import.meta.dirname, './__fixtures__/test-doc.snapshot.bin')
);
const docSnapshotWithAiEditable = readFileSync(
path.join(
import.meta.dirname,
'./__fixtures__/test-doc-with-ai-editable.snapshot.bin'
)
);
test.each(['missing-child', 'parent-cycle'])(
'reads remaining blocks once with a %s',
async mode => {
const doc = new YDoc();
const blocks = doc.getMap('blocks');
blocks.set(
'page',
new YMap<unknown>([
['sys:id', 'page'],
['sys:flavour', 'affine:page'],
['prop:title', new YText('Title')],
[
'sys:children',
YArray.from(
mode === 'missing-child' ? ['missing', 'image'] : ['image']
),
],
])
);
blocks.set(
'image',
new YMap<unknown>([
['sys:id', 'image'],
['sys:flavour', 'affine:image'],
['prop:sourceId', 'image-blob'],
['sys:children', YArray.from(mode === 'parent-cycle' ? ['page'] : [])],
])
);
const result = await readAllBlocksFromDoc({ ydoc: doc, spaceId: 'space' });
expect(result?.blocks.map(block => block.blockId)).toEqual([
'page',
'image',
]);
expect(result?.blocks[1].blob).toEqual(['image-blob']);
doc.destroy();
}
);
test('should read doc blocks work', async () => {
const rootDoc = new YDoc({
guid: 'test-root-doc',
});
applyUpdate(rootDoc, rootDocSnapshot);
const doc1 = new YDoc({
guid: 'test-doc',
});
applyUpdate(doc1, docSnapshot);
const result = await readAllBlocksFromDoc({
ydoc: doc1,
rootYDoc: rootDoc,
spaceId: 'test-space',
});
expect(result).toMatchSnapshot();
});
test('should read doc blocks work without root doc', async () => {
const doc = new YDoc({
guid: 'test-doc',
});
applyUpdate(doc, docSnapshot);
const result = await readAllBlocksFromDoc({
ydoc: doc,
spaceId: 'test-space',
});
expect(result).toMatchSnapshot();
});
test('should get all docs from root doc work', async () => {
const rootDoc = new YDoc({
guid: 'test-root-doc',
});
rootDoc.getMap('meta').set(
'pages',
YArray.from([
new YMap([
['id', 'test-doc-1'],
['title', 'Test Doc 1'],
]),
new YMap([
['id', 'test-doc-2'],
['title', 'Test Doc 2'],
]),
new YMap([
['id', 'test-doc-3'],
['title', 'Test Doc 3'],
['trash', true],
]),
new YMap([['id', 'test-doc-4']]),
])
);
const docs = readAllDocsFromRootDoc(rootDoc);
expect(Array.from(docs.entries())).toMatchSnapshot();
// include trash
const docsWithTrash = readAllDocsFromRootDoc(rootDoc, {
includeTrash: true,
});
expect(Array.from(docsWithTrash.entries())).toMatchSnapshot();
});
test('should read all docs from root doc snapshot work', async () => {
const rootDoc = new YDoc({
guid: 'test-root-doc',
});
applyUpdate(rootDoc, rootDocSnapshot);
const docsWithTrash = readAllDocsFromRootDoc(rootDoc, {
includeTrash: true,
});
expect(Array.from(docsWithTrash.entries())).toMatchSnapshot();
});
test('should read all doc ids from root doc snapshot work', async () => {
const rootDoc = new YDoc({
guid: 'test-root-doc',
});
applyUpdate(rootDoc, rootDocSnapshot);
const docIds = readAllDocIdsFromRootDoc(rootDoc);
expect(docIds).toMatchSnapshot();
});
test('should parse page doc work', () => {
const doc = new YDoc({
guid: 'test-doc',
});
applyUpdate(doc, docSnapshot);
const result = parsePageDoc({
workspaceId: 'test-space',
doc,
buildBlobUrl: id => `blob://${id}`,
buildDocUrl: id => `doc://${id}`,
renderDocTitle: id => `Doc Title ${id}`,
});
expect(result).toMatchSnapshot();
});
test('should parse page doc work with ai editable', () => {
const doc = new YDoc({
guid: 'test-doc',
});
applyUpdate(doc, docSnapshot);
const result = parsePageDoc({
workspaceId: 'test-space',
doc,
buildBlobUrl: id => `blob://${id}`,
buildDocUrl: id => `doc://${id}`,
renderDocTitle: id => `Doc Title ${id}`,
aiEditable: true,
});
expect(result.md).toMatchSnapshot();
});
test('should parse page full doc work with ai editable', () => {
const doc = new YDoc({
guid: 'test-doc',
});
applyUpdate(doc, docSnapshotWithAiEditable);
const result = parsePageDoc({
workspaceId: 'test-space',
doc,
buildBlobUrl: id => `blob://${id}`,
buildDocUrl: id => `doc://${id}`,
renderDocTitle: id => `Doc Title ${id}`,
aiEditable: true,
});
expect(result.md).toMatchSnapshot();
});
test('should index references from database rich-text cells', async () => {
const doc = new YDoc({
guid: 'db-doc',
});
const blocks = doc.getMap('blocks');
const pageTitle = new YText();
pageTitle.insert(0, 'Page');
const page = new YMap();
page.set('sys:id', 'page');
page.set('sys:flavour', 'affine:page');
page.set('sys:children', YArray.from(['note']));
page.set('prop:title', pageTitle);
blocks.set('page', page);
const note = new YMap();
note.set('sys:id', 'note');
note.set('sys:flavour', 'affine:note');
note.set('sys:children', YArray.from(['db']));
note.set('prop:displayMode', 'page');
blocks.set('note', note);
const dbTitle = new YText();
dbTitle.insert(0, 'Database');
const db = new YMap();
db.set('sys:id', 'db');
db.set('sys:flavour', 'affine:database');
db.set('sys:children', new YArray());
db.set('prop:title', dbTitle);
const columns = new YArray();
const column = new YMap();
column.set('id', 'col1');
column.set('name', 'Text');
column.set('type', 'rich-text');
column.set('data', new YMap());
columns.push([column]);
db.set('prop:columns', columns);
const cellText = new YText();
cellText.applyDelta([
{ insert: 'See ' },
{
insert: 'Target',
attributes: {
reference: {
pageId: 'target-doc',
params: { mode: 'page' },
},
},
},
]);
const cell = new YMap();
cell.set('columnId', 'col1');
cell.set('value', cellText);
const row = new YMap();
row.set('col1', cell);
const cells = new YMap();
cells.set('row1', row);
db.set('prop:cells', cells);
blocks.set('db', db);
const result = await readAllBlocksFromDoc({
ydoc: doc,
spaceId: 'test-space',
});
const dbBlock = result?.blocks.find(block => block.blockId === 'db');
expect(dbBlock?.refDocId).toEqual(['target-doc']);
expect(dbBlock?.ref).toEqual([
JSON.stringify({ docId: 'target-doc', mode: 'page' }),
]);
});
test('should index references from table cells', async () => {
const doc = new YDoc({
guid: 'table-doc',
});
const blocks = doc.getMap('blocks');
const pageTitle = new YText();
pageTitle.insert(0, 'Page');
const page = new YMap();
page.set('sys:id', 'page');
page.set('sys:flavour', 'affine:page');
page.set('sys:children', YArray.from(['note']));
page.set('prop:title', pageTitle);
blocks.set('page', page);
const note = new YMap();
note.set('sys:id', 'note');
note.set('sys:flavour', 'affine:note');
note.set('sys:children', YArray.from(['table']));
note.set('prop:displayMode', 'page');
blocks.set('note', note);
const table = new YMap();
table.set('sys:id', 'table');
table.set('sys:flavour', 'affine:table');
table.set('sys:children', new YArray());
const plainText = new YText();
plainText.insert(0, 'Plain');
table.set('prop:cells.row1:col1.text', plainText);
const refText = new YText();
refText.applyDelta([
{ insert: 'See ' },
{
insert: 'Target',
attributes: {
reference: {
pageId: 'target-doc',
params: { mode: 'page' },
},
},
},
]);
table.set('prop:cells.row1:col2.text', refText);
blocks.set('table', table);
const result = await readAllBlocksFromDoc({
ydoc: doc,
spaceId: 'test-space',
});
const tableBlock = result?.blocks.find(block => block.blockId === 'table');
expect(tableBlock?.content).toEqual(['Plain', 'See Target']);
expect(tableBlock?.refDocId).toEqual(['target-doc']);
expect(tableBlock?.ref).toEqual([
JSON.stringify({ docId: 'target-doc', mode: 'page' }),
]);
});