Skip to content

Comments

Adds ORCID claiming button to search results#509

Open
codycooperross wants to merge 1 commit intomasterfrom
orcid-button-search-results
Open

Adds ORCID claiming button to search results#509
codycooperross wants to merge 1 commit intomasterfrom
orcid-button-search-results

Conversation

@codycooperross
Copy link
Contributor

@codycooperross codycooperross commented Aug 18, 2025

Purpose

closes: Add github issue that originated this PR

Approach

Open Questions and Pre-Merge TODOs

Learning

Types of changes

  • Bug fix (non-breaking change which fixes an issue)

  • New feature (non-breaking change which adds functionality)

  • Breaking change (fix or feature that would cause existing functionality to change)

Reviewer, please remember our guidelines:

  • Be humble in the language and feedback you give, ask don't tell.
  • Consider using positive language as opposed to neutral when offering feedback. This is to avoid the negative bias that can occur with neutral language appearing negative.
  • Offer suggestions on how to improve code e.g. simplification or expanding clarity.
  • Ensure you give reasons for the changes you are proposing.

Summary by CodeRabbit

  • New Features

    • Added a Claim button for eligible DataCite DOIs when signed in, displayed alongside work metadata.
  • Style

    • Introduced a visual divider in the metadata section for clearer separation.
    • Adjusted header layout to accommodate the optional claim action.
    • Repositioned the footer to appear after tags and added a divider below it.
  • UX

    • Shortened the description preview from 2500 to 350 characters to improve readability.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 18, 2025

Walkthrough

Introduces a conditional Claim button for DataCite DOIs based on user session and metadata visibility, adjusts header layout to accommodate the button, shortens description truncation from 2500 to 350 characters, moves footer placement, and adds a visual divider via new SCSS class.

Changes

Cohort / File(s) Summary
UI logic and layout updates
src/components/WorkMetadata/WorkMetadata.tsx
Adds session-based gating for a Claim button when DOI agency is DataCite; renders a right-side column (col-3) for the button when applicable; left header adapts between col-9/col-12; reduces description truncation to 350 chars; repositions footer; renders a divider after footer when metadata is visible; imports Claim and session helpers.
Styling additions
src/components/WorkMetadata/WorkMetadata.module.scss
Adds .divider with border-bottom: 1px solid rgb(205, 210, 213) and margin-top: 1.5rem.

Sequence Diagram(s)

sequenceDiagram
  participant U as User
  participant W as WorkMetadata.tsx
  participant S as Session
  participant C as Claim

  U->>W: Navigate to work page
  W->>S: Fetch current user/session
  S-->>W: Return user (or null)
  W->>W: Evaluate shouldDisplayOrcidButton (user && !hideMetadata && DOI && agency==DataCite)
  alt Button shown
    W->>C: Render Claim button with doi_id
  else No button
    W->>W: Render full-width header
  end
  W->>U: Render metadata, truncated description (350), footer, divider
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • jrhoads
  • wendelfabianchinsamy

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 Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch orcid-button-search-results

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 @coderabbitai in a new review comment at the desired location with your query.
  • 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 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 @coderabbitai help to get the list of available commands.

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

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
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

🧹 Nitpick comments (4)
src/components/WorkMetadata/WorkMetadata.module.scss (1)

9-12: Use theme-aware border color for better consistency (and dark mode).

Hard-coding rgb(205,210,213) may clash with Bootstrap themes. Prefer the Bootstrap border color variable so the divider adapts to light/dark themes.

Apply this diff:

 .divider {
-  border-bottom: 1px solid rgb(205, 210, 213);
+  border-bottom: 1px solid var(--bs-border-color);
   margin-top: 1.5rem;
 }
src/components/WorkMetadata/WorkMetadata.tsx (3)

199-201: Confirm product intent for aggressive description truncation (350 chars).

This is a big reduction and may hide useful context in search results. If intentional, all good; otherwise consider a slightly higher limit (e.g., 600–800) for readability.


