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

feat(ui): Adjust linkify directive #739

Merged
merged 2 commits into from
Jan 8, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
58 changes: 54 additions & 4 deletions libs/ui/elements/src/lib/metadata-info/linkify.directive.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,35 @@ const testingUrls = [
'http://foo.com/(something)?after=parens',
],
]

const testWithMultipleUrls = {
input:
'Fourteenth links http://foo.com/(something)?after=parens with multiple links http://foo.com/(something)?before=multiple',
output: [
'http://foo.com/(something)?after=parens',
'http://foo.com/(something)?before=multiple',
],
}

const testWithHTML = {
input:
'<p>Fourteenth link with html input <a href="http://foo.com/(something)?after=before">This is the display text</a> query params</p>',
output: 'http://foo.com/(something)?after=before',
}

@Component({
template: `<div [gnUiLinkify]>{{ text }}</div>`,
template: `<div
*ngIf="customInnerHTML"
[innerHTML]="customInnerHTML"
[gnUiLinkify]
></div>
<div *ngIf="!customInnerHTML" [gnUiLinkify]>
{{ text }}
</div>`,
})
class TestComponent {
text = ''
customInnerHTML = null
}

describe('GnUiLinkifyDirective', () => {
Expand All @@ -80,23 +104,49 @@ describe('GnUiLinkifyDirective', () => {
component.text = input
fixture.detectChanges()
await fixture.whenStable()
const href = getAnchorElement().nativeElement.getAttribute('href')
const href = getAnchorElement()[0].nativeElement.getAttribute('href')
expect(href).toBe(output)
}
)

it('should create multiple anchor elements with the correct href', async () => {
component.text = testWithMultipleUrls.input
const output = testWithMultipleUrls.output
fixture.detectChanges()
await fixture.whenStable()
const amountOfAnchors = getAnchorElement().length
const firstHref = getAnchorElement()[0].nativeElement.getAttribute('href')
const secondHref =
getAnchorElement()[1].nativeElement.getAttribute('href')
expect(amountOfAnchors).toBe(2)
expect(firstHref).toBe(output[0])
expect(secondHref).toBe(output[1])
})
})

it('should have the target attribute set to "_blank"', async () => {
component.text = 'Click this link https://www.example.com/'
fixture.detectChanges()
await fixture.whenStable()
const target = getAnchorElement().nativeElement.getAttribute('target')
const target = getAnchorElement()[0].nativeElement.getAttribute('target')
expect(target).toBe('_blank')
})
function getAnchorElement() {
debugElement = fixture.debugElement.query(
By.directive(GnUiLinkifyDirective)
)
return debugElement.query(By.css('a'))
return debugElement.queryAll(By.css('a'))
}

describe('HTML input', () => {
it('should create an anchor element with the correct href', async () => {
component.customInnerHTML = testWithHTML.input
fixture.detectChanges()
await fixture.whenStable()
const href = getAnchorElement()[0].nativeElement.getAttribute('href')
const matIcon = getAnchorElement()[0].nativeElement.childNodes[1]
expect(href).toBe(testWithHTML.output)
expect(matIcon.nodeName).toContain('MAT-ICON')
})
})
})
30 changes: 15 additions & 15 deletions libs/ui/elements/src/lib/metadata-info/linkify.directive.stories.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
import {
componentWrapperDecorator,
Meta,
moduleMetadata,
StoryObj,
} from '@storybook/angular'
import { Meta, moduleMetadata, StoryObj } from '@storybook/angular'
import { GnUiLinkifyDirective } from './linkify.directive'

