Files
habitica/website/server/libs/highlightMentions.js
Fiz 8faa5b0582 Updates & Fixes: Profile Modal Tab URLs, Chat Mention Case-Insensitive, G1G1 Updates, Challenge Participants, End Challenge Modal (#15493)
* Fix profile modal tab navigation URLs for both own and other users profiles

- Add routes for /user/profile, /user/stats, and /user/achievements
- Update selectPage() to properly update URLs when switching tabs
- Own profile uses /user/{tab} format
- Other users' profiles use /profile/{userId}#{tab} format
- Parse hash fragments when navigating to other users' profile tabs
- Ensure direct navigation to tab URLs opens correct tab

* Fix undefined userId

* Server now matches usernames case insensitively like client

- Preserves original capitalization in mention text
- Fixes profile links not working with wrong case mentions

* lint fixes

* g1g1 width auto sizing w/padding

* Challenge participants spacing & text sizing fix

* Fix inconsistent profile URL format between own and other users' profiles

- Update profile tab navigation to use consistent URL format for all users
- Redirect old /user/* routes to new format for backward compatibility
- Update all navigation points (dropdown menu, notifications) to use new URLs

* Update End Challenge modal

- Replace dropdown with searchable input (384x32px) for winner selection
- Add visual badge state with gems icons for challenge completion
- Update Delete Challenge flow with refund info and proper styling
- Add close button (X) with opacity hover effect
- Enhance Award Winner button with gem icon and dynamic prize display
- Apply conditional styling based on winner selection state
- Update text colors: Maroon/50 for delete warning, Gray/100 for "OR" text
- Add proper translations for gem/gems and refund description

* lint error fixes

* end challenge modal fixes

* lint fix

* Use existing closeX component, minor UI fixes to close challenge modal

* fix lint

* Delete icon color to match text on close challenge modal

use color field to set delete icon color

* Highlight username on close challenge modal color updates

- Background color on hover: purple-600
- Text color on hover: purple-300
- Changed transition from just background-color to all so both color changes animate smoothly

* Fix strings

* Refactor g1g1 notifications from database-driven to event-based system

Changed g1g1 (gift one get one) notifications to display automatically during event periods instead of requiring database storage. Notifications now appear based on event calendar dates and use sessionStorage for dismissal state.

- Display g1g1 notification when event is active in worldState
- Store dismissal state in sessionStorage with event-specific keys
- Remove dependency on user.notifications database array
- Maintain identical user experience and appearance

* Update prize card to match participants card on challenges

* End Challenge modal UI tweaks

* Prevent false mention highlights

Prevent false mention highlights when a user's display name matches another user's username. The purple mention indicator now only appears for actual @username mentions.

* lint fixes

* Remove mention highlight

* Mention highlighting to only highlight w/username mentions

* Update G1G1 Notification

- Updated text styling for title & description
- Updated button styling
- Updated close button

* lint fix

* Add updated G1G1 notification SVGs

* Don't highlight display name w/mention

* g1g1 UI updates

- Fix sizing of gift SVGs (96px tall)
- Update button to use button element and styles <button class="btn btn-secondary mx-auto">
- Fixed positioning, color, and hover state of close icon (default white 50% opacity, hover 75% opacity)

* Fix g1g1 close icon hover state

Fix hover state of close icon (default white 50% opacity, hover 75% opacity)

* g1g1 close hover state fix

* End challenge UI updates

- Fix modal title positioning
- Fix close icon positioning
- Fix spacing between title and gem graphic
- Fix spacing between label and input field
- Fix search icon position, change input hint to "@Username"
- Set search results text align start/left with 16px starting padding.
- Fix Award Button state

* remove trailing space

* Fix exit hover state on g1g1

* fix g1g1 close icon (directly render close icon)

* new line

* Update z-index of g1g1 close button

* add display name support for mention highlighting

mention highlights now trigger for both username and display name mentions.

* Override default close button color (gray -> white)

(Also revert the renderWithMentions change)

* Fix mention display name test (& fix lint)

* Revert display name mention, strictly only username

Mentions work w/username only (works w/case insensitive as well)

* Improved case-insensitive username matching

* add close-white.svg, replace close.svg on g1g1

* find mentions that match the current user's username (case-insensitive)

* fix lint errors

* end challenge modal UI updates

* Don't change gem color on update

* disabled state button match button.scss syling

* remove padding from g1g1 close

* Directly use button.scss on end challenge modal

* Update disabled state for button.scss

* explicitly set close challenge modal button disabled/enabled state

* fix trailing space

* Add font details (and fix text color) for button disabled state

* Update award winner button min-height & padding

* button.scss button disabled styling updates

* Remove redundant disabled override on award winner button

* lint

* Use single gifts svg, and apply transform to flip horizontally

Remove unneeded gifts_end.svg

* Replaced the hardcoded #1A1B1D color with the $black from colors.scss

* Removed the 0.5em padding w/p-2

* added v-once to the refund text element

* Converted the line-height values from pixel values to multipliers
2025-09-16 22:12:41 -05:00

190 lines
6.4 KiB
JavaScript

import escapeRegExp from 'lodash/escapeRegExp';
import habiticaMarkdown from 'habitica-markdown';
import { model as User } from '../models/user';
import logger from './logger';
const mentionRegex = /\B@[-\w]+/g;
const ignoreTokenTypes = ['code_block', 'code_inline', 'fence', 'link_open'];
/**
* Container class for valid text blocks and text blocks that should be ignored.
* Blocks have the properties `text` and `ignore`
*/
class TextBlocks {
constructor (blocks) {
this.blocks = blocks;
this.validBlocks = blocks.filter(block => !block.ignore);
this.allValidText = this.validBlocks.map(block => block.text).join('\n');
}
transformValidBlocks (transform) {
this.validBlocks.forEach(block => {
block.text = transform(block.text);
});
}
rebuild () {
return this.blocks.map(block => block.text).join('');
}
}
/**
* Since tokens have both order and can be nested until infinite depth,
* use a branching recursive algorithm to maintain order and check all tokens.
*/
function findIgnoreBlocks (tokens) {
// Links span multiple tokens, so keep local state of whether we're in a link
let inLink = false;
function recursor (ts, result) {
const [head, ...tail] = ts;
if (!head) {
return result;
}
if (!inLink && ignoreTokenTypes.includes(head.type)) {
result.push(head);
}
if (head.type.includes('link')) {
inLink = !inLink;
} else if (inLink && head.type === 'text') {
const linkBlock = result[result.length - 1];
linkBlock.textContents = (linkBlock.textContents || []).concat(head.content);
}
return recursor(tail, head.children ? recursor(head.children, result) : result);
}
return recursor(tokens, []);
}
/**
* Since there are many factors that can prefix lines with indentation in
* markdown, each line from a token's content needs to be prefixed with a
* variable whitespace matcher.
*
* See for example: https://spec.commonmark.org/0.29/#example-224
*/
function withOptionalIndentation (content) {
return content.split('\n').map(line => `\\s*${line}`).join('\n');
}
/* This is essentially a workaround around the fact that markdown-it doesn't
* provide sourcemap functionality and is the most brittle part of this code.
*
* Known errors (Not supported markdown link variants):
* - [a](<b)c>) https://spec.commonmark.org/0.29/#example-489
* - [link](\(foo\)) https://spec.commonmark.org/0.29/#example-492
* - [link](foo(and(bar))) https://spec.commonmark.org/0.29/#example-493
* - [link](foo\(and\(bar\)) https://spec.commonmark.org/0.29/#example-494
* - [link](<foo(and(bar)>) https://spec.commonmark.org/0.29/#example-495
* - [link](foo\)\:) https://spec.commonmark.org/0.29/#example-496
*/
function toSourceMapRegex (token) {
const { type, content, markup } = token;
const contentRegex = escapeRegExp(content);
let regexStr = '';
if (type === 'code_block') {
regexStr = withOptionalIndentation(contentRegex);
} else if (type === 'fence') {
regexStr = `\\s*${markup}.*\n${withOptionalIndentation(contentRegex)}\\s*${markup}`;
} else if (type === 'code_inline') {
regexStr = `${markup} ?${contentRegex} ?${markup}`;
} else if (type === 'link_open') {
const texts = token.textContents ? token.textContents.map(escapeRegExp) : [''];
regexStr = markup === 'linkify' || markup === 'autolink' ? texts[0]
: `\\[[^\\]]*${texts.join('[^\\]]*')}[^\\]]*\\]\\([^)]*\\)`;
} else {
throw new Error(`No source mapping regex defined for ignore blocks of type ${type}`);
}
return new RegExp(regexStr, 's');
}
/**
* Uses habiticaMarkdown to determine which text blocks should be ignored (links and code blocks)
* according to the specification here: https://spec.commonmark.org/0.29/
*/
function findTextBlocks (text) {
// For token description see https://markdown-it.github.io/markdown-it/#Token
// The second parameter is mandatory even if not used, see
// https://markdown-it.github.io/markdown-it/#MarkdownIt.parse
const tokens = habiticaMarkdown.parse(text, {});
const ignoreBlockRegexes = findIgnoreBlocks(tokens).map(toSourceMapRegex);
const blocks = [];
let index = 0;
ignoreBlockRegexes.forEach(regex => {
const targetText = text.substr(index);
const match = targetText.match(regex);
if (!match) {
logger.error(
new Error('Failed to match source-mapping regex to find ignore block'),
{ text, targetText, regex: String(regex) },
);
return;
}
if (match.index) {
blocks.push({ text: targetText.substr(0, match.index), ignore: false });
}
blocks.push({ text: match[0], ignore: true });
index += match.index + match[0].length;
});
if (index < text.length) {
blocks.push({ text: text.substr(index), ignore: false });
}
return new TextBlocks(blocks);
}
function determineBaseUrl () {
// eslint-disable-next-line no-process-env
return process.env.NODE_ENV === 'production' ? 'https://habitica.com' : '';
}
/**
* Replaces `@user` mentions by `[@user](/profile/{user-id})` markup to inject
* a link towards the user's profile page.
* - Only works if there are no more that 5 user mentions
* - Skips mentions in code blocks as defined by https://spec.commonmark.org/0.29/
* - Skips mentions in links
*/
export default async function highlightMentions (text) {
const textBlocks = findTextBlocks(text);
const mentions = textBlocks.allValidText.match(mentionRegex);
let members = [];
if (mentions && mentions.length <= 5) {
const usernames = mentions.map(mention => mention.substr(1));
const usernameRegexes = usernames.map(username => new RegExp(`^${escapeRegExp(username)}$`, 'i'));
members = await User
.find({
$or: usernameRegexes.map(regex => ({ 'auth.local.username': regex })),
'flags.verifiedUsername': true,
})
.select(['auth.local.username', '_id', 'preferences.pushNotifications', 'pushDevices', 'party', 'guilds'])
.lean()
.exec();
const baseUrl = determineBaseUrl();
members.forEach(member => {
const { username } = member.auth.local;
const regex = new RegExp(`@${escapeRegExp(username)}(?![\\-\\w])`, 'gi');
textBlocks.transformValidBlocks(blockText => blockText.replace(regex, match => {
const mentionedUsername = match.substr(1);
return `[@${mentionedUsername}](${baseUrl}/profile/${member._id})`;
}));
});
}
return [textBlocks.rebuild(), mentions, members];
}