Skip to content
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

[Bugfix] #7924 Add link redirection in comment textarea #3504

Merged
merged 7 commits into from
Dec 23, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
(paste)="onPaste($event)"
tabindex="0"
[ngClass]="{ invalid: content.errors?.maxlength }"
(blur)="onCommentTextareaBlur()"
></div>
<p *ngIf="content.errors?.maxlength" class="error-message">
{{ 'homepage.eco-news.comment.reply-error-message' | translate }}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,19 @@ import { SocketService } from '@global-service/socket/socket.service';
import { LocalStorageService } from '@global-service/localstorage/local-storage.service';
import { BehaviorSubject, Observable } from 'rxjs';
import { TranslateModule } from '@ngx-translate/core';
import { By } from '@angular/platform-browser';
import { By, DomSanitizer } from '@angular/platform-browser';
import { PlaceholderForDivDirective } from 'src/app/main/component/comments/directives/placeholder-for-div.directive';
import { MatSelectModule } from '@angular/material/select';
import { UserProfileImageComponent } from '@global-user/components/shared/components/user-profile-image/user-profile-image.component';
import { MatMenuModule } from '@angular/material/menu';
import { MatIconModule } from '@angular/material/icon';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ElementRef } from '@angular/core';

describe('CommentTextareaComponent', () => {
let component: CommentTextareaComponent;
let fixture: ComponentFixture<CommentTextareaComponent>;
let mockSanitizer: jasmine.SpyObj<DomSanitizer>;

const socketServiceMock: SocketService = jasmine.createSpyObj('SocketService', ['onMessage', 'send', 'initiateConnection']);
socketServiceMock.onMessage = () => new Observable();
Expand Down Expand Up @@ -45,12 +47,14 @@ describe('CommentTextareaComponent', () => {
];

beforeEach(waitForAsync(() => {
mockSanitizer = jasmine.createSpyObj('DomSanitizer', ['sanitize']);
TestBed.configureTestingModule({
declarations: [CommentTextareaComponent, PlaceholderForDivDirective, UserProfileImageComponent],
providers: [
{ provide: Router, useValue: {} },
{ provide: SocketService, useValue: socketServiceMock },
{ provide: LocalStorageService, useValue: localStorageServiceMock }
{ provide: LocalStorageService, useValue: localStorageServiceMock },
{ provide: DomSanitizer, useValue: mockSanitizer }
],
imports: [MatSelectModule, TranslateModule.forRoot(), BrowserAnimationsModule, MatMenuModule, MatIconModule]
}).compileComponents();
Expand All @@ -64,6 +68,7 @@ describe('CommentTextareaComponent', () => {
beforeEach(() => {
fixture = TestBed.createComponent(CommentTextareaComponent);
component = fixture.componentInstance;
component.commentTextarea = new ElementRef(document.createElement('div'));
fixture.detectChanges();
});

Expand Down Expand Up @@ -253,4 +258,82 @@ describe('CommentTextareaComponent', () => {
imageFiles: null
});
});

describe('handleInputChange', () => {
it('should update the content value if the text content changes', () => {
component.commentTextarea.nativeElement.textContent = 'New content';
component.content.setValue('Old content');

component['handleInputChange']();

expect(component.content.value).toBe('New content');
});

it('should call updateLinksInTextarea with the new text content', () => {
const updateLinksSpy = spyOn<any>(component, 'updateLinksInTextarea');
component.commentTextarea.nativeElement.textContent = 'New content';

component['handleInputChange']();

expect(updateLinksSpy).toHaveBeenCalledWith('New content');
});
});

describe('onCommentTextareaFocus', () => {
it('should call updateLinksInTextarea with trimmed current text', () => {
const updateLinksSpy = spyOn<any>(component, 'updateLinksInTextarea');
component.commentTextarea.nativeElement.textContent = ' Current text ';
component.onCommentTextareaFocus();

expect(updateLinksSpy).toHaveBeenCalledWith('Current text');
});
});

describe('onCommentTextareaBlur', () => {
it('should set the stripped text to the content value', () => {
component.commentTextarea.nativeElement.textContent = 'Blur text';
component.onCommentTextareaBlur();

expect(component.content.value).toBe('Blur text');
});

it('should call emitComment', () => {
const emitCommentSpy = spyOn<any>(component, 'emitComment');
component.onCommentTextareaBlur();

expect(emitCommentSpy).toHaveBeenCalled();
});
});

describe('updateLinksInTextarea', () => {
it('should sanitize and set innerHTML if a URL pattern is found', () => {
const renderLinksSpy = spyOn(component, 'renderLinks').and.returnValue('<a href="http://example.com">http://example.com</a>');
mockSanitizer.sanitize.and.returnValue('<a href="http://example.com">http://example.com</a>');
const initializeLinksSpy = spyOn<any>(component, 'initializeLinkClickListeners');
const testText = 'Check this link http://example.com';

component['updateLinksInTextarea'](testText);

expect(renderLinksSpy).toHaveBeenCalledWith(testText);
expect(component.commentTextarea.nativeElement.innerHTML).toBe('<a href="http://example.com">http://example.com</a>');
expect(initializeLinksSpy).toHaveBeenCalledWith(component.commentTextarea.nativeElement);
});

describe('initializeLinkClickListeners', () => {
it('should open links in a new tab on click', () => {
const element = document.createElement('div');
const link = document.createElement('a');
link.href = 'http://example.com';
link.textContent = 'example';
element.appendChild(link);

const openSpy = spyOn(window, 'open');
component['initializeLinkClickListeners'](element);

link.click();

expect(openSpy).toHaveBeenCalledWith('http://example.com', '_blank', 'noopener,noreferrer');
});
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { debounceTime, filter, takeUntil, tap } from 'rxjs/operators';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { CHAT_ICONS } from 'src/app/chat/chat-icons';
import { insertEmoji } from '../add-emoji/add-emoji';
import { Patterns } from '@assets/patterns/patterns';

@Component({
selector: 'app-comment-textarea',
Expand Down Expand Up @@ -115,7 +116,14 @@ export class CommentTextareaComponent implements OnInit, AfterViewInit, OnChange
}

private handleInputChange(): void {
this.content.setValue(this.commentTextarea.nativeElement.textContent);
const textContent = this.commentTextarea.nativeElement.textContent;

if (this.content.value !== textContent) {
this.content.setValue(textContent);
}

this.updateLinksInTextarea(textContent);

this.emitComment();
this.closeDropdownIfNoTag();
}
Expand Down Expand Up @@ -201,6 +209,7 @@ export class CommentTextareaComponent implements OnInit, AfterViewInit, OnChange
this.commentTextarea.nativeElement.textContent = '';
}

this.updateLinksInTextarea(currentText);
const range = document.createRange();
const nodeAmount = this.commentTextarea.nativeElement.childNodes.length;
range.setStartAfter(this.commentTextarea.nativeElement.childNodes[nodeAmount - 1]);
Expand All @@ -211,6 +220,12 @@ export class CommentTextareaComponent implements OnInit, AfterViewInit, OnChange
selection.addRange(range);
}

onCommentTextareaBlur(): void {
const strippedText = this.commentTextarea.nativeElement.textContent;
this.content.setValue(strippedText);
this.emitComment();
}

onCommentKeyDown(event: KeyboardEvent): void {
if (event.key === 'Enter' || event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault();
Expand Down Expand Up @@ -267,6 +282,36 @@ export class CommentTextareaComponent implements OnInit, AfterViewInit, OnChange
});
}

private updateLinksInTextarea(currentText: string): void {
if (Patterns.urlLinkifyPattern.test(currentText)) {
const sanitizedHtml = this.sanitizer.sanitize(SecurityContext.HTML, this.renderLinks(currentText));
if (sanitizedHtml) {
this.commentTextarea.nativeElement.innerHTML = sanitizedHtml;
this.initializeLinkClickListeners(this.commentTextarea.nativeElement);
}
}
}

renderLinks(text: string): string {
return text.replace(Patterns.urlLinkifyPattern, (match) => {
const safeUrl = this.sanitizer.sanitize(SecurityContext.URL, match) || '';
return `<a href="${safeUrl}" target="_blank" rel="noopener noreferrer">${match}</a>`;
});
}

initializeLinkClickListeners(element: HTMLElement): void {
element.addEventListener('click', (event) => {
const target = event.target as HTMLElement;
if (target.tagName === 'A') {
event.preventDefault();
const href = target.getAttribute('href');
if (href) {
window.open(href, '_blank', 'noopener,noreferrer');
}
}
});
}

private insertTextAtCursor(text: string): void {
const selection = window.getSelection();
const range = selection.getRangeAt(0);
Expand Down
Loading