8000 Nc feat/canvas formula url by AmitJoki · Pull Request #10541 · nocodb/nocodb · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Nc feat/canvas formula url #10541

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Feb 19, 2025
Merged

Nc feat/canvas formula url #10541

merged 7 commits into from
Feb 19, 2025

Conversation

AmitJoki
Copy link
Contributor

Change Summary

Handle formula URLs in Canvas

Change type

  • feat: (new feature for the user, not a new feature for build script)
  • fix: (bug fix for the user, not a fix to a build script)
  • docs: (changes to the documentation)
  • style: (formatting, missing semi colons, etc; no production code change)
  • refactor: (refactoring production code, eg. renaming a variable)
  • test: (adding missing tests, refactoring tests; no production code change)
  • chore: (updating grunt tasks etc; no production code change)

Test/ Verification

Provide summary of changes.

Additional information / screenshots (optional)

Anything for maintainers to be made aware of

Copy link
Contributor
coderabbitai bot commented Feb 19, 2025
📝 Walkthrough

Walkthrough

This update enhances URL handling in the formula cell rendering functionality. The FormulaCellRenderer methods (render and handleClick) now accept additional properties and have been modified to detect and process URLs. When URLs are found, they are rendered using a new utility function. Additionally, two new helper functions have been introduced: one for rendering multi-line URLs and another for parsing HTML anchor elements to extract URL details.

Changes

File(s) Change Summary
.../cells/Formula.ts Updated FormulaCellRenderer methods (render and handleClick) to accept extra properties and process URL-containing results, including styling adjustments and URL interactivity.
.../canvas/utils/canvas.ts Added new function renderFormulaURL to render multiple lines of text with associated URLs on a canvas, handling text wrapping and underlining.
.../utils/urlUtils.ts Added caching to replaceUrlsWithLink and introduced getFormulaTextSegments to parse an HTML anchor string and extract its text and URL details.

Suggested labels

🔦 Type: Feature, size:L, lgtm

Suggested reviewers

  • amandesai01
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai 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:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @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

Documentation and Community

  • 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
Contributor
@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: 2

🧹 Nitpick comments (2)
packages/nc-gui/components/smartsheet/grid/canvas/cells/Formula.ts (1)

67-85: Consider accessibility improvements for URL rendering.

While the URL rendering is visually enhanced, it lacks accessibility considerations for screen readers.

Consider adding ARIA attributes and keyboard navigation support. You can achieve this by maintaining a separate DOM element for accessibility:

+const createAccessibleLink = (label: string, url: string) => {
+  const link = document.createElement('a')
+  link.href = url
+  link.textContent = label
+  link.setAttribute('aria-label', `${label} - Link`)
+  link.setAttribute('role', 'link')
+  return link
+}

 if (typeof urls === 'string') {
   const { label, suffixText, prefixText } = getFormulaLabelAndUrl(urls)
+  // Create accessible link in the DOM
+  const accessibleLink = createAccessibleLink(label, url)
   ctx.font = `${pv ? 600 : 500} 13px Manrope`
   ctx.fillStyle = pv ? '#3366FF' : textColor
packages/nc-gui/components/smartsheet/grid/canvas/utils/canvas.ts (1)

1160-1232: Optimize performance with text measurement caching.

The function performs repeated text measurements which can be expensive. Consider caching these measurements to improve performance.

Apply this diff to add text measurement caching:

+const measurementCache = new LRUCache<string, number>({
+  max: 1000,
+})

+function getCachedTextWidth(
+  ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+  text: string,
+): number {
+  const cacheKey = `${text}-${ctx.font}`
+  let width = measurementCache.get(cacheKey)
+  if (width === undefined) {
+    width = ctx.measureText(text).width
+    measurementCache.set(cacheKey, width)
+  }
+  return width
+}

 const renderText = (text: string, isUrl: boolean): void => {
   const words = text.split(' ')
   let wordCount = 0
   for (const word of words) {
     wordCount++
     const separator = wordCount === words.length ? '' : ' '
-    const wordWidth = ctx.measureText(word + separator).width
+    const wordWidth = getCachedTextWidth(ctx, word + separator)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aa67b38 and 0d1da96.

📒 Files selected for processing (3)
  • packages/nc-gui/components/smartsheet/grid/canvas/cells/Formula.ts (4 hunks)
  • packages/nc-gui/components/smartsheet/grid/canvas/utils/canvas.ts (1 hunks)
  • packages/nc-gui/utils/urlUtils.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: release-docker / buildx
  • GitHub Check: pre-build-for-playwright / playwright
  • GitHub Check: unit-tests
  • GitHub Check: unit-tests-pg

Comment on lines 36 to 74
export function getFormulaLabelAndUrl(anchorLinkHTML: string) {
const parser = new DOMParser()
const dom = parser.parseFromString(anchorLinkHTML, 'text/html')
const anchor = dom.querySelector('a')
return {
label: anchor?.textContent ?? '',
url: anchor?.href ?? '',
suffixText: anchor?.nextSibling?.nodeValue ?? '',
prefixText: anchor?.previousSibling?.nodeValue ?? '',
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for malformed HTML and missing elements.

The function assumes well-formed HTML and presence of anchor elements. Consider adding error handling to make it more robust.

Apply this diff to improve error handling:

 export function getFormulaLabelAndUrl(anchorLinkHTML: string) {
+  if (!anchorLinkHTML) {
+    return {
+      label: '',
+      url: '',
+      suffixText: '',
+      prefixText: '',
+    }
+  }
+
   const parser = new DOMParser()
   const dom = parser.parseFromString(anchorLinkHTML, 'text/html')
   const anchor = dom.querySelector('a')
+
+  if (!anchor) {
+    console.warn('No anchor element found in the provided HTML')
+    return {
+      label: '',
+      url: '',
+      suffixText: '',
+      prefixText: '',
+    }
+  }
+
   return {
     label: anchor?.textContent ?? '',
     url: anchor?.href ?? '',
     suffixText: anchor?.nextSibling?.nodeValue ?? '',
     prefixText: anchor?.previousSibling?.nodeValue ?? '',
   }
 }
📝 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
export function getFormulaLabelAndUrl(anchorLinkHTML: string) {
const parser = new DOMParser()
const dom = parser.parseFromString(anchorLinkHTML, 'text/html')
const anchor = dom.querySelector('a')
return {
label: anchor?.textContent ?? '',
url: anchor?.href ?? '',
suffixText: anchor?.nextSibling?.nodeValue ?? '',
prefixText: anchor?.previousSibling?.nodeValue ?? '',
}
}
export function getFormulaLabelAndUrl(anchorLinkHTML: string) {
if (!anchorLinkHTML) {
return {
label: '',
url: '',
suffixText: '',
prefixText: '',
}
}
const parser = new DOMParser()
const dom = parser.parseFromString(anchorLinkHTML, 'text/html')
const anchor = dom.querySelector('a')
if (!anchor) {
console.warn('No anchor element found in the provided HTML')
return {
label: '',
url: '',
suffixText: '',
prefixText: '',
}
}
return {
label: anchor?.textContent ?? '',
url: anchor?.href ?? '',
suffixText: anchor?.nextSibling?.nodeValue ?? '',
prefixText: anchor?.previousSibling?.nodeValue ?? '',
}
}

Comment on lines 104 to 120
if (typeof urls === 'string') {
const { label, suffixText, prefixText, url } = getFormulaLabelAndUrl(urls)
const ctx = defaultOffscreen2DContext
ctx.font = `${pv ? 600 : 500} 13px Manrope`
ctx.fillStyle = pv ? '#3366FF' : textColor
const boxes = renderMultiLineURLWithPrefixAndSuffix(ctx, {
urlText: label,
height,
maxWidth,
prefixText,
suffixText,
x: x + padding,
y: y + 3,
lineHeight: 16,
underlineOffset: y < 36 ? 0 : 3,
})
if (boxes.some((box) => isBoxHovered(box, props.mousePosition))) {
window.open(url, '_blank')
}
return true
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Enhance URL security handling.

The current implementation opens URLs in a new window without proper security checks.

Apply this diff to improve URL security:

 if (typeof urls === 'string') {
   const { label, suffixText, prefixText, url } = getFormulaLabelAndUrl(urls)
+  // Validate URL protocol
+  const safeUrl = (() => {
+    try {
+      const urlObj = new URL(url)
+      // Only allow http/https protocols
+      if (!['http:', 'https:'].includes(urlObj.protocol)) {
+        console.warn('Blocked potentially unsafe URL protocol:', urlObj.protocol)
+        return null
+      }
+      return url
+    } catch {
+      console.warn('Invalid URL:', url)
+      return null
+    }
+  })()
+
   const ctx = defaultOffscreen2DContext
   ctx.font = `${pv ? 600 : 500} 13px Manrope`
   ctx.fillStyle = pv ? '#3366FF' : textColor
   const boxes = renderMultiLineURLWithPrefixAndSuffix(ctx, {
     urlText: label,
     height,
     maxWidth,
     prefixText,
     suffixText,
     x: x + padding,
     y: y + 3,
     lineHeight: 16,
     underlineOffset: y < 36 ? 0 : 3,
   })
-  if (boxes.some((box) => isBoxHovered(box, props.mousePosition))) {
+  if (safeUrl && boxes.some((box) => isBoxHovered(box, props.mousePosition))) {
-    window.open(url, '_blank')
+    window.open(safeUrl, '_blank', 'noopener,noreferrer')
   }
   return true
 }
📝 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
if (typeof urls === 'string') {
const { label, suffixText, prefixText, url } = getFormulaLabelAndUrl(urls)
const ctx = defaultOffscreen2DContext
ctx.font = `${pv ? 600 : 500} 13px Manrope`
ctx.fillStyle = pv ? '#3366FF' : textColor
const boxes = renderMultiLineURLWithPrefixAndSuffix(ctx, {
urlText: label,
height,
maxWidth,
prefixText,
suffixText,
x: x + padding,
y: y + 3,
lineHeight: 16,
underlineOffset: y < 36 ? 0 : 3,
})
if (boxes.some((box) => isBoxHovered(box, props.mousePosition))) {
window.open(url, '_blank')
}
return true
}
if (typeof urls === 'string') {
const { label, suffixText, prefixText, url } = getFormulaLabelAndUrl(urls)
// Validate URL protocol
const safeUrl = (() => {
try {
const urlObj = new URL(url)
// Only allow http/https protocols
if (!['http:', 'https:'].includes(urlObj.protocol)) {
console.warn('Blocked potentially unsafe URL protocol:', urlObj.protocol)
return null
}
return url
} catch {
console.warn('Invalid URL:', url)
return null
}
})()
const ctx = defaultOffscreen2DContext
ctx.font = `${pv ? 600 : 500} 13px Manrope`
ctx.fillStyle = pv ? '#3366FF' : textColor
const boxes = renderMultiLineURLWithPrefixAndSuffix(ctx, {
urlText: label,
height,
maxWidth,
prefixText,
suffixText,
x: x + padding,
y: y + 3,
lineHeight: 16,
underlineOffset: y < 36 ? 0 : 3,
})
if (safeUrl && boxes.some((box) => isBoxHovered(box, props.mousePosition))) {
window.open(safeUrl, '_blank', 'noopener,noreferrer')
}
return true
}

Copy link
Contributor
github-actions bot commented Feb 19, 2025

Uffizzi Preview deployment-61101 was deleted.

@o1lab o1lab force-pushed the nc-feat/canvas-formula-url branch from 0d1da96 to 6be6981 Compare February 19, 2025 11:10
Copy link
Contributor
@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: 0

♻️ Duplicate comments (1)
packages/nc-gui/components/smartsheet/grid/canvas/cells/Formula.ts (1)

97-116: ⚠️ Potential issue

Enhance URL security handling.

The current implementation opens URLs in a new window without proper security checks.

This is a duplicate of a previous review comment. The same security concerns about URL validation and safe window opening options still apply. Please refer to the previous review comment for the recommended fix.

🧹 Nitpick comments (1)
packages/nc-gui/components/smartsheet/grid/canvas/cells/Formula.ts (1)

62-78: Add error handling for URL processing.

The URL rendering logic could benefit from error handling to gracefully handle malformed URLs or text segments.

      const urls = replaceUrlsWithLink(result)
      const maxWidth = width - padding * 2
      if (typeof urls === 'string') {
+       try {
          const texts = getFormulaTextSegments(urls)
          ctx.font = `${pv ? 600 : 500} 13px Manrope`
          ctx.fillStyle = pv ? '#3366FF' : textColor
          renderFormulaURL(ctx, {
            texts,
            height,
            maxWidth,
            x: x + padding,
            y: y + 3,
            lineHeight: 16,
            underlineOffset: y < 36 ? 0 : 3,
          })
          return
+       } catch (error) {
+         console.warn('Error processing URL:', error)
+         // Fallback to single line text rendering
+         SingleLineTextCellRenderer.render(ctx, {
+           ...props,
+           value: urls,
+           formula: true,
+         })
+         return
+       }
      }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0d1da96 and 6be6981.

📒 Files selected for processing (3)
  • packages/nc-gui/components/smartsheet/grid/canvas/cells/Formula.ts (4 hunks)
  • packages/nc-gui/components/smartsheet/grid/canvas/utils/canvas.ts (1 hunks)
  • packages/nc-gui/utils/urlUtils.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/nc-gui/utils/urlUtils.ts
  • packages/nc-gui/components/smartsheet/grid/canvas/utils/canvas.ts
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: release-docker / buildx
  • GitHub Check: pre-build-for-playwright / playwright
  • GitHub Check: unit-tests
  • GitHub Check: unit-tests-pg
🔇 Additional comments (1)
packages/nc-gui/components/smartsheet/grid/canvas/cells/Formula.ts (1)

1-2: LGTM! Appropriate imports added for formula handling.

The new imports for FormulaDataTypes, handleTZ, and canvas utilities are well-aligned with the URL handling enhancements.

@o1lab o1lab force-pushed the nc-feat/canvas-formula-url branch from 6be6981 to 5ddece6 Compare February 19, 2025 11:17
Copy link
Contributor
@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: 1

♻️ Duplicate comments (1)
packages/nc-gui/components/smartsheet/grid/canvas/cells/Formula.ts (1)

97-116: ⚠️ Potential issue

Enhance URL security handling.

The current implementation opens URLs in a new window without proper security checks.

The security concern raised in the past review comments is still valid. Please implement the suggested security checks to protect against malicious URLs.

🧹 Nitpick comments (1)
packages/nc-gui/components/smartsheet/grid/canvas/cells/Formula.ts (1)

117-118: Address TODO comments for inline warnings.

The TODO comments indicate that inline warning functionality is incomplete. Consider implementing a more descriptive warning message or a proper error handling mechanism.

Would you like me to help implement a proper warning system for these scenarios?

Also applies to: 126-127

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6be6981 and 5ddece6.

📒 Files selected for processing (3)
  • packages/nc-gui/components/smartsheet/grid/canvas/cells/Formula.ts (4 hunks)
  • packages/nc-gui/components/smartsheet/grid/canvas/utils/canvas.ts (1 hunks)
  • packages/nc-gui/utils/urlUtils.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/nc-gui/utils/urlUtils.ts
  • packages/nc-gui/components/smartsheet/grid/canvas/utils/canvas.ts
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: pre-build-for-playwright / playwright
  • GitHub Check: unit-tests-pg
  • GitHub Check: unit-tests
  • GitHub Check: release-docker / buildx

@@ -57,10 +58,62 @@ export const FormulaCellRenderer: CellRenderer = {
})
return
}
SingleLineTextCellRenderer.render(ctx, props)

const urls = replaceUrlsWithLink(result)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix undefined variable reference.

The result variable is used but not defined. This could cause runtime errors.

Add the missing variable definition before line 62:

+      const result = isPg(column.columnObj.source_id) ? renderValue(handleTZ(value)) : renderValue(value)
       const urls = replaceUrlsWithLink(result)
📝 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
const urls = replaceUrlsWithLink(result)
const result = isPg(column.columnObj.source_id) ? renderValue(handleTZ(value)) : renderValue(value)
const urls = replaceUrlsWithLink(result)

@o1lab o1lab force-pushed the nc-feat/canvas-formula-url branch from 5ddece6 to 5b59c4b Compare February 19, 2025 12:50
Copy link
Contributor
@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: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5ddece6 and 5b59c4b.

📒 Files selected for processing (3)
  • packages/nc-gui/components/smartsheet/grid/canvas/cells/Formula.ts (4 hunks)
  • packages/nc-gui/components/smartsheet/grid/canvas/utils/canvas.ts (1 hunks)
  • packages/nc-gui/utils/urlUtils.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/nc-gui/components/smartsheet/grid/canvas/utils/canvas.ts
  • packages/nc-gui/utils/urlUtils.ts
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: release-docker / buildx
  • GitHub Check: pre-build-for-playwright / playwright
  • GitHub Check: unit-tests
  • GitHub Check: unit-tests-pg
🔇 Additional comments (2)
packages/nc-gui/components/smartsheet/grid/canvas/cells/Formula.ts (2)

62-62: Fix undefined variable reference.

The result variable is used but not defined.

Add the missing variable definition before line 62:

+      const result = isPg(column.columnObj.source_id) ? renderValue(handleTZ(value)) : renderValue(value)
       const urls = replaceUrlsWithLink(result)

64-82: Enhance URL security handling.

The current implementation processes URLs without proper security validation.

Apply the previously suggested security improvements to validate URL protocols.

Comment on lines +116 to +118
if (hoveredBox) {
window.open(hoveredBox.url, '_blank')
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve URL click handling security.

The current implementation opens URLs without proper security checks and parameters.

Apply this diff to improve security:

       if (hoveredBox) {
-        window.open(hoveredBox.url, '_blank')
+        const safeUrl = (() => {
+          try {
+            const urlObj = new URL(hoveredBox.url)
+            if (!['http:', 'https:'].includes(urlObj.protocol)) {
+              console.warn('Blocked unsafe URL protocol:', urlObj.protocol)
+              return null
+            }
+            return hoveredBox.url
+          } catch {
+            console.warn('Invalid URL:', hoveredBox.url)
+            return null
+          }
+        })()
+        if (safeUrl) {
+          window.open(safeUrl, '_blank', 'noopener,noreferrer')
+        }
       }
📝 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
if (hoveredBox) {
window.open(hoveredBox.url, '_blank')
}
if (hoveredBox) {
const safeUrl = (() => {
try {
const urlObj = new URL(hoveredBox.url)
if (!['http:', 'https:'].includes(urlObj.protocol)) {
console.warn('Blocked unsafe URL protocol:', urlObj.protocol)
return null
}
return hoveredBox.url
} catch {
console.warn('Invalid URL:', hoveredBox.url)
return null
}
})()
if (safeUrl) {
window.open(safeUrl, '_blank', 'noopener,noreferrer')
}
}

@o1lab o1lab force-pushed the nc-feat/canvas-formula-url branch from 5b59c4b to bc63cd5 Compare February 19, 2025 14:43
Copy link
Contributor
@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: 2

♻️ Duplicate comments (1)
packages/nc-gui/components/smartsheet/grid/canvas/cells/Formula.ts (1)

91-120: ⚠️ Potential issue

Enhance URL click handling security.

The URL click handling needs additional security measures.

The current implementation opens URLs without proper security checks. This issue was previously identified in past reviews. Please refer to the existing comment for the recommended fix.

🧹 Nitpick comments (3)
packages/nc-gui/utils/urlUtils.ts (1)

3-44: Improve caching implementation with error handling and cache size monitoring.

The caching implementation is good for performance optimization, but could be enhanced with error handling and monitoring.

Consider these improvements:

 export const replaceUrlsWithLink = (text: string) => {
+  if (!text) return false
+
   if (replaceUrlsWithLinkCache.has(text)) {
+    try {
       return replaceUrlsWithLinkCache.get(text)!
+    } catch (error) {
+      console.warn('Cache retrieval failed:', error)
+      replaceUrlsWithLinkCache.delete(text)
+    }
   }
+
   const result = _replaceUrlsWithLink(text)
-  replaceUrlsWithLinkCache.set(text, result)
+  try {
+    replaceUrlsWithLinkCache.set(text, result)
+  } catch (error) {
+    console.warn('Cache set failed:', error)
+  }
   return result
 }
packages/nc-gui/components/smartsheet/grid/canvas/utils/canvas.ts (2)

29-35: Consider adjusting cache size based on usage patterns.

The cache size is hardcoded to 1000 entries which might not be optimal for all use cases.

Consider making the cache size configurable:

+const DEFAULT_CACHE_SIZE = 1000
+
 export const replaceUrlsWithLinkCache: LRUCache<string, boolean | string> = new LRUCache({
-  max: 1000,
+  max: process.env.URL_CACHE_SIZE ? parseInt(process.env.URL_CACHE_SIZE) : DEFAULT_CACHE_SIZE,
 })

 export const formulaTextSegmentsCache: LRUCache<string, Array<{ text: string; url?: string }>> = new LRUCache({
-  max: 1000,
+  max: process.env.SEGMENTS_CACHE_SIZE ? parseInt(process.env.SEGMENTS_CACHE_SIZE) : DEFAULT_CACHE_SIZE,
 })

1170-1237: Optimize text rendering performance and memory usage.

The text rendering implementation could be optimized for better performance.

Consider these optimizations:

 export function renderFormulaURL(
   ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
   params: {
     texts: Array<{ text: string; url?: string }>
     x: number
     y: number
     maxWidth: number
     height: number
     lineHeight: number
     underlineOffset: number
   },
 ): { x: number; y: number; width: number; height: number; url?: string }[] {
   const { texts, x, y, maxWidth, height, lineHeight, underlineOffset } = params
+  // Pre-calculate text metrics for better performance
+  const textMetrics = new Map<string, number>()
 
   let currentX = x
   let currentY = y
   let remainingHeight = height
 
   const urlRects: { x: number; y: number; width: number; height: number; url: string }[] = []
 
   const renderText = (text: string, url?: string): void => {
     const words = text.split(' ')
 
     let wordCount = 0
     for (const word of words) {
       wordCount++
       const separator = wordCount === words.length ? '' : ' '
-      const wordWidth = ctx.measureText(word + separator).width
+      const key = word + separator
+      let wordWidth = textMetrics.get(key)
+      if (wordWidth === undefined) {
+        wordWidth = ctx.measureText(key).width
+        textMetrics.set(key, wordWidth)
+      }
 
       if (currentX + wordWidth > x + maxWidth) {
         currentX = x
         currentY += lineHeight
         remainingHeight -= lineHeight
 
         if (remainingHeight < lineHeight) {
           return // Stop rendering if out of height
         }
       }
 
       ctx.fillText(word + separator, currentX, currentY + lineHeight * 0.8)
 
       if (url) {
         urlRects.push({
           x: currentX,
           y: currentY,
           width: wordWidth,
           height: lineHeight,
           url: url,
         })
 
+        // Batch underline drawing for better performance
+        if (!ctx.batch) ctx.batch = []
+        ctx.batch.push({
+          x: currentX,
+          y: currentY + lineHeight + underlineOffset,
+          width: wordWidth
+        })
-        const underlineY = currentY + lineHeight + underlineOffset
-        ctx.strokeStyle = 'black'
-        ctx.beginPath()
-        ctx.moveTo(currentX, underlineY)
-        ctx.lineTo(currentX + wordWidth, underlineY)
-        ctx.stroke()
       }
 
       currentX += wordWidth
     }
   }
 
   for (const item of texts) {
     renderText(item.text, item.url)
   }
 
+  // Batch draw underlines
+  if (ctx.batch) {
+    ctx.strokeStyle = 'black'
+    ctx.beginPath()
+    for (const {x, y, width} of ctx.batch) {
+      ctx.moveTo(x, y)
+      ctx.lineTo(x + width, y)
+    }
+    ctx.stroke()
+    delete ctx.batch
+  }
 
   return urlRects
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5b59c4b and bc63cd5.

📒 Files selected for processing (3)
  • packages/nc-gui/components/smartsheet/grid/canvas/cells/Formula.ts (4 hunks)
  • packages/nc-gui/components/smartsheet/grid/canvas/utils/canvas.ts (3 hunks)
  • packages/nc-gui/utils/urlUtils.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: release-docker / buildx
  • GitHub Check: unit-tests
  • GitHub Check: unit-tests-pg
🔇 Additional comments (1)
packages/nc-gui/components/smartsheet/grid/canvas/utils/canvas.ts (1)

46-47: LGTM!

The cache clearing implementation is correct and comprehensive.

Comment on lines +46 to +74
export function getFormulaTextSegments(anchorLinkHTML: string) {
if (formulaTextSegmentsCache.has(anchorLinkHTML)) {
return formulaTextSegmentsCache.get(anchorLinkHTML)!
}
const container = document.createElement('div')
container.innerHTML = anchorLinkHTML

const result: Array<{ text: string; url?: string }> = []

function traverseNodes(node: ChildNode) {
if (node.nodeType === Node.TEXT_NODE) {
const text = node.textContent
if (text) {
result.push({ text })
}
} else if (node.nodeType === Node.ELEMENT_NODE) {
if ((node as Element).tagName === 'A') {
const anchor = node as HTMLAnchorElement
result.push({ text: node.textContent ?? '', url: anchor.href })
} else {
node.childNodes.forEach(traverseNodes)
}
}
}

container.childNodes.forEach(traverseNodes)
formulaTextSegmentsCache.set(anchorLinkHTML, result)
return result
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance DOM manipulation security and performance.

The function creates DOM elements for HTML parsing which could be optimized and secured.

Apply these improvements:

 export function getFormulaTextSegments(anchorLinkHTML: string) {
+  if (!anchorLinkHTML) {
+    return []
+  }
+
   if (formulaTextSegmentsCache.has(anchorLinkHTML)) {
     return formulaTextSegmentsCache.get(anchorLinkHTML)!
   }
+
+  // Sanitize input HTML
+  const sanitizedHTML = anchorLinkHTML.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
+
   const container = document.createElement('div')
-  container.innerHTML = anchorLinkHTML
+  container.innerHTML = sanitizedHTML
+
+  // Use DocumentFragment for better performance
+  const fragment = document.createDocumentFragment()
+  fragment.appendChild(container)

   const result: Array<{ text: string; url?: string }> = []

   function traverseNodes(node: ChildNode) {
     if (node.nodeType === Node.TEXT_NODE) {
       const text = node.textContent
       if (text) {
         result.push({ text })
       }
     } else if (node.nodeType === Node.ELEMENT_NODE) {
       if ((node as Element).tagName === 'A') {
         const anchor = node as HTMLAnchorElement
+        // Validate URL
+        try {
+          new URL(anchor.href)
+        } catch {
+          console.warn('Invalid URL:', anchor.href)
+          return
+        }
         result.push({ text: node.textContent ?? '', url: anchor.href })
       } else {
         node.childNodes.forEach(traverseNodes)
       }
     }
   }

   container.childNodes.forEach(traverseNodes)
   formulaTextSegmentsCache.set(anchorLinkHTML, result)
   return result
 }
📝 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
export function getFormulaTextSegments(anchorLinkHTML: string) {
if (formulaTextSegmentsCache.has(anchorLinkHTML)) {
return formulaTextSegmentsCache.get(anchorLinkHTML)!
}
const container = document.createElement('div')
container.innerHTML = anchorLinkHTML
const result: Array<{ text: string; url?: string }> = []
function traverseNodes(node: ChildNode) {
if (node.nodeType === Node.TEXT_NODE) {
const text = node.textContent
if (text) {
result.push({ text })
}
} else if (node.nodeType === Node.ELEMENT_NODE) {
if ((node as Element).tagName === 'A') {
const anchor = node as HTMLAnchorElement
result.push({ text: node.textContent ?? '', url: anchor.href })
} else {
node.childNodes.forEach(traverseNodes)
}
}
}
container.childNodes.forEach(traverseNodes)
formulaTextSegmentsCache.set(anchorLinkHTML, result)
return result
}
export function getFormulaTextSegments(anchorLinkHTML: string) {
+ if (!anchorLinkHTML) {
+ return []
+ }
+
if (formulaTextSegmentsCache.has(anchorLinkHTML)) {
return formulaTextSegmentsCache.get(anchorLinkHTML)!
}
+
+ // Sanitize input HTML
+ const sanitizedHTML = anchorLinkHTML.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
+
const container = document.createElement('div')
- container.innerHTML = anchorLinkHTML
+ container.innerHTML = sanitizedHTML
+
+ // Use DocumentFragment for better performance
+ const fragment = document.createDocumentFragment()
+ fragment.appendChild(container)
const result: Array<{ text: string; url?: string }> = []
function traverseNodes(node: ChildNode) {
if (node.nodeType === Node.TEXT_NODE) {
const text = node.textContent
if (text) {
result.push({ text })
}
} else if (node.nodeType === Node.ELEMENT_NODE) {
if ((node as Element).tagName === 'A') {
const anchor = node as HTMLAnchorElement
+ // Validate URL
+ try {
+ new URL(anchor.href)
+ } catch {
+ console.warn('Invalid URL:', anchor.href)
+ return
+ }
result.push({ text: node.textContent ?? '', url: anchor.href })
} else {
node.childNodes.forEach(traverseNodes)
}
}
}
container.childNodes.forEach(traverseNodes)
formulaTextSegmentsCache.set(anchorLinkHTML, result)
return result
}

Comment on lines +62 to +82
const urls = replaceUrlsWithLink(result)
const maxWidth = width - padding * 2
if (typeof urls === 'string') {
const texts = getFormulaTextSegments(urls)
ctx.font = `${pv ? 600 : 500} 13px Manrope`
ctx.fillStyle = pv ? '#3366FF' : textColor
const boxes = renderFormulaURL(ctx, {
texts,
height,
maxWidth,
x: x + padding,
y: y + 3,
lineHeight: 16,
underlineOffset: y < 36 ? 0 : 3,
})
const hoveredBox = boxes.find((box) => isBoxHovered(box, mousePosition))
if (hoveredBox) {
setCursor('pointer')
}
return
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Add missing variable declaration and improve URL rendering.

The code has a missing variable declaration and could benefit from improved URL handling.

Apply these fixes:

+      const result = isPg(column.columnObj.source_id) ? renderValue(handleTZ(value)) : renderValue(value)
       const urls = replaceUrlsWithLink(result)
       const maxWidth = width - padding * 2
       if (typeof urls === 'string') {
         const texts = getFormulaTextSegments(urls)
+        // Save current context state
+        const originalFont = ctx.font
+        const originalFillStyle = ctx.fillStyle
+
         ctx.font = `${pv ? 600 : 500} 13px Manrope`
         ctx.fillStyle = pv ? '#3366FF' : textColor
         const boxes = renderFormulaURL(ctx, {
           texts,
           height,
           maxWidth,
           x: x + padding,
           y: y + 3,
           lineHeight: 16,
           underlineOffset: y < 36 ? 0 : 3,
         })
         const hoveredBox = boxes.find((box) => isBoxHovered(box, mousePosition))
         if (hoveredBox) {
           setCursor('pointer')
         }
+        // Restore context state
+        ctx.font = originalFont
+        ctx.fillStyle = originalFillStyle
         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
const urls = replaceUrlsWithLink(result)
const maxWidth = width - padding * 2
if (typeof urls === 'string') {
const texts = getFormulaTextSegments(urls)
ctx.font = `${pv ? 600 : 500} 13px Manrope`
ctx.fillStyle = pv ? '#3366FF' : textColor
const boxes = renderFormulaURL(ctx, {
texts,
height,
maxWidth,
x: x + padding,
y: y + 3,
lineHeight: 16,
underlineOffset: y < 36 ? 0 : 3,
})
const hoveredBox = boxes.find((box) => isBoxHovered(box, mousePosition))
if (hoveredBox) {
setCursor('pointer')
}
return
}
const result = isPg(column.columnObj.source_id) ? renderValue(handleTZ(value)) : renderValue(value)
const urls = replaceUrlsWithLink(result)
const maxWidth = width - padding * 2
if (typeof urls === 'string') {
const texts = getFormulaTextSegments(urls)
// Save current context state
const originalFont = ctx.font
const originalFillStyle = ctx.fillStyle
ctx.font = `${pv ? 600 : 500} 13px Manrope`
ctx.fillStyle = pv ? '#3366FF' : textColor
const boxes = renderFormulaURL(ctx, {
texts,
height,
maxWidth,
x: x + padding,
y: y + 3,
lineHeight: 16,
underlineOffset: y < 36 ? 0 : 3,
})
const hoveredBox = boxes.find((box) => isBoxHovered(box, mousePosition))
if (hoveredBox) {
setCursor('pointer')
}
// Restore context state
ctx.font = originalFont
ctx.fillStyle = originalFillStyle
return
}

@AmitJoki AmitJoki merged commit 36bbfd8 into develop Feb 19, 2025
22 checks passed
@AmitJoki AmitJoki deleted the nc-feat/canvas-formula-url branch February 19, 2025 15:33
@coderabbitai coderabbitai bot mentioned this pull request Feb 20, 2025
1 task
@coderabbitai coderabbitai bot mentioned this pull request Feb 28, 2025
1 task
@coderabbitai coderabbitai bot mentioned this pull request Mar 21, 2025
7 tasks
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.

2 participants
0