11import contextvars
22import markdown
3- import posixpath
43import httpx
4+ import os
55import pathlib
6+ import posixpath
67
78
89page_context = contextvars .ContextVar ('page_context' )
910
1011
12+ def joinpath (x : pathlib .Path , y : pathlib .Path ):
13+ return pathlib .Path (os .path .normpath (x .joinpath (y )))
14+
1115class PageContext :
12- def __init__ (self , path : pathlib .Path , path_to_url : dict [pathlib .Path , str ]):
16+ def __init__ (self , path : pathlib .Path , path_to_url : dict [pathlib .Path , str ], relative : bool ):
1317 self .path = path
1418 self .path_to_url = path_to_url
1519 self .url_to_path = {u : p for p , u in path_to_url .items ()}
20+ self .relative = relative
1621
1722 def __enter__ (self ):
1823 self ._token = page_context .set (self )
@@ -31,6 +36,7 @@ def run(self, root):
3136 link = ''
3237
3338 for el in root .iter ():
39+ # We want to rewrite image and links.
3440 if el .tag == 'a' :
3541 key = 'href'
3642 link = el .get (key )
@@ -43,11 +49,21 @@ def run(self, root):
4349
4450 if link :
4551 url = httpx .URL (link )
52+ # We want to rewrite relative links... '/page'
53+ # We don't want to rewrite external links. 'https://elsewhere.com/here'
54+ # We don't want to rewrite anchor links. '#section'
4655 if url .is_relative_url and url ._uri_reference .path :
56+ link = pathlib .PosixPath (url .path )
57+
58+ # Path to the current page...
4759 from_path = ctx .path
48- to_path = ctx .path .parent .joinpath (url .path )
60+ # Path to the linked page...
61+ to_path = joinpath (ctx .path .parent , link ) if ctx .relative else link
62+ # Current URL...
4963 from_url = ctx .path_to_url [from_path ]
64+ # Linked URL...
5065 to_url = ctx .path_to_url .get (to_path )
66+
5167 if to_url is None :
5268 continue
5369 rewrite = posixpath .relpath (to_url , from_url )
@@ -60,10 +76,12 @@ def run(self, root):
6076 el .set (key , rewrite )
6177 links .append ({"title" : el .text , "url" : rewrite })
6278
79+ # Is this is a link to the current page?
6380 if from_url == to_url :
6481 el .set ('class' , 'active' )
6582 idx = len (links )
6683
84+ # We also want to track the previous and next link.
6785 links = [None ] + links + [None ]
6886 if idx is not None :
6987 ctx .previous = links [idx - 1 ]
0 commit comments