Skip to content

Commit 4b1f1f2

Browse files
melissawmstory645
andcommitted
Add index for tags pages
Co-authored-by: hannah <story645@gmail.com>
1 parent 0842553 commit 4b1f1f2

File tree

1 file changed

+53
-6
lines changed

1 file changed

+53
-6
lines changed

src/sphinx_tags/__init__.py

Lines changed: 53 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
33
"""
44

5-
from sphinx.domains import Domain
5+
from sphinx.domains import Domain, Index, IndexEntry
66
from sphinx.util.logging import getLogger
77
from sphinx.util.docutils import SphinxDirective
88
from sphinx.errors import ExtensionError
@@ -14,6 +14,8 @@
1414
from typing import List
1515
from fnmatch import fnmatch
1616
import re
17+
from collections.abc import Iterable
18+
from collections import defaultdict
1719

1820
__version__ = "0.4dev"
1921

@@ -66,7 +68,8 @@ def run(self):
6668
page_tags.extend(
6769
[_normalize_tag(tag) for tag in ",".join(self.content).split(",")]
6870
)
69-
# Remove empty elements from page_tags (can happen after _normalize_tag())
71+
# Remove empty elements from page_tags
72+
# (can happen after _normalize_tag())
7073
page_tags = list(filter(None, page_tags))
7174

7275
global_tags = self.env.get_domain("tags")
@@ -104,6 +107,9 @@ def run(self):
104107
if not count == len(page_tags):
105108
result += nodes.inline(text=tag_separator)
106109

110+
td = self.env.get_domain("tags")
111+
td.add_tagpage(self.env.docname, page_tags)
112+
107113
return [result]
108114

109115
def _get_plaintext_node(
@@ -146,6 +152,33 @@ def _get_tag_color(self, tag: str) -> str:
146152
return "primary"
147153

148154

155+
class PagesIndex(Index):
156+
"""A custom index that creates a pages matrix."""
157+
158+
name = "tagpage"
159+
localname = "Page Index"
160+
shortname = "TagPage"
161+
162+
def generate(
163+
self, docnames: Iterable[str] | None = None
164+
) -> tuple[list[tuple[str, list[IndexEntry]]], bool]:
165+
content = defaultdict(list)
166+
167+
# sort the list of pages
168+
pages = sorted(self.domain.get_objects(), key=lambda page: page[0])
169+
170+
# name, subtype, docname, anchor, extra, qualifier, description
171+
172+
for _name, dispname, typ, docname, anchor, _priority in pages:
173+
content[dispname[0].lower()].append(
174+
(dispname, 0, docname, anchor, docname, "", typ)
175+
)
176+
177+
# convert the dict to the sorted list of tuples expected
178+
179+
return sorted(content.items()), True
180+
181+
149182
class TagsDomain(Domain):
150183

151184
name = "tags"
@@ -157,12 +190,15 @@ class TagsDomain(Domain):
157190
"tags": TagLinks,
158191
}
159192

193+
indices = [PagesIndex]
194+
160195
# The values defined in initial_data will be copied to
161196
# env.domaindata[domain_name] as the initial data of the domain, and domain
162197
# instances can access it via self.data.
163198
initial_data = {
164-
"tags": [],
165-
"entries": {},
199+
"tags": [], # list of tags
200+
"entries": {}, # list of pages with tags
201+
"pages": [], # list of tag pages
166202
}
167203

168204
def get_full_qualified_name(self, node):
@@ -186,6 +222,17 @@ def add_tag(self, tagname, page):
186222
# name, dispname, type, docname, anchor, priority
187223
self.data["tags"].append((tagname, tagname, "Tag", page, anchor, 0))
188224

225+
def add_tagpage(self, docname, tags):
226+
"""Add a new page of tags to domain"""
227+
name = f"tagpage.{docname}"
228+
anchor = f"tagpage-{docname}"
229+
230+
print(f"{self.data['tags']=}")
231+
# name, dispname, type, docname, anchor, priority
232+
self.data["pages"].append(
233+
(name, docname, "TagPage", self.env.docname, anchor, 0)
234+
)
235+
189236

190237
def create_file(
191238
app,
@@ -346,7 +393,7 @@ def update_tags(app):
346393
os.remove(os.path.join(app.srcdir, tags_output_dir, file))
347394

348395
# Create pages for each tag
349-
global_tags = env.get_domain("tags").data["entries"]
396+
global_tags = app.env.get_domain("tags").data["entries"]
350397
logger.info(f"Global tags: {global_tags=}", color="green")
351398

352399
for tag in global_tags.items():
@@ -408,7 +455,7 @@ def setup(app):
408455
# Update tags
409456
# Tags should be updated after sphinx-gallery is generated, on
410457
# builder-inited
411-
app.connect("source-read", update_tags)
458+
app.connect("builder-inited", update_tags)
412459
app.add_directive("tags", TagLinks)
413460
app.add_domain(TagsDomain)
414461

0 commit comments

Comments
 (0)