Skip to content

feat: support copy link to block render#360

Open
LucasXu0 wants to merge 3 commits into
mainfrom
feat/copy_link_to_block
Open

feat: support copy link to block render#360
LucasXu0 wants to merge 3 commits into
mainfrom
feat/copy_link_to_block

Conversation

@LucasXu0
Copy link
Copy Markdown
Contributor

@LucasXu0 LucasXu0 commented May 22, 2026

Description

closes AppFlowy-IO/AppFlowy#8748

Screenshot 2026-05-22 at 10 42 47 Screenshot 2026-05-22 at 10 43 05

Checklist

General

  • I've included relevant documentation or comments for the changes introduced.
  • I've tested the changes in multiple environments (e.g., different browsers, operating systems).

Testing

  • I've added or updated tests to validate the changes introduced for AppFlowy Web.

Feature-Specific

  • For feature additions, I've added a preview (video, screenshot, or demo) in the "Feature Preview" section.
  • I've verified that this feature integrates seamlessly with existing functionality.

Summary by Sourcery

Add support for interpreting pasted AppFlowy block links as page-reference mentions and improve hover controls behavior for table blocks.

New Features:

  • Recognize AppFlowy block URLs from clipboard data and insert corresponding page-reference mentions when pasted.

Enhancements:

  • Centralize parsing and detection of AppFlowy block links from various clipboard formats.
  • Adjust hover controls to correctly anchor and display on table root blocks instead of nested elements.

Tests:

  • Add unit tests covering AppFlowy block link parsing and clipboard URL extraction logic.
  • Add unit test scaffolding for hover controls behavior around table blocks.

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented May 22, 2026

Reviewer's Guide

Adds support for pasting AppFlowy "copy link to block" URLs as page mention references and refactors hover controls behavior for table blocks, along with new parsing utilities and tests.

Sequence diagram for pasting AppFlowy block link as page mention

sequenceDiagram
  actor User
  participant Browser
  participant withPasted
  participant getSingleURLTextFromClipboardData
  participant parseAppFlowyBlockLink
  participant handleURLPaste
  participant Transforms

  User->>Browser: paste (DataTransfer)
  Browser->>withPasted: onPaste(data)
  withPasted->>getSingleURLTextFromClipboardData: getSingleURLTextFromClipboardData(data)
  getSingleURLTextFromClipboardData-->>withPasted: clipboardURL
  withPasted->>parseAppFlowyBlockLink: parseAppFlowyBlockLink(clipboardURL)
  parseAppFlowyBlockLink-->>withPasted: AppFlowyBlockLink | null
  withPasted->>handleURLPaste: handleURLPaste(editor, clipboardURL)
  handleURLPaste->>parseAppFlowyBlockLink: parseAppFlowyBlockLink(url)
  parseAppFlowyBlockLink-->>handleURLPaste: AppFlowyBlockLink
  handleURLPaste->>Transforms: insertNodes(editor, mention)
  Transforms-->>handleURLPaste: success
  handleURLPaste-->>withPasted: true
Loading

File-Level Changes

Change Details Files
Support pasting AppFlowy block-link URLs as page/block mentions before normal HTML/text paste handling.
  • Capture a single HTTP URL from clipboard data across text/plain, text/uri-list, and text/html formats before other paste logic runs.
  • Detect AppFlowy block-link URLs via a dedicated parser rather than generic URL validation, extracting pageId and blockId from the route and query string.
  • On detecting a valid block link, insert an @ mention node with PageRef, wiring pageId and blockId into the mention payload and short-circuiting other paste handlers.
src/components/editor/plugins/withPasted.ts
src/components/editor/plugins/appflowy-block-link.ts
Introduce utilities for parsing AppFlowy block links and extracting a single URL from clipboard data, with accompanying tests.
  • Define an AppFlowyBlockLink type and a regex-based matcher for AppFlowy /app/{workspaceId}/{pageId}?blockId=... URLs that is host-agnostic.
  • Implement helpers to safely read clipboard data and derive a single HTTP(S) URL from plain text, URI list, or HTML clipboard formats.
  • Add Jest tests to validate parsing of desktop copy-link-to-block URLs, prioritization of URI-list over HTML, and rejection of page URLs lacking blockId.