export default {
Expand All @@ -17,13 +12,19 @@ export default {

export const Primary: StoryObj<any> = {
args: {
htmlContent: `Région Hauts-de-France, Dreal, IGN BD Topo<br>

Les données produites s'appuient sur le modèle CNIG de juin 2018 relatif aux SCoT : http://cnig.gouv.fr/wp-content/uploads/2019/04/190315_Standard_CNIG_SCOT.pdf<br>

La structure a été modifiée au 03/2023 pour prendre en compte les évolutions du modèle CNIG du 10/06/2021 :<br>
http://cnig.gouv.fr/IMG/pdf/210615_standard_cnig_nouveauscot.pdf<br>
(il coexiste donc dans le modèle des champs liés aux deux modèles, par exemple sur les PADD pour les "anciens" SCoT, ou encore sur les PAS ou les DAAC pour les "nouveaux" SCoT)`,
htmlContent: `<p class='my-2'>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin purus elit, tincidunt et gravida sit amet, mattis eget orci. Suspendisse dignissim magna sed neque rutrum lobortis. Aenean vitae quam sapien. Phasellus eleifend tortor ac imperdiet tristique. Curabitur aliquet mauris tristique, iaculis est sit amet, pulvinar ipsum. Maecenas lacinia varius felis sit amet tempor. Curabitur pulvinar ipsum eros, quis accumsan odio hendrerit sit amet.</p>
This is a link without markup: http://cnig.gouv.fr/wp-content/uploads/2019/04/190315_Standard_CNIG_SCOT.pdf<br>
Another link without markup:<br>
http://cnig.gouv.fr/IMG/pdf/210615_standard_cnig_nouveauscot.pdf<br>
<p class='my-2'>This is a link with markup: <a href="http://foo.com/(something)?after=before">This is the display text</a></p>
This is a list containing links:
<ul class='list-disc my-2 ml-3'>
<li>http://cnig.gouv.fr/IMG/pdf/210615_standard_cnig_nouveauscot.pdf</li>
<li><a href="http://foo.com/(something)?after=before">This is the display text</a></li>
<li><a href="http://foo.com/(something)?after=before" style='font-weight: bolder;'>
<span>Same link with style and <code>span</code> element inside</span>
</a></li>
</ul>`,
},
argTypes: {
htmlContent: {
Expand All @@ -33,8 +34,7 @@ export const Primary: StoryObj<any> = {
render: (args) => ({
props: args,
template: `
<div
gnUiLinkify>
<div gnUiLinkify>
${args.htmlContent}
</div>`,
}),
Expand Down
68 changes: 55 additions & 13 deletions libs/ui/elements/src/lib/metadata-info/linkify.directive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,30 +9,72 @@ export class GnUiLinkifyDirective implements OnInit {

ngOnInit() {
setTimeout(() => {
this.processLinks()
this.processLinks(this.el.nativeElement)
}, 0)
}

private processLinks() {
const container = this.el.nativeElement

private processLinks(container: HTMLElement | ChildNode) {
const nodes = Array.from(container.childNodes)

nodes.forEach((node) => {
if (node instanceof Text) {
const textNode = node as Text
const linkified = this.linkifyText(textNode.nodeValue)
const span = this.renderer.createElement('span')
span.innerHTML = linkified
container.insertBefore(span, textNode)
container.removeChild(textNode)
const linkified = this.linkifyNode(textNode.nodeValue)
if (linkified) {
this.createLinkElements(container, linkified, node)
}
} else if (node instanceof HTMLAnchorElement) {
const url = node.href
const displayValue = node.innerHTML
const linkified = this.linkifyNode(displayValue, url)
if (linkified) {
this.createLinkElements(container, linkified, node)
}
} else {
this.processLinks(node)
}
})
}

private linkifyText(text: string): string {
return text.replace(/(\bhttps?:\/\/\S+\b[=)/]?)/g, (match) => {
return `<a href="${match}" target="_blank"
class="text-primary cursor-pointer hover:underline">${match} <mat-icon class="material-symbols-outlined !w-[12px] !h-[14px] !text-[14px] opacity-75">open_in_new</mat-icon></a>`
private linkifyNode(displayValue: string, url?: string): string | undefined {
if (url) {
displayValue = this.createLink(displayValue, url)
} else {
const urlRegex = /\bhttps?:\/\/\S+\b[=)/]?/g
const matches = displayValue.match(urlRegex)

if (matches && matches.length > 0) {
matches.forEach((match) => {
url = match

displayValue = displayValue.replace(match, (match) => {
return this.createLink(match, url)
})
})
}
}

return displayValue
}

private createLinkElements(
container: HTMLElement | ChildNode,
htmlContent: string,
node: ChildNode
): void {
const div = this.renderer.createElement('div')
div.innerHTML = htmlContent

const fragment = document.createDocumentFragment()
Array.from(div.childNodes).forEach((childNode: ChildNode) => {
fragment.appendChild(childNode)
})

container.insertBefore(fragment, node)
container.removeChild(node)
}

private createLink(displayValue: string, url: string): string {
return `<a href="${url}" target="_blank" class="text-primary cursor-pointer hover:underline">${displayValue} <mat-icon class="material-symbols-outlined !w-[12px] !h-[14px] !text-[14px] opacity-75">open_in_new</mat-icon></a>`
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
<p
class="whitespace-pre-line break-words sm:mb-4 sm:pr-16"
[innerHTML]="metadata.abstract"
gnUiLinkify
></p>
<ng-container *ngIf="metadata.keywords?.length">
<p class="mb-3 font-medium text-primary text-sm" translate>
Expand Down Expand Up @@ -100,11 +101,7 @@
<p class="text-sm" translate>record.metadata.sheet</p>
<p class="text-primary font-medium mt-1" translate>
<a [href]="metadata.landingPage" target="_blank">
<mat-icon
class="material-symbols-outlined inline-block align-bottom pt-1.5 text-xs text-black !w-[20px]"
>open_in_new</mat-icon
>
<span class="break-all">{{ metadata.landingPage }}</span>
<span class="break-all" gnUiLinkify>{{ metadata.landingPage }}</span>
</a>
</p>
</div>
Expand Down
Loading