295-311: Use react-bootstrap grid and responsive columns; avoid inline styles.

Using Row/Col improves consistency, and responsive widths prevent cramped layouts on small screens. Inline font-size isn’t necessary here.

Apply this diff:

-        {!hideTitle && (
-          <div className='row'>
-            <div
-              className={`col-${shouldDisplayOrcidButton ? '9' : '12'}`}
-            >
+        {!hideTitle && (
+          <Row>
+            <Col xs={12} lg={shouldDisplayOrcidButton ? 9 : 12}>
               {title()}
               {includeMetricsDisplay && <MetricsDisplay counts={{ citations: metadata.citationCount, views: metadata.viewCount, downloads: metadata.downloadCount }} />}
               {!hideMetadataInTable && creators()}
               {metadataTag()}
-            </div>
+            </Col>
             {shouldDisplayOrcidButton && (
-              <div className="col-3" style={{ fontSize: '1rem'}}>
+              <Col xs={12} lg={3}>
                 <Claim doi_id={metadata.doi} />
-              </div>
+              </Col>
             )}
-          </div>
+          </Row>
         )}

332-334: Add separator semantics and verify footer grid nesting.

  • Add role/aria to the decorative divider for a11y clarity.
  • footer() returns a Col; here it’s rendered inside another Col without an intervening Row, which violates Bootstrap grid nesting and can cause layout quirks.

Apply this diff for the divider:

-        {!hideMetadataInTable && <div className={styles.divider}/>}
+        {!hideMetadataInTable && <div className={styles.divider} role="separator" aria-hidden="true" />}

If you’d like to fix the grid nesting, consider changing footer() to return a simple div instead of a Col. Example (outside the changed hunk):

// replace the current footer() body
const footer = () => {
  return (
    <div className="panel-footer">
      <a href={handleUrl} className={styles.doiLink}>
        <i className="ai ai-doi"></i> {handleUrl}
      </a>
    </div>
  )
}

Alternatively, wrap the current footer() output in a Row at the call site and remove the inner Col in footer().

📜 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
  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between ebb9dfb and 12ca199.

📒 Files selected for processing (2)
  • src/components/WorkMetadata/WorkMetadata.module.scss (1 hunks)
  • src/components/WorkMetadata/WorkMetadata.tsx (5 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/components/WorkMetadata/WorkMetadata.tsx (3)
src/utils/session.ts (1)
  • session (10-32)
src/components/Claim/Claim.tsx (2)
  • Claim (34-178)
  • cache (40-63)
src/data/types.ts (1)
  • Claim (146-153)
⏰ 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). (5)
  • GitHub Check: test / cypress (4)
  • GitHub Check: test / cypress (1)
  • GitHub Check: test / cypress (2)
  • GitHub Check: test / cypress (3)
  • GitHub Check: test / cypress (5)
🔇 Additional comments (1)
src/components/WorkMetadata/WorkMetadata.tsx (1)

23-25: LGTM: targeted imports to support the Claim flow.

Importing Claim and session here keeps the work-scoped logic local and avoids loading the Claim UI unless needed later.

Comment on lines +141 to 144
const user = session()
const claim = metadata.claims ? metadata.claims[0] : null
const shouldDisplayOrcidButton = user && !hideMetadataInTable && metadata.doi && metadata.registrationAgency.id === 'datacite'

Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Guard session() for SSR and consider sync decode to avoid always-null user.

Calling session() at render can break on the server (Cookies/window not available) and, as implemented, verify() with a callback likely returns before setting user, yielding null. This can hide the button unintentionally.

Minimal guard in this component:

-  const user = session()
+  const user = typeof window !== 'undefined' ? session() : null
-  const shouldDisplayOrcidButton = user && !hideMetadataInTable && metadata.doi && metadata.registrationAgency.id === 'datacite'
+  const shouldDisplayOrcidButton =
+    !!user &&
+    !hideMetadataInTable &&
+    !!metadata.doi &&
+    metadata.registrationAgency?.id === 'datacite'

If session() is using asynchronous verification, please switch to a synchronous decode/verify (no callback) or a lightweight decode (e.g., jwt-decode) on the client. I can open a follow-up PR to adjust session() accordingly.

Run this script to confirm the async verify pattern in session.ts:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "session() implementation:"
rg -n -A5 -B8 $'export\\s+const\\s+session\\s*=\\s*\\(' src/utils/session.ts

echo
echo "Check for async JsonWebToken.verify callback usage:"
rg -n -C2 'JsonWebToken\\.verify\\s*\\(.*\\,\\s*.*\\,\\s*\\{[^}]*\\}\\s*,\\s*[^)]*\\)' src/utils/session.ts || true

Length of output: 970


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Displaying full session() implementation in src/utils/session.ts:"
sed -n '1,200p' src/utils/session.ts

Length of output: 970


Ensure session() is synchronous and guard against SSR to correctly display the ORCID button

The current session() implementation uses JsonWebToken.verify with a callback, so it always returns null (the callback runs after return). Additionally, calling session() during SSR may throw if window/cookies aren’t available.

• src/utils/session.ts

  • Replace the async callback pattern with a synchronous verify or lightweight decode.
  • Example refactor:
export const session = (): User => {
  if (!JWT_KEY) return null
  const sessionCookie = Cookies.getJSON('_datacite')
  const token = sessionCookie?.authenticated?.access_token
  if (!token) return null

- let user: any = null
- function setUser(error: any, payload: any) {
-   if (error) {
-     console.log('JWT verification error: ' + error.message)
-     return
-   }
-
-   user = payload
- }
-
- JsonWebToken.verify(token, JWT_KEY, { algorithms: ['RS256'] }, setUser)
-
- return user as User
+ try {
+   return JsonWebToken.verify(token, JWT_KEY, { algorithms: ['RS256'] }) as User
+ } catch (err) {
+   console.error('JWT verification error:', err)
+   return null
+ }
}

• src/components/WorkMetadata/WorkMetadata.tsx

  • Guard client‐only calls and tighten null checks:
- const user = session()
+ const user = typeof window !== 'undefined' ? session() : null

- const shouldDisplayOrcidButton = user && !hideMetadataInTable && metadata.doi && metadata.registrationAgency.id === 'datacite'
+ const shouldDisplayOrcidButton =
+   Boolean(user) &&
+   !hideMetadataInTable &&
+   Boolean(metadata.doi) &&
+   metadata.registrationAgency?.id === 'datacite'

Let me know if you’d like assistance wiring up a React hook or using jwt-decode for a lighter client‐side implementation.

📝 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 user = session()
const claim = metadata.claims ? metadata.claims[0] : null
const shouldDisplayOrcidButton = user && !hideMetadataInTable && metadata.doi && metadata.registrationAgency.id === 'datacite'
const user = typeof window !== 'undefined' ? session() : null
const claim = metadata.claims ? metadata.claims[0] : null
const shouldDisplayOrcidButton =
Boolean(user) &&
!hideMetadataInTable &&
Boolean(metadata.doi) &&
metadata.registrationAgency?.id === 'datacite'
🤖 Prompt for AI Agents
In src/components/WorkMetadata/WorkMetadata.tsx around lines 141 to 144, the
call to session() is currently returning null because the session helper uses an
async callback verify and is also unsafe during SSR; replace the session
implementation in src/utils/session.ts with a synchronous token decode/verify
(for example use jwt-decode or a synchronous verify call) so session() returns
the user immediately, and in this file guard the client-only call by checking
typeof window !== 'undefined' before invoking session(), and tighten the
ORCID-button condition to ensure metadata.registrationAgency exists and has id
=== 'datacite' and metadata.doi is present and user is non-null so the
shouldDisplayOrcidButton is computed safely on the client.

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