src/components/editor/plugins/appflowy-block-link.ts
src/components/editor/plugins/__tests__/withPasted.test.ts
Refine hover controls behavior so table blocks are treated as a single hover root and avoid showing controls for nested blocks.
  • Add TABLE_ROOT_TYPES and helper to find the containing table root element for a block DOM node.
  • When resolving the block for hover controls, if the block is inside a table, re-resolve the Slate node and DOM element at the table root and use that as the hover target.
  • Introduce shouldShowHoverControlsForBlock to suppress hover controls for child blocks when a table root exists, replacing the previous parent-skipping logic and ensuring hover controls close safely on lookup errors.
src/components/editor/components/toolbar/block-controls/HoverControls.hooks.ts
src/components/editor/components/toolbar/block-controls/__tests__/HoverControls.hooks.test.ts

Assessment against linked issues

Issue Objective Addressed Explanation
AppFlowy-IO/AppFlowy#8748 Ensure the table block option/hover menu appears correctly for table blocks (including when only one row remains) on web so that the table can be deleted.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 2 issues, and left some high level feedback:

  • In withPasted, parseAppFlowyBlockLink is invoked once before handleURLPaste and again inside handleURLPaste; consider changing handleURLPaste to accept an AppFlowyBlockLink (or returning early when a parsed link is passed) to avoid redundant parsing and branching.
  • shouldShowHoverControlsForBlock duplicates the logic in getTableHoverControlsRoot by calling blockElement.closest in a loop; reusing getTableHoverControlsRoot there would simplify the code and ensure the hover-control table detection behavior stays consistent in one place.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `withPasted`, `parseAppFlowyBlockLink` is invoked once before `handleURLPaste` and again inside `handleURLPaste`; consider changing `handleURLPaste` to accept an `AppFlowyBlockLink` (or returning early when a parsed link is passed) to avoid redundant parsing and branching.
- `shouldShowHoverControlsForBlock` duplicates the logic in `getTableHoverControlsRoot` by calling `blockElement.closest` in a loop; reusing `getTableHoverControlsRoot` there would simplify the code and ensure the hover-control table detection behavior stays consistent in one place.

## Individual Comments

### Comment 1
<location path="src/components/editor/plugins/appflowy-block-link.ts" line_range="7-8" />
<code_context>
+}
+
+const UUID_PATTERN = '[0-9a-fA-F-]{36}';
+const APPFLOWY_BLOCK_LINK_PATTERN = new RegExp(
+  `^https?://[^/]+/app/(${UUID_PATTERN})/(${UUID_PATTERN})(?:[?#][^\\s]*)?$`
+);
+
</code_context>
<issue_to_address>
**issue (bug_risk):** The new block-link parser no longer enforces same-origin, which may be an unintended behavior change.

Previously, `handleURLPaste` called `isURL` with `host_whitelist: [window.location.hostname]`, so only same-origin URLs were treated as internal block links. The new `APPFLOWY_BLOCK_LINK_PATTERN` accepts any host (`[^/]+`) as long as the path matches `/app/{uuid}/{uuid}` with optional query/hash, so a URL from any domain that mimics this structure will now be handled as an internal block link. If we still intend to restrict this to the current origin, we should add an explicit host (and possibly protocol/port) check via the regex or a `URL` parse compared against `window.location.hostname`.
</issue_to_address>

