-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcopyLink.tsx
75 lines (67 loc) · 2.6 KB
/
copyLink.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import React, { useState } from 'react';
import { LinkIcon } from '@navikt/aksel-icons';
import { translator } from 'translations';
import { classNames } from 'utils/classnames';
import { AnalyticsEvents, logAmplitudeEvent } from 'utils/amplitude';
import { usePageContentProps } from 'store/pageContext';
import { getDecoratorParams } from 'utils/decorator-utils';
import { innholdsTypeMap } from 'types/content-props/_content-common';
import { useLayoutConfig } from 'components/layouts/useLayoutConfig';
import style from './copyLink.module.scss';
type CopyLinkProps = {
anchor: string;
heading: string;
className?: string;
showLabel?: boolean;
};
const linkCopiedDisplayTimeMs = 2500;
export const CopyLink = ({ anchor, heading, className, showLabel = true }: CopyLinkProps) => {
const [showCopyTooltip, setShowCopyTooltip] = useState(false);
const contentProps = usePageContentProps();
const { context } = getDecoratorParams(contentProps);
const { language, type } = contentProps;
const { layoutConfig } = useLayoutConfig();
const getLabel = translator('header', language);
if (!anchor) {
return null;
}
const copyLinkToClipboard = (e: React.MouseEvent) => {
e.preventDefault();
if (navigator?.clipboard?.writeText) {
const baseUrl = (e.target as HTMLAnchorElement)?.baseURI?.split('#')[0];
if (baseUrl) {
navigator?.clipboard?.writeText(`${baseUrl}${anchor}`);
setShowCopyTooltip(true);
setTimeout(() => setShowCopyTooltip(false), linkCopiedDisplayTimeMs);
}
logAmplitudeEvent(AnalyticsEvents.COPY_LINK, {
målgruppe: context,
seksjon: layoutConfig.title,
innholdstype: innholdsTypeMap[type],
});
}
};
return (
<span className={classNames(style.copyLinkContainer, className)}>
<a
href={anchor}
onClick={copyLinkToClipboard}
className={style.copyLink}
aria-label={`${getLabel('copyLinkTo')}: "${heading}"`}
>
<LinkIcon className={style.anchorIcon} aria-hidden />
{showLabel && getLabel('copyLink')}
</a>
<span
className={classNames(
style.copyTooltip,
showCopyTooltip && style.copyTooltipVisible
)}
aria-live="assertive"
aria-atomic={true}
>
{getLabel('copiedLinkConfirmed')}
</span>
</span>
);
};