Skip to content

Allow multiple references to the same footnote #40

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion tests/templates/test/endnote_reference.html
Original file line number Diff line number Diff line change
@@ -1 +1 @@
<a href="#endnote-{{ index }}" id="endnote-source-{{ index }}"><sup>{{ index }}</sup></a>
<a href="#endnote-{{ index }}" id="endnote-source-{{ index }}-{{ reference_index }}"><sup>{{ index }}</sup></a>
68 changes: 54 additions & 14 deletions tests/test/test_blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,19 +38,47 @@ def setUp(self):
[
{
"type": "paragraph",
"value": f'<p>This is a paragraph with a footnote. <footnote id="{uuid}">1</footnote></p>',
"value": (
f'<p>This is a paragraph with a footnote. <footnote id="{uuid}">[{uuid[:6]}]</footnote></p>'
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The [{uuid[:6]}] bit isn't strictly required since FIND_FOOTNOTE_TAG doesn't care what's between <footnote></footnote> but I opted to make it an accurate representation of what is actually stored in the database.

),
},
]
),
)
home_page.add_child(instance=self.test_page_with_footnote)
self.test_page_with_footnote.save_revision().publish()
self.footnote = Footnote.objects.create(
Footnote.objects.create(
page=self.test_page_with_footnote,
uuid=uuid,
text="This is a footnote",
)

self.test_page_with_multiple_references_to_the_same_footnote = TestPageStreamField(
title="Test Page With Multiple References to the Same Footnote",
slug="test-page-with-multiple-references-to-the-same-footnote",
body=json.dumps(
[
{
"type": "paragraph",
"value": (
f'<p>This is a paragraph with a footnote. <footnote id="{uuid}">[{uuid[:6]}]</footnote></p>'
f"<p>This is another paragraph with a reference to the same footnote. "
f'<footnote id="{uuid}">[{uuid[:6]}]</footnote></p>'
),
},
]
),
)
home_page.add_child(
instance=self.test_page_with_multiple_references_to_the_same_footnote
)
self.test_page_with_multiple_references_to_the_same_footnote.save_revision().publish()
Footnote.objects.create(
page=self.test_page_with_multiple_references_to_the_same_footnote,
uuid=uuid,
text="This is a footnote",
)

def test_block_with_no_features(self):
block = RichTextBlockWithFootnotes()
self.assertIsInstance(block, blocks.RichTextBlock)
Expand Down Expand Up @@ -98,35 +126,47 @@ def test_block_replace_footnote_tags(self):
html = block.replace_footnote_tags(None, "foo")
self.assertEqual(html, "foo")

def test_block_replace_footnote_render_basic(self):
def test_block_replace_footnote_render(self):
rtb = self.test_page_with_footnote.body.stream_block.child_blocks["paragraph"]
value = rtb.get_prep_value(self.test_page_with_footnote.body[0].value)
context = self.test_page_with_footnote.get_context(self.client.get("/"))
out = rtb.render_basic(value, context=context)
result = '<p>This is a paragraph with a footnote. <a href="#footnote-1" id="footnote-source-1"><sup>[1]</sup></a></p>'
out = rtb.render(value, context=context)
result = (
'<p>This is a paragraph with a footnote. <a href="#footnote-1" id="footnote-source-1-1"><sup>[1]</sup></a>'
"</p>"
)
self.assertHTMLEqual(out, result)

def test_block_replace_footnote_render(self):
rtb = self.test_page_with_footnote.body.stream_block.child_blocks["paragraph"]
value = rtb.get_prep_value(self.test_page_with_footnote.body[0].value)
context = self.test_page_with_footnote.get_context(self.client.get("/"))
def test_block_replace_footnote_with_multiple_references_render(self):
body = self.test_page_with_multiple_references_to_the_same_footnote.body
rtb = body.stream_block.child_blocks["paragraph"]
value = rtb.get_prep_value(body[0].value)
context = (
self.test_page_with_multiple_references_to_the_same_footnote.get_context(
self.client.get("/")
)
)
out = rtb.render(value, context=context)
result = '<p>This is a paragraph with a footnote. <a href="#footnote-1" id="footnote-source-1"><sup>[1]</sup></a></p>'
result = (
'<p>This is a paragraph with a footnote. <a href="#footnote-1" id="footnote-source-1-1"><sup>[1]</sup></a>'
'</p><p>This is another paragraph with a reference to the same footnote. <a href="#footnote-1" '
'id="footnote-source-1-2"><sup>[1]</sup></a></p>'
)
self.assertHTMLEqual(out, result)

def test_render_footnote_tag(self):
block = RichTextBlockWithFootnotes()
html = block.render_footnote_tag(2)
html = block.render_footnote_tag(index=2, reference_index=1)
self.assertHTMLEqual(
html, '<a href="#footnote-2" id="footnote-source-2"><sup>[2]</sup></a>'
html, '<a href="#footnote-2" id="footnote-source-2-1"><sup>[2]</sup></a>'
)

@override_settings(
WAGTAIL_FOOTNOTES_REFERENCE_TEMPLATE="test/endnote_reference.html"
)
def test_render_footnote_tag_new_template(self):
block = RichTextBlockWithFootnotes()
html = block.render_footnote_tag(2)
html = block.render_footnote_tag(index=2, reference_index=1)
self.assertHTMLEqual(
html, '<a href="#endnote-2" id="endnote-source-2"><sup>2</sup></a>'
html, '<a href="#endnote-2" id="endnote-source-2-1"><sup>2</sup></a>'
)
8 changes: 4 additions & 4 deletions tests/test/test_functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,21 +78,21 @@ def test_with_footnote(self):

# Test that required html tags are present with correct
# attrs that enable the footnotes to respond to clicks
source_anchor = soup.find("a", {"id": "footnote-source-1"})
source_anchor = soup.find("a", {"id": "footnote-source-1-1"})
self.assertTrue(source_anchor)

source_anchor_string = str(source_anchor)
self.assertIn("<sup>[1]</sup>", source_anchor_string)
self.assertIn('href="#footnote-1"', source_anchor_string)
self.assertIn('id="footnote-source-1"', source_anchor_string)
self.assertIn('id="footnote-source-1-1"', source_anchor_string)

footnotes = soup.find("div", {"class": "footnotes"})
self.assertTrue(footnotes)

footnotes_string = str(footnotes)
self.assertIn('id="footnote-1"', footnotes_string)
self.assertIn('href="#footnote-source-1"', footnotes_string)
self.assertIn("[1] This is a footnote", footnotes_string)
self.assertIn('href="#footnote-source-1-1"', footnotes_string)
self.assertIn("This is a footnote", footnotes_string)

def test_edit_page_with_footnote(self):
self.client.force_login(self.admin_user)
Expand Down
8 changes: 4 additions & 4 deletions tests/test/test_translation.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,18 +138,18 @@ def test_translated_page_shows_translated_footnote(self):

# Test that required html tags are present with correct
# attrs that enable the footnotes to respond to clicks
source_anchor = soup.find("a", {"id": "footnote-source-1"})
source_anchor = soup.find("a", {"id": "footnote-source-1-1"})
self.assertTrue(source_anchor)

source_anchor_string = str(source_anchor)
self.assertIn("<sup>[1]</sup>", source_anchor_string)
self.assertIn('href="#footnote-1"', source_anchor_string)
self.assertIn('id="footnote-source-1"', source_anchor_string)
self.assertIn('id="footnote-source-1-1"', source_anchor_string)

footnotes = soup.find("div", {"class": "footnotes"})
self.assertTrue(footnotes)

footnotes_string = str(footnotes)
self.assertIn('id="footnote-1"', footnotes_string)
self.assertIn('href="#footnote-source-1"', footnotes_string)
self.assertIn("[1] This is a French translated footnote", footnotes_string)
self.assertIn('href="#footnote-source-1-1"', footnotes_string)
self.assertIn("This is a French translated footnote", footnotes_string)
71 changes: 48 additions & 23 deletions wagtail_footnotes/blocks.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import re

from django.conf import settings
from django.core.exceptions import ValidationError
from django.template.loader import get_template
from django.utils.safestring import mark_safe
from wagtail.blocks import RichTextBlock
from wagtail.models import Page

from wagtail_footnotes.models import Footnote


FIND_FOOTNOTE_TAG = re.compile(r'<footnote id="(.*?)">.*?</footnote>')

Expand All @@ -15,69 +16,93 @@ class RichTextBlockWithFootnotes(RichTextBlock):
"""
Rich Text block that renders footnotes in the format
'<footnote id="long-id">short-id</footnote>' as anchor elements. It also
adds the Footnote object to the 'page' object for later use. It uses
adds the Footnote object(s) to the 'page' object for later use. It uses
'page' because variables added to 'context' do not persist into the
final template context.
"""

all_footnotes: dict[str, Footnote]

def __init__(self, **kwargs):
super().__init__(**kwargs)
if not self.features:
self.features = []
if "footnotes" not in self.features:
self.features.append("footnotes")

def render_footnote_tag(self, index):
def render_footnote_tag(self, index: int, reference_index: int):
template_name = getattr(
settings,
"WAGTAIL_FOOTNOTES_REFERENCE_TEMPLATE",
"wagtail_footnotes/includes/footnote_reference.html",
)
template = get_template(template_name)
return template.render({"index": index})
return template.render({"index": index, "reference_index": reference_index})

def replace_footnote_tags(self, value, html, context=None):
if context is None:
new_context = self.get_context(value)
else:
new_context = self.get_context(value, parent_context=dict(context))

if not isinstance(new_context.get("page"), Page):
page = new_context.get("page")
if page is None or not isinstance(page, Page):
return html

page = new_context["page"]
if not hasattr(page, "footnotes_list"):
page.footnotes_list = []
self.footnotes = {
# Map Footnote UUIDs to Footnote instances to simplify lookups once a reference has been found in the text.
# NOTE: Footnotes may exist in the database for a given page but this does not necessarily mean that the
# footnote was referenced in the text.
self.all_footnotes = {
str(footnote.uuid): footnote for footnote in page.footnotes.all()
}

# Patch the page to track the footnotes that are actually referenced in the text, so that they can be rendered
# in footnotes.html
if not hasattr(page, "footnotes_list"):
page.footnotes_list = []

def replace_tag(match):
footnote_uuid = match.group(1)
try:
index = self.process_footnote(match.group(1), page)
except (KeyError, ValidationError):
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't see anything that would raise a ValidationError, so I removed it.

footnote = self.attach_footnote_to_page(footnote_uuid, page)
except KeyError:
return ""
else:
return self.render_footnote_tag(index)
# Add 1 to the footnote index as footnotes are rendered in footnotes.html using `{{ forloop.counter }}`
# which is 1-based.
footnote_index = page.footnotes_list.index(footnote) + 1
reference_index = footnote.references[-1]
# Supplying both indexes allows for unique id values to be generated in the HTML. E.g., the first
# reference to the first footnote will have `id="footnote-source-1-1"`, and the second reference to the
# first footnote will have `id="footnote-source-1-2"`, etc.
return self.render_footnote_tag(footnote_index, reference_index)

# note: we return safe html
return mark_safe(FIND_FOOTNOTE_TAG.sub(replace_tag, html)) # noqa: S308

def render(self, value, context=None):
if not self.get_template(value=value, context=context):
return self.render_basic(value, context=context)

html = super().render(value, context=context)
return self.replace_footnote_tags(value, html, context=context)

def render_basic(self, value, context=None):
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I removed render_basic because super.render() will already return this, and at the end of the day, all that is happening is regex substitutions on the output, which is handled in render() above.

html = super().render_basic(value, context)
def attach_footnote_to_page(self, footnote_uuid: str, page: Page) -> Footnote:
"""Finds the Footnote object matching `footnote_uuid`, then modifies it to track how many times it has been
referenced, and attaches it to the `page` so the footnote can be rendered in the page template.
"""
# Fetch the unmodified Footnote
footnote = self.all_footnotes[footnote_uuid]

return self.replace_footnote_tags(value, html, context=context)

def process_footnote(self, footnote_id, page):
footnote = self.footnotes[footnote_id]
# If this is the first time the Footnote has been referenced, modify it to track references before appending it
# to the page
if footnote not in page.footnotes_list:
footnote.references = [1]
page.footnotes_list.append(footnote)
# Add 1 to the index as footnotes are indexed starting at 1 not 0.
return page.footnotes_list.index(footnote) + 1
else:
# If this Footnote has been processed by a previous reference, fetch the modified Footnote from the page and
# update its reference tracking
footnote_index = page.footnotes_list.index(footnote)
footnote = page.footnotes_list[footnote_index]
# Update the references e.g., [1, 2]
footnote.references.append(footnote.references[-1] + 1)
# Update the page with the updated footnote
page.footnotes_list[footnote_index] = footnote
return footnote
Original file line number Diff line number Diff line change
@@ -1 +1 @@
<a href="#footnote-{{ index }}" id="footnote-source-{{ index }}"><sup>[{{ index }}]</sup></a>
<a href="#footnote-{{ index }}" id="footnote-source-{{ index }}-{{ reference_index }}"><sup>[{{ index }}]</sup></a>
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,27 @@ <h2 id="footnote-label">
</h2>
<ol>
{% for footnote in page.footnotes_list %}
<li id="footnote-{{ forloop.counter }}">
[{{ forloop.counter }}] {{ footnote.text|richtext }}
<a href="#footnote-source-{{ forloop.counter }}" aria-label="{% translate "Back to content" %}">↩</a>
{% with footnote_index=forloop.counter %}
<li id="footnote-{{ footnote_index }}">
{% if footnote.references|length == 1 %}
{# If there is only a single reference, link the return icon back to it #}
<a href="#footnote-source-{{ footnote_index }}-{{ footnote.references.0 }}" aria-label={% translate "Back to content" %}>
</a>
{% else %}
{% for reference_index in footnote.references %}
{# If there are multiple references, generate unique links per reference #}
<a href="#footnote-source-{{ footnote_index }}-{{ reference_index }}" aria-label={% translate "Back to content" %}>
<sup>{# Display a 1-indexed counter for each of the references to this footnote #}
{{ forloop.counter }}
</sup>
</a>
{% endfor %}
{% endif %}
{{ footnote.text|richtext }}
</li>
{% endwith %}
{% endfor %}
</ol>
</div>
Expand Down