### Comment 2
<location path="src/components/editor/plugins/appflowy-block-link.ts" line_range="1" />
<code_context>
+export interface AppFlowyBlockLink {
+  pageId: string;
+  blockId: string;
</code_context>
<issue_to_address>
**issue (complexity):** Consider refactoring the URL parsing and clipboard helpers to centralize HTTP URL validation and line handling, eliminating duplicate parsing logic and regex branching.

You can keep the same behavior with less branching and duplication by:

### 1. Simplifying `parseAppFlowyBlockLink`

You don’t need both a regex and `new URL`. You can derive `pageId` from the path and `blockId` from `searchParams` in a single pass, and avoid hard‑coding UUID shapes:

```ts
export function parseAppFlowyBlockLink(raw: string): AppFlowyBlockLink | null {
  const trimmed = raw.trim();
  let url: URL;
  try {
    url = new URL(trimmed);
  } catch {
    return null;
  }

  // Expect /app/{pageId}/{something}
  const segments = url.pathname.split('/').filter(Boolean);
  if (segments.length < 3 || segments[0] !== 'app') return null;

  const pageId = segments[1];
  const blockId = url.searchParams.get('blockId');
  if (!blockId) return null;

  return { pageId, blockId };
}
```

This removes `UUID_PATTERN`, `APPFLOWY_BLOCK_LINK_PATTERN`, and the double parse while keeping the same logical checks.

---

### 2. Centralizing URL parsing

Instead of `isHTTPURL` + multiple `new URL` calls, use a single helper:

```ts
function tryParseHttpUrl(value: string | undefined): URL | null {
  if (!value) return null;
  try {
    const url = new URL(value);
    return url.protocol === 'http:' || url.protocol === 'https:' ? url : null;
  } catch {
    return null;
  }
}
```

Then your call sites become simpler, e.g.:

```ts
function getSingleURLText(value: string | undefined): string | undefined {
  const trimmed = value?.trim();
  if (!trimmed) return undefined;

  const lines = trimmed.split(/\r\n|\r|\n/).filter(Boolean);
  if (lines.length !== 1) return undefined;

  return tryParseHttpUrl(lines[0]) ? lines[0] : undefined;
}
```

And:

```ts
function getSingleURLTextFromUriList(value: string | undefined): string | undefined {
  const lines = value
    ?.split(/\r\n|\r|\n/)
    .map((line) => line.trim())
    .filter((line) => line && !line.startsWith('#'));

  if (!lines || lines.length !== 1) return undefined;
  return tryParseHttpUrl(lines[0]) ? lines[0] : undefined;
}
```

---

### 3. Flattening the clipboard URL extraction pipeline

You can reuse a “single URL from lines” helper so the three sources differ only in how they supply candidate lines:

```ts
function pickSingleHttpUrl(lines: string[] | undefined): string | undefined {
  if (!lines) return undefined;
  const normalized = lines.map((l) => l.trim()).filter(Boolean);
  if (normalized.length !== 1) return undefined;
  return tryParseHttpUrl(normalized[0]) ? normalized[0] : undefined;
}
```

Then:

```ts
function getSingleURLText(value: string | undefined): string | undefined {
  return pickSingleHttpUrl(value?.split(/\r\n|\r|\n/));
}

function getSingleURLTextFromUriList(value: string | undefined): string | undefined {
  const lines = value
    ?.split(/\r\n|\r|\n/)
    .filter((line) => !line.trim().startsWith('#'));
  return pickSingleHttpUrl(lines);
}
```

For HTML, avoid re‑entering `getSingleURLText` and instead feed `pickSingleHttpUrl` directly:

```ts
function getSingleURLTextFromHTML(html: string | undefined): string | undefined {
  const trimmed = html?.trim();
  if (!trimmed || typeof DOMParser === 'undefined') return undefined;

  try {
    const doc = new DOMParser().parseFromString(trimmed, 'text/html');

    const href = doc.querySelector('a[href]')?.getAttribute('href')?.trim();
    if (href && tryParseHttpUrl(href)) return href;

    const bodyText = doc.body.textContent ?? '';
    return pickSingleHttpUrl(bodyText.split(/\r\n|\r|\n/));
  } catch {
    return undefined;
  }
}
```

This keeps the same behavior (HTML → URL from text or `<a>`), but with a single line-processing + URL-validation core, and no nested reuse of helpers with different semantics.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread src/components/editor/plugins/appflowy-block-link.ts Outdated
Comment thread src/components/editor/plugins/appflowy-block-link.ts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] the option menu doesn't appear when hovering over the table on the web

1 participant