11import React , { createContext , useContext } from "react" ;
22import type { ReactNode } from "react" ;
3+ import { assert } from "tsafe/assert" ;
34
45import type { DetailedHTMLProps , AnchorHTMLAttributes } from "react" ;
56
67// eslint-disable-next-line @typescript-eslint/no-empty-interface
8+
9+ /*
710export interface LinkProps extends React.AriaAttributes {
811 className?: string;
912 children?: ReactNode;
1013}
14+ */
1115
1216export type HTMLAnchorProps = DetailedHTMLProps <
1317 AnchorHTMLAttributes < HTMLAnchorElement > ,
1418 HTMLAnchorElement
1519> ;
1620
17- //NOTE: Here we have use as any because the module augmentation that we define in ../next applies unfortunately.
18- const context = createContext < CreateLinkProviderPrams [ "Link" ] > ( props => < a { ...( props as any ) } /> ) ;
21+ // eslint-disable-next-line @typescript-eslint/no-empty-interface
22+ export interface RegisterLink {
23+ // Link: typeof Link
24+ }
25+
26+ export type RegisteredLinkProps = RegisterLink extends {
27+ Link : ( props : infer LinkProps ) => any ;
28+ }
29+ ? Omit < LinkProps , "children" >
30+ : RegisterLink extends { Link : "a" }
31+ ? Omit < HTMLAnchorProps , "children" >
32+ : React . AriaAttributes & { className ?: string } ;
33+
34+ const context = createContext < CreateLinkProviderPrams [ "Link" ] | undefined > ( undefined ) ;
1935
2036type CreateLinkProviderPrams = {
21- Link : ( props : LinkProps ) => ReturnType < React . FC > ;
37+ Link : ( ( props : RegisteredLinkProps & { children : ReactNode } ) => ReturnType < React . FC > ) | "a" ;
2238} ;
2339
2440export function createDsfrLinkProvider ( params : CreateLinkProviderPrams ) {
@@ -38,7 +54,16 @@ export function createDsfrLinkProvider(params: CreateLinkProviderPrams) {
3854}
3955
4056export function useLink ( ) {
41- const Link = useContext ( context ) ;
57+ let Link = useContext ( context ) ;
58+
59+ assert (
60+ Link !== undefined ,
61+ "You need to specify what routing library is in use in your project, see: https://react-dsfr.etalab.studio/routing"
62+ ) ;
63+
64+ if ( Link === "a" ) {
65+ Link = props => < a { ...props } /> ;
66+ }
4267
4368 return { Link } ;
4469}
0 commit comments