Skip to content
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

Allow multiple references to the same footnote #40

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
59 changes: 55 additions & 4 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 @@ -103,13 +131,36 @@ def test_block_replace_footnote_render_basic(self):
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>'
result = (
'<p>This is a paragraph with a footnote. <a href="#footnote-1" id="footnote-source-1-0"><sup>[1]</sup></a>'
"</p>"
)
self.assertEqual(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("/"))
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-0"><sup>[1]</sup></a>'
"</p>"
)
self.assertEqual(out, result)

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-0"><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-1"><sup>[1]</sup></a></p>'
)
self.assertEqual(out, result)
8 changes: 4 additions & 4 deletions tests/test/test_functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,21 +76,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-0"})
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-0"', 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-0"', 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
19 changes: 16 additions & 3 deletions wagtail_footnotes/blocks.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import re

from collections import defaultdict

from django.core.exceptions import ValidationError
from django.utils.safestring import mark_safe
from wagtail.blocks import RichTextBlock
Expand All @@ -24,6 +26,7 @@ def __init__(self, **kwargs):
self.features = []
if "footnotes" not in self.features:
self.features.append("footnotes")
self.footnotes = {}

def replace_footnote_tags(self, value, html, context=None):
if context is None:
Expand All @@ -37,17 +40,28 @@ def replace_footnote_tags(self, value, html, context=None):
page = new_context["page"]
if not hasattr(page, "footnotes_list"):
page.footnotes_list = []
Copy link
Member

Choose a reason for hiding this comment

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

I think we can do away with footnotes_list in favour of the new footnotes_references.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

These are two different things. footnotes_list is the list of the actual Footnote objects to be rendered at the bottom of the rendered page, and footnotes_references is a dict that maps a Footnote's UUID to a list of all of the references found in the rich text blocks, so that jump links back to each individual reference can be rendered.

I didn't have any better idea of how to make the Footnote objects aware of the one or more references contained in the rich text blocks. This is why I made the goofy template tag so I could at least do dict lookups using the UUID in the template to fetch the references.

I'm working on getting this rebased on main now that the custom template PR was merged.

Copy link
Member

Choose a reason for hiding this comment

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

Right, that makes sense. I think some additional comments would be helpful then, and perhaps some type hinting, then there will be no ambiguity. Thank you

if not hasattr(page, "footnotes_references"):
page.footnotes_references = defaultdict(list)
self.footnotes = {
str(footnote.uuid): footnote for footnote in page.footnotes.all()
}

def replace_tag(match):
footnote_uuid = match.group(1)
try:
index = self.process_footnote(match.group(1), page)
index = self.process_footnote(footnote_uuid, page)
except (KeyError, ValidationError):
return ""
else:
return f'<a href="#footnote-{index}" id="footnote-source-{index}"><sup>[{index}]</sup></a>'
# Generate a unique html id for each link in the content to this footnote since the same footnote may be
# referenced multiple times in the page content. For the first reference to the first footnote, it will
# be "footnote-source-1-0" (the index for the footnote is 1-based but the index for the links are
# 0-based) and if it's the second link to the first footnote, it will be "footnote-source-1-1", etc.
# This ensures the ids are unique throughout the page and allows for the template to generate links from
# the footnote back up to the distinct references in the content.
link_id = f"footnote-source-{index}-{len(page.footnotes_references[footnote_uuid])}"
Copy link
Member

Choose a reason for hiding this comment

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

suggestion: keep indexes consistent. for regular users 1-1, 1-2 etc make more sense than 1-0. 1-1

page.footnotes_references[footnote_uuid].append(link_id)
return f'<a href="#footnote-{index}" id="{link_id}"><sup>[{index}]</sup></a>'

# note: we return safe html
return mark_safe(FIND_FOOTNOTE_TAG.sub(replace_tag, html)) # noqa: S308
Expand All @@ -61,7 +75,6 @@ def render(self, value, context=None):

def render_basic(self, value, context=None):
html = super().render_basic(value, context)

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

def process_footnote(self, footnote_id, page):
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{% load wagtailcore_tags %}
{% load wagtailfootnotes_tags %}

{% if page.footnotes_list %}
<div class="footnotes" id="footnotes">
Expand All @@ -8,8 +9,23 @@ <h2 id="footnote-label">
<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="Back to content">↩</a>
{% with reference_ids=page|get_reference_ids:footnote.uuid num=reference_ids|length %}
{% if num == 1 %}{# If there is only a single reference, simply link the return icon back to it #}
<a href="#{{ reference_ids.0 }}" aria-label="Back to content">
</a>
{% else %}
{% for reference_id in reference_ids %}
<a href="#{{ reference_id }}" aria-label="Back to content">
<sup>{# Display a 1-indexed counter for each of the references to this footnote #}
{{ forloop.counter }}
</sup>
</a>
{% endfor %}
{% endif %}
{% endwith %}
{{ footnote.text|richtext }}
</li>
{% endfor %}
</ol>
Expand Down
Empty file.
15 changes: 15 additions & 0 deletions wagtail_footnotes/templatetags/wagtailfootnotes_tags.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from django import template


register = template.Library()


@register.filter
def get_reference_ids(value, footnote_uuid):
"""This takes the current `footnote_uuid` and returns the list of references in the page content to that footnote.
This template tag is only necessary because it is not possible to do dictionary lookups using variables as keys in
Django templates.
"""
if hasattr(value, "footnotes_references"):
return value.footnotes_references.get(footnote_uuid, [])
return []
Copy link
Member

@zerolab zerolab Apr 15, 2024

Choose a reason for hiding this comment

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

I am not sure we need this. if we drop footnotes_list, we can update the template to check for page.footnotes_references and tweak the loops accordingly