Skip to content

Fix Web2 link meta fetch interrupting user input and automatically bumping the cursor to the next input field#516

Open
HexaField wants to merge 1 commit intodevfrom
fix/web2-link-validate-is-awkward
Open

Fix Web2 link meta fetch interrupting user input and automatically bumping the cursor to the next input field#516
HexaField wants to merge 1 commit intodevfrom
fix/web2-link-validate-is-awkward

Conversation

@HexaField
Copy link

@HexaField HexaField commented Aug 29, 2025

Summary by CodeRabbit

  • New Features

    • Automatic URL normalization (adds https:// when missing) in add and card views.
    • Debounced metadata fetching for smoother input.
    • Input field switched to text for easier editing.
  • Bug Fixes

    • Safer external links using rel="noopener noreferrer" and normalized URLs.
    • Validates and fetches metadata only for host-like, valid URLs; prevents empty/invalid requests.
    • More reliable hostname display and link opening via normalized, parsed URLs.

@netlify
Copy link

netlify bot commented Aug 29, 2025

Deploy Preview for fluxdocs ready!

Name Link
🔨 Latest commit ca1fea6
🔍 Latest deploy log https://app.netlify.com/projects/fluxdocs/deploys/68b1960e9ee9ee00085b0144
😎 Deploy Preview https://deploy-preview-516--fluxdocs.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@netlify
Copy link

netlify bot commented Aug 29, 2025

Deploy Preview for fluxsocial-dev ready!

Name Link
🔨 Latest commit ca1fea6
🔍 Latest deploy log https://app.netlify.com/projects/fluxsocial-dev/deploys/68b1960eb50cef00088a80cc
😎 Deploy Preview https://deploy-preview-516--fluxsocial-dev.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai
Copy link

coderabbitai bot commented Aug 29, 2025

Walkthrough

Two profile view components were updated: WebLinkAdd.vue now normalizes and validates URLs, debounces and gates metadata fetches, and sends normalized URLs; WebLinkCard.vue now normalizes URLs for display, updates hostname derivation, and adds rel attributes for the anchor.

Changes

Cohort / File(s) Summary
Web link input normalization & metadata fetch
app/src/views/main/profile/WebLinkAdd.vue
Switched input to text; added normalizeUrl and looksLikeHost; validated via URL constructor; introduced 500ms debounce for metadata fetch; gated fetch to host-like inputs; updated getMeta signature to accept urlForMeta and use jsonlink.io with encodeURIComponent; removed post-fetch title focus; createLink now sends normalized URL.
Web link display normalization & anchor hardening
app/src/views/main/profile/WebLinkCard.vue
Added normalizeUrl and computed safeUrl; anchor now uses safeUrl with rel="noopener noreferrer"; hostname derived from safeUrl; returns empty values on invalid/empty input; no public API changes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor U as User
  participant WA as WebLinkAdd.vue
  participant N as normalizeUrl()
  participant H as looksLikeHost()
  participant D as metaDebounce(500ms)
  participant J as jsonlink.io

  U->>WA: Type in link field
  WA->>N: Normalize input
  N-->>WA: normalizedUrl
  WA->>H: Check host-likeness
  alt Host-like and valid URL
    WA->>D: Schedule getMeta(normalizedUrl)
    D-->>WA: Debounced trigger
    WA->>J: Fetch metadata (encodeURIComponent(url))
    J-->>WA: Metadata JSON
    WA->>WA: Update title/description/image
  else Not host-like or invalid
    WA->>WA: Skip metadata fetch
  end
  U->>WA: Submit create link
  WA->>N: Normalize final value
  WA-->>WA: Send normalized url in payload
Loading
sequenceDiagram
  autonumber
  participant WC as WebLinkCard.vue
  participant N as normalizeUrl()
  note over WC: On render/prop update
  WC->>N: Normalize props.url
  N-->>WC: safeUrl
  alt safeUrl valid
    WC-->>WC: Derive hostname from safeUrl
    WC-->>User: Anchor href=safeUrl rel="noopener noreferrer"
  else invalid/empty
    WC-->>WC: Empty href/hostname
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

I nibble links with cautious cheer,
Trim the stems, make pathways clear.
A hop, a pause—debounce the breeze,
Fetching meta through the trees.
Now safe and neat, my URLs gleam—
A rabbit’s tidy, well-linked dream. 🥕✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/web2-link-validate-is-awkward

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbit in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbit in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbit gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbit read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbit help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbit ignore or @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbit summary or @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbit or @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
app/src/views/main/profile/WebLinkCard.vue (1)

9-15: Guard empty href and harden rel

Avoid empty-string hrefs and add nofollow/ugc for user-supplied links.

-      <a :href="safeUrl" target="_blank" rel="noopener noreferrer" class="link-card__info">
+      <a :href="safeUrl || undefined" target="_blank" rel="noopener noreferrer nofollow ugc" class="link-card__info">
🧹 Nitpick comments (3)
app/src/views/main/profile/WebLinkCard.vue (2)

49-49: Deduplicate URL normalization across components

normalizeUrl is duplicated here and in WebLinkAdd.vue. Extract to a shared util to prevent drift and enable testing.

Example new file:

// app/src/utils/url.ts
export function normalizeWebUrl(input: string): string {
  const value = (input || "").trim();
  if (!value) return "";
  const hasScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(value);
  const withScheme = hasScheme ? value : `https://${value}`;
  try {
    const u = new URL(withScheme);
    return u.protocol === "http:" || u.protocol === "https:" ? withScheme : "";
  } catch {
    return "";
  }
}

Then import and use in both components.


52-55: Nit: consider including port in display

hostname omits port. If you want “example.com:8080” when present, use URL.host instead of hostname. If not desired, ignore.

app/src/views/main/profile/WebLinkAdd.vue (1)

85-94: Broaden looksLikeHost to cover IPv4/IPv6

Current check rejects valid IPv6 hosts. Include IPs while keeping the early-gate intent.

 function looksLikeHost(urlStr: string): boolean {
   try {
     const u = new URL(urlStr);
     const host = u.hostname;
-    // Require a dot or be localhost to reduce early validations like "https://exa"
-    return host === "localhost" || host.includes(".");
+    // Require a dotted name, localhost, or an IP (v4/v6)
+    const isIPv4 = /^\d{1,3}(?:\.\d{1,3}){3}$/.test(host);
+    const isIPv6 = /^[a-fA-F0-9:]+$/.test(host) && host.includes(":");
+    return host === "localhost" || host.includes(".") || isIPv4 || isIPv6;
   } catch {
     return false;
   }
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between b61b8a4 and ca1fea6.

📒 Files selected for processing (2)
  • app/src/views/main/profile/WebLinkAdd.vue (3 hunks)
  • app/src/views/main/profile/WebLinkCard.vue (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Redirect rules - fluxsocial-dev
  • GitHub Check: Redirect rules - fluxdocs
  • GitHub Check: Header rules - fluxsocial-dev
  • GitHub Check: Header rules - fluxdocs
  • GitHub Check: Pages changed - fluxdocs
  • GitHub Check: Pages changed - fluxsocial-dev
🔇 Additional comments (2)
app/src/views/main/profile/WebLinkAdd.vue (2)

12-14: Switch to text input—LGTM

Prevents native URL validation/focus jumps that were interrupting entry.


148-149: Send normalized URL on create—LGTM

This aligns creation with the new normalization flow.

Comment on lines +75 to +76
let metaDebounce: ReturnType<typeof setTimeout> | null = null;

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Clear debounce on unmount and track requests to avoid leaks/races

Ensure pending timers don’t fire after unmount and prep a request id for stale-response protection.

-let metaDebounce: ReturnType<typeof setTimeout> | null = null;
+let metaDebounce: ReturnType<typeof setTimeout> | null = null;
+let metaReqId = 0;

Add (outside this block) to imports and lifecycle:

// add to imports
import { ref, onBeforeUnmount } from "vue";

// add after declarations
onBeforeUnmount(() => {
  if (metaDebounce) clearTimeout(metaDebounce);
});
🤖 Prompt for AI Agents
In app/src/views/main/profile/WebLinkAdd.vue around lines 75 to 76, the debounce
timer assigned to metaDebounce can fire after the component unmounts and there’s
no request-id tracking to ignore stale async responses; import ref and
onBeforeUnmount from "vue", add an onBeforeUnmount handler that clears
metaDebounce if set, and add a simple incrementing request id (e.g., a numeric
ref or local variable updated when issuing the request) that you pass into the
async metadata fetch and check on response to ignore stale results so timers and
responses cannot cause leaks or racey state updates after unmount.

Comment on lines +77 to +84
function normalizeUrl(input: string): string {
const value = (input || "").trim();
if (!value) return value;
// If already has a scheme, keep as is
const hasScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(value);
return hasScheme ? value : `https://${value}`;
}

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Allow-list http/https in normalizeUrl

Match WebLinkCard hardening; block non-web schemes early.

-function normalizeUrl(input: string): string {
-  const value = (input || "").trim();
-  if (!value) return value;
-  // If already has a scheme, keep as is
-  const hasScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(value);
-  return hasScheme ? value : `https://${value}`;
-}
+function normalizeUrl(input: string): string {
+  const value = (input || "").trim();
+  if (!value) return "";
+  const hasScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(value);
+  const withScheme = hasScheme ? value : `https://${value}`;
+  try {
+    const u = new URL(withScheme);
+    return u.protocol === "http:" || u.protocol === "https:" ? withScheme : "";
+  } catch {
+    return "";
+  }
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function normalizeUrl(input: string): string {
const value = (input || "").trim();
if (!value) return value;
// If already has a scheme, keep as is
const hasScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(value);
return hasScheme ? value : `https://${value}`;
}
function normalizeUrl(input: string): string {
const value = (input || "").trim();
if (!value) return "";
const hasScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(value);
const withScheme = hasScheme ? value : `https://${value}`;
try {
const u = new URL(withScheme);
return u.protocol === "http:" || u.protocol === "https:" ? withScheme : "";
} catch {
return "";
}
}
🤖 Prompt for AI Agents
In app/src/views/main/profile/WebLinkAdd.vue around lines 77 to 84, normalizeUrl
currently accepts any URI scheme; change it to allow-list only http and https:
detect a leading scheme, and if one exists but is not http or https return an
empty string (block non-web schemes early), otherwise if no scheme prepend
"https://" as before; ensure case-insensitive matching and keep the function
signature returning a string.

Comment on lines +96 to 105
async function getMeta(urlForMeta: string) {
try {
loadingMeta.value = true;
const data = await fetch("https://jsonlink.io/api/extract?url=" + link.value).then((res) => res.json());
const data = await fetch("https://jsonlink.io/api/extract?url=" + encodeURIComponent(urlForMeta)).then((res) =>
res.json()
);

title.value = data.title || "";
description.value = data.description || "";
imageUrl.value = data.images[0] || "";
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Prevent stale meta overwrites; make images access safe; only fetch on http(s)

Concurrent fetches can race and older responses can clobber newer input; also data.images may be undefined; and we should skip meta for non-http(s).

-async function getMeta(urlForMeta: string) {
+async function getMeta(urlForMeta: string, reqId: number) {
   try {
     loadingMeta.value = true;
-    const data = await fetch("https://jsonlink.io/api/extract?url=" + encodeURIComponent(urlForMeta)).then((res) =>
-      res.json()
-    );
+    const data = await fetch(
+      "https://jsonlink.io/api/extract?url=" + encodeURIComponent(urlForMeta)
+    ).then((res) => res.json());
+
+    // Drop if a newer request started after this one
+    if (reqId !== metaReqId) return;
 
     title.value = data.title || "";
     description.value = data.description || "";
-    imageUrl.value = data.images[0] || "";
+    imageUrl.value = (data.images?.[0] as string | undefined) || "";
   } finally {
     loadingMeta.value = false;
   }
 }
 
@@
-    // Validate
-    // new URL will throw if not valid
+    // Validate (throws if invalid)
     // We intentionally do not mutate the visible input to avoid caret jumps
     // Use a debounced meta fetch to avoid interrupting typing
-    new URL(normalized);
-    isValidLink.value = true;
+    const u = new URL(normalized);
+    // Only accept http(s)
+    if (u.protocol !== "http:" && u.protocol !== "https:") {
+      isValidLink.value = false;
+      if (metaDebounce) clearTimeout(metaDebounce);
+      return;
+    }
+    isValidLink.value = true;
     if (metaDebounce) clearTimeout(metaDebounce);
-    metaDebounce = setTimeout(() => {
-      getMeta(normalized);
+    metaReqId += 1;
+    const reqId = metaReqId;
+    metaDebounce = setTimeout(() => {
+      getMeta(normalized, reqId);
     }, 500);

Also applies to: 123-133

🤖 Prompt for AI Agents
In app/src/views/main/profile/WebLinkAdd.vue around lines 96-105 (and similarly
at 123-133), the meta fetch needs three fixes: first, only run the fetch when
the URL uses http or https (skip otherwise); second, prevent stale response
overwrites by capturing a local token (requestId or the current url value)
before awaiting and only apply results if the token still matches the latest
input; third, guard access to images (check data.images && data.images.length >
0) before reading images[0] and fall back to an empty string. Also ensure
loadingMeta is properly cleared (in a finally block) so UI state is consistent.

Comment on lines +42 to +47
function normalizeUrl(input: string): string {
const value = (input || "").trim();
if (!value) return "";
const hasScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(value);
return hasScheme ? value : `https://${value}`;
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Allow-list http/https to block javascript: and other unsafe schemes

Current normalizeUrl passes through any scheme, enabling clickable javascript: URLs. Restrict to http(s) and return empty for others.

-function normalizeUrl(input: string): string {
-  const value = (input || "").trim();
-  if (!value) return "";
-  const hasScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(value);
-  return hasScheme ? value : `https://${value}`;
-}
+function normalizeUrl(input: string): string {
+  const value = (input || "").trim();
+  if (!value) return "";
+  const hasScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(value);
+  const withScheme = hasScheme ? value : `https://${value}`;
+  try {
+    const u = new URL(withScheme);
+    return u.protocol === "http:" || u.protocol === "https:" ? withScheme : "";
+  } catch {
+    return "";
+  }
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function normalizeUrl(input: string): string {
const value = (input || "").trim();
if (!value) return "";
const hasScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(value);
return hasScheme ? value : `https://${value}`;
}
function normalizeUrl(input: string): string {
const value = (input || "").trim();
if (!value) return "";
const hasScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(value);
const withScheme = hasScheme ? value : `https://${value}`;
try {
const u = new URL(withScheme);
return u.protocol === "http:" || u.protocol === "https:" ? withScheme : "";
} catch {
return "";
}
}
🤖 Prompt for AI Agents
In app/src/views/main/profile/WebLinkCard.vue around lines 42 to 47,
normalizeUrl currently accepts any URL scheme (allowing unsafe schemes like
javascript:). Change it so that after trimming and early-return for empty, it
detects a scheme case-insensitively; if no scheme, prefix with "https://"; if a
scheme is present, only allow "http" or "https" (case-insensitive) and otherwise
return an empty string to block unsafe schemes. Ensure regex/check is updated
accordingly and tests/uses of normalizeUrl handle the empty-string case.

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.

1 participant