diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..69747db --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,56 @@ +name: Publish to PyPI + +on: + release: + types: [released, prereleased] + +permissions: + contents: read # to fetch code (actions/checkout) + +env: + PYTHON_LATEST: "3.11" + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - uses: actions/setup-python@v4 + with: + python-version: ${{env.PYTHON_LATEST}} + cache: "pip" + cache-dependency-path: "pyproject.toml" + + - name: โฌ‡๏ธ Install dependencies + run: | + python -Im pip install flit + python -Im flit install --symlink + + - name: ๐Ÿ—๏ธ Build + run: python -Im flit build + + - uses: actions/upload-artifact@v3 + with: + path: ./dist + + # https://docs.pypi.org/trusted-publishers/using-a-publisher/ + pypi-publish: + needs: build + environment: 'release' + + name: โฌ†๏ธ Upload release to PyPI + runs-on: ubuntu-latest + permissions: + # Mandatory for trusted publishing + id-token: write + steps: + - uses: actions/download-artifact@v3 + + - name: ๐Ÿš€ Publish package distributions to PyPI + uses: pypa/gh-action-pypi-publish@release/v1 + with: + packages-dir: artifact/ + print-hash: true diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..260738f --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,101 @@ +name: CI + +on: + push: + branches: + - main + - 'stable/**' + + pull_request: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read # to fetch code (actions/checkout) + +env: + FORCE_COLOR: "1" # Make tools pretty. + TOX_TESTENV_PASSENV: FORCE_COLOR + PIP_DISABLE_PIP_VERSION_CHECK: "1" + PIP_NO_PYTHON_VERSION_WARNING: "1" + PYTHON_LATEST: "3.11" + + +jobs: + + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + - uses: actions/setup-python@v4 + with: + python-version: ${{env.PYTHON_LATEST}} + - uses: pre-commit/action@v3.0.0 + + tests: + runs-on: ubuntu-latest + needs: lint + strategy: + matrix: + python: ["3.8", "3.9", "3.10", "3.11", "3.12"] + + steps: + - uses: actions/checkout@v3 + - name: ๐Ÿ Setup Python ${{ matrix.python }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python }} + - name: ๐Ÿ“ฆ Install dependencies + run: | + python -Im pip install tox tox-gh-actions flit + python -Im flit install --symlink + + - name: ๐Ÿ—๏ธ Build wheel + run: python -Im flit build --format wheel + + - name: ๐Ÿงช Run tox targets for Python ${{ matrix.python-version }} + run: tox --installpkg ./dist/*.whl + + - name: โฌ†๏ธ Upload coverage data + uses: actions/upload-artifact@v3 + with: + name: coverage-data + path: .coverage.* + if-no-files-found: ignore + retention-days: 1 + + coverage: + runs-on: ubuntu-latest + needs: tests + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + - uses: actions/setup-python@v4 + with: + # Use latest Python, so it understands all syntax. + python-version: ${{env.PYTHON_LATEST}} + + - run: python -Im pip install --upgrade "coverage[toml]>=7.2,<8.0" + + - name: โฌ‡๏ธ Download coverage data + uses: actions/download-artifact@v3 + with: + name: coverage-data + + - name: ๏ผ‹ Combine coverage + run: | + python -Im coverage combine + python -Im coverage html --skip-covered --skip-empty + python -Im coverage report + echo "## Coverage summary" >> $GITHUB_STEP_SUMMARY + python -Im coverage report --format=markdown >> $GITHUB_STEP_SUMMARY + - name: ๐Ÿ“ˆ Upload HTML report if check failed. + uses: actions/upload-artifact@v3 + with: + name: html-report + path: htmlcov diff --git a/.gitignore b/.gitignore index b8315bc..515ba64 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,164 @@ -__pycache__ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class -dist/ +# C extensions +*.so + +# Distribution / packaging +.Python build/ -wagtail_footnotes.egg-info/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + + +# local +test_wagtail_footnotes.db diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..0073f0d --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,46 @@ +ci: + autofix_prs: false + +default_language_version: + python: python3.11 + +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.4.0 + hooks: + - id: check-added-large-files + - id: check-case-conflict + - id: check-json + - id: check-merge-conflict + - id: check-symlinks + - id: check-toml + - id: check-yaml + - id: end-of-file-fixer + - id: trailing-whitespace + - repo: https://github.com/psf/black + rev: 23.7.0 + hooks: + - id: black + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: 'v0.0.280' + hooks: + - id: ruff + - repo: https://github.com/adamchainz/blacken-docs + rev: 1.15.0 + hooks: + - id: blacken-docs + additional_dependencies: [black==23.7.0] + - repo: https://github.com/adamchainz/blacken-docs + rev: v1.12.1 + hooks: + - id: blacken-docs + additional_dependencies: + - black==23.7.0 + - repo: https://github.com/jackdewinter/pymarkdown + rev: v0.9.12 + hooks: + - id: pymarkdown + args: + - --disable-rules + - line-length + - scan diff --git a/CHANGELOG.md b/CHANGELOG.md index 39c0c64..0d57724 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,38 @@ ## Unreleased +- Add support for Wagtail 5.2 +- Add Wagtail 5.2 and Python 3.12 in test matrices @katdom13 + +## 0.10.0 + +- Add tests. (https://github.com/torchbox/wagtail-footnotes/pull/49) @nickmoreton + Includes tox 4, coverage configuration. +- Drop support for Python 3.7 and Wagtail < 4.1. (https://github.com/torchbox/wagtail-footnotes/pull/49) @nickmoreton +- Add the coverage report to the GitHub Actions summary. @zerolab +- Switch to using [ruff](https://beta.ruff.rs/docs/) for linting. (https://github.com/torchbox/wagtail-footnotes/pull/52) @zerolab +- Switched to using PyPI trusted publishing (https://github.com/torchbox/wagtail-footnotes/pull/53) @zerolab +- Switched to using [flit](https://flit.pypa.io/en/latest/) for packaging (https://github.com/torchbox/wagtail-footnotes/pull/54) @zerolab + +## 0.9.0 + +- Add support for Wagtail 4.0 +- Add GitHub Action to publish to PyPI on release by @zerolab in (https://github.com/torchbox/wagtail-footnotes/pull/45) + +## 0.8.0 + +- Add support for Wagtail 3.0 and drop support for all Wagtail versions before 2.15 +- Dropped support for all Django versions before 3.2 +- Removed support for Python 3.6 +- Fix previews (https://github.com/torchbox/wagtail-footnotes/pull/24) - [@jsma](https://github.com/jsma) + +## 0.7.0 + +- Clean up old step from README - It is no longer recommended to define footnotes in `WAGTAILADMIN_RICH_TEXT_EDITORS` +- Add `footnotes` rich text feature automatically +- Clean up `RichTextBlockWithFootnotes` +- Make Footnotes unique on `page` <-> `uuid` + ## 0.6.0 - Add `WAGTAIL_FOOTNOTES_TEXT_FEATURES` to add custom rich text features to footnote content @@ -33,4 +65,4 @@ ## 0.1.0 -- Initial release of the Wagtail Footnotes package \ No newline at end of file +- Initial release of the Wagtail Footnotes package diff --git a/LICENCE.txt b/LICENSE similarity index 100% rename from LICENCE.txt rename to LICENSE diff --git a/MANIFEST.in b/MANIFEST.in index b4959d9..ad5c4dd 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,5 +1,8 @@ -include LICENSE *.rst *.txt *.md +include LICENSE graft wagtail_footnotes -global-exclude __pycache__ +prune **/__pycache__ global-exclude *.py[co] global-exclude .DS_Store +recursive-include wagtail_footnotes/static/footnotes/js +recursive-include wagtail_footnotes/templates/wagtail_footnotes +prune **/tests diff --git a/README.md b/README.md index 7b38fc6..ae63f46 100644 --- a/README.md +++ b/README.md @@ -1,62 +1,120 @@ # Wagtail Footnotes +[![PyPI](https://img.shields.io/pypi/v/wagtail-footnotes.svg)](https://pypi.org/project/wagtail-footnotes/) +[![PyPI downloads](https://img.shields.io/pypi/dm/wagtail-footnotes.svg)](https://pypi.org/project/wagtail-footnotes/) +[![Build Status](https://github.com/torchbox/wagtail-footnotes/workflows/CI/badge.svg)](https://github.com/torchbox/wagtail-footnotes/actions) + Add footnotes functionality to your Wagtail project. ## Usage - - Add the app to `INSTALLED_APPS`: - ```python - INSTALLED_APPS = [ - ... - "wagtail_footnotes", - ... - ] - ``` - - Add the footnotes `urls.py` to your project's `urls.py`: - ```python - from wagtail_footnotes import urls as footnotes_urls - urlpatterns = [ - ... - path("footnotes/", include(footnotes_urls)), - ... - ] - ``` - Note: The URL has to be defined as above as it is currently hardcoded in the Javascript. - - Update your page models to show the footnotes field: - ```python - class InformationPage(BasePage): - ... - content_panels = [ - ... - InlinePanel("footnotes", label="Footnotes"), - ] - ``` - - Update your `RichTextBlock`s - - Add `"footnotes"` to the `features` arg for each `RichTextBlock` that you want to have this functionality - - You will also need to change any `RichTextBlock`s to `wagtail_footnotes.blocks.RichTextBlockWithFootnotes` - - You can add the footnotes to `RichTextBlock`s across the project by updating `WAGTAILADMIN_RICH_TEXT_EDITORS["default"]["OPTIONS"]["features"]`: - ```python - WAGTAILADMIN_RICH_TEXT_EDITORS = { - "default": { - "WIDGET": "wagtail.admin.rich_text.DraftailRichTextArea", - "OPTIONS": {"features": ["bold", "italic", "h3", "h4", "ol", "ul", "link", "footnotes"]}, - } - } - ``` - - Update your page templates to include `{% include "wagtail_footnotes/includes/footnotes.html" %}` - - Make and run migrations: - ``` - ./manage.py makemigrations - ./manage.py migrate - ``` + +- Add the app to `INSTALLED_APPS`: + +```python +INSTALLED_APPS = [ + # ... + "wagtail_footnotes", + # ... +] +``` + +- Add the footnotes `urls.py` to your project's `urls.py`: + +```python +from wagtail_footnotes import urls as footnotes_urls + +urlpatterns = [ + # ... + path("footnotes/", include(footnotes_urls)), + # ... +] +``` + +Note: The URL has to be defined as above as it is currently hardcoded in the Javascript. + +- Update your page models to show the footnotes field: + +```python +class InformationPage(BasePage): + # ... + content_panels = [ + # ... + InlinePanel("footnotes", label="Footnotes"), + ] +``` + +- Update your `RichTextBlock`s + - Add `"footnotes"` to the `features` arg for each `RichTextBlock` that you want to have this functionality + - You will also need to change any `RichTextBlock`s to `wagtail_footnotes.blocks.RichTextBlockWithFootnotes` +- Update your page templates to include `{% include "wagtail_footnotes/includes/footnotes.html" %}` + +Make and run migrations: + +```bash +./manage.py makemigrations +./manage.py migrate +``` ## Settings - - `WAGTAIL_FOOTNOTES_TEXT_FEATURES` - - Default: `["bold", "italic", "link"]` - - Use this to update a list of Rich Text features allowed in the footnote text. +- `WAGTAIL_FOOTNOTES_TEXT_FEATURES` + - Default: `["bold", "italic", "link"]` + - Use this to update a list of Rich Text features allowed in the footnote text. ## Common issues - - I click on the `Fn` button in the editor and it stops working - - This is likely because the URL in the JS does not match the URL of the footnotes view. Check the URL in `wagtail_footnotes/static/footnotes/js/footnotes.js` matches the URL you set. - - `NoneType` error when rendering page. - - Make sure you are rendering the field in the template using `{% include_block page.field_name %}` + +- I click on the `Fn` button in the editor and it stops working + - This is likely because the URL in the JS does not match the URL of the footnotes view. Check the URL in `wagtail_footnotes/static/footnotes/js/footnotes.js` matches the URL you set. +- `NoneType` error when rendering page. + - Make sure you are rendering the field in the template using `{% include_block page.field_name %}` + +## Contributing + +All contributions are welcome! + +### Install + +To make changes to this project, first clone this repository: + +```sh +git clone git@github.com:torchbox/wagtail-footnotes.git +cd wagtail-footnotes +``` + +With your preferred virtualenv activated, install testing dependencies: + +```sh +pip install -e '.[testing]' -U +``` + +### pre-commit + +Note that this project uses [pre-commit](https://github.com/pre-commit/pre-commit). To set up locally: + +```shell +$ pip install pre-commit +# initialize pre-commit +$ pre-commit install +# Optional, run all checks once for this, then the checks will run only on the changed files +$ pre-commit run --all-files +``` + +### How to run tests + +To run all tests in all environments: + +```sh +tox +``` + +To run tests for a specific environment: + +```shell +tox -e python3.11-django4.2-wagtail5.2 +``` + +To run a single test method in a specific environment: + +```shell +tox -e python3.11-django4.2-wagtail5.2 -- tests.test.test_blocks.TestBlocks.test_block_with_features +``` diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..01ff6f3 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,147 @@ +[project] +name = "wagtail-footnotes" +description = "Add footnotes to rich text in your Wagtail pages" +authors = [{name = "Cameron Lamb ", email = "hello@torchbox.com"}] +maintainers = [ + {name = "Kevin Howbrook", email="kevin.howbrook@torchbox.com"}, + {name = "Dan Braghis", email="dan.braghis@torchbox.com"} +] +readme = "README.md" +license = {file = "LICENSE"} +keywords = ["Wagtail", "Django", "footnotes", "rich text"] +classifiers = [ + "Development Status :: 4 - Beta", + "Environment :: Web Environment", + "Intended Audience :: Developers", + "Operating System :: OS Independent", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Framework :: Django", + "Framework :: Django :: 3", + "Framework :: Django :: 3.2", + "Framework :: Django :: 4", + "Framework :: Django :: 4.1", + "Framework :: Django :: 4.2", + "Framework :: Wagtail", + "Framework :: Wagtail :: 4", + "Framework :: Wagtail :: 5", +] + +dynamic = ["version"] # will read __version__ from wagtail_footnotes/__init__.py +requires-python = ">=3.8" +dependencies = [ + "Wagtail>=4.1", + "Django>=3.2", +] + +[project.optional-dependencies] +testing = [ + "pre-commit>=3.3.0,<4", + "tox>=4.6.4,<5", + "black==23.7.0", + "ruff==0.0.280", + "coverage[toml]>=7.2,<8.0", +] + +[project.urls] +Repository = "https://github.com/torchbox/wagtail-footnotes" +Changelog = "https://github.com/torchbox/wagtail-footnotes/blob/main/CHANGELOG.md" + + +[build-system] +requires = ["flit_core >=3.2,<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.module] +name = "wagtail_footnotes" + +[tool.flit.sdist] +exclude = [ + "tests", + "Makefile", + "docs", + ".*", + "*.json", + "*.ini", + "*.yml", + "CHANGELOG.md", + "testmanage.py", +] + +[tool.black] +line_length = 88 +target-version = ["py38"] + + +[tool.ruff] +target-version = "py38" + +extend-select = [ + "B", # flake8-bugbear + "C4", # flake8-comprehensions + "DJ", # flake8-django + "E", # pycodestyle errors + "F", # pyflakes + "I", # isort + "PGH", # pygrep-hooks + "S", # flake8-bandit + "SIM", # flake8-simplify + "W", # pycodestyle warnings + "YTT", # flake8-2020 + "UP", # pyupgrade + "RUF100", # unused noqa +] + +# Never enforce `E501` (line length violations). +ignore = ["E501"] + +[tool.ruff.isort] +known-first-party = ["src"] +lines-between-types = 1 +lines-after-imports = 2 + + +[tool.coverage.run] +branch = true +concurrency = ["multiprocessing", "thread"] +parallel = true + +source = ["wagtail_footnotes"] +omit = ["**/migrations/*", "tests/*"] + +[tool.coverage.paths] +source = ["wagtail_footnotes", ".tox/py*/**/site-packages"] + +[tool.coverage.report] +show_missing = true +ignore_errors = true +skip_empty = true +skip_covered = true +exclude_lines = [ + # Have to re-enable the standard pragma + "pragma: no cover", + + # Don't complain about missing debug-only code: + "def __repr__", + "if self.debug", + + # Don't complain if tests don't hit defensive assertion code: + "raise AssertionError", + "raise NotImplementedError", + + # Don't complain if non-runnable code isn't run: + "if 0:", + "if __name__ == .__main__.:", + + # Don't complain about abstract methods, they aren't run: + "@(abc.)?abstractmethod", + + # Nor complain about type checking + "if TYPE_CHECKING:", +] diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 726f16b..0000000 --- a/setup.cfg +++ /dev/null @@ -1,25 +0,0 @@ -[metadata] -name = wagtail-footnotes -author = Cameron Lamb -author_email = cameron.lamb@torchbox.com -description = Add footnotes to rich text in your wagtail pages -version = 0.6.0 -url = https://github.com/torchbox/wagtail-footnotes -keywords = - wagtail - django -long_description = file:README.md -long_description_content_type = text/markdown -license_files = - LICENSE.txt - -[options] -python_requires = >= 3.6 -setup_requires = - setuptools >= 40.6 - pip >= 10 -include_package_data = true -packages = find: -install_requires = - Django>=2.2, <3.3 - wagtail>=2.5, <3 diff --git a/setup.py b/setup.py deleted file mode 100644 index 6068493..0000000 --- a/setup.py +++ /dev/null @@ -1,3 +0,0 @@ -from setuptools import setup - -setup() diff --git a/testmanage.py b/testmanage.py new file mode 100644 index 0000000..77f635c --- /dev/null +++ b/testmanage.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python + +import argparse +import os +import shutil +import sys +import warnings + +from django.core.management import execute_from_command_line + + +os.environ["DJANGO_SETTINGS_MODULE"] = "tests.settings" + + +def make_parser(): + parser = argparse.ArgumentParser() + parser.add_argument( + "--deprecation", + choices=["all", "pending", "imminent", "none"], + default="imminent", + ) + return parser + + +def parse_args(args=None): + return make_parser().parse_known_args(args) + + +def runtests(): + args, rest = parse_args() + + only_wagtail = r"^wagtail(\.|$)" + if args.deprecation == "all": + # Show all deprecation warnings from all packages + warnings.simplefilter("default", DeprecationWarning) + warnings.simplefilter("default", PendingDeprecationWarning) + elif args.deprecation == "pending": + # Show all deprecation warnings from wagtail + warnings.filterwarnings( + "default", category=DeprecationWarning, module=only_wagtail + ) + warnings.filterwarnings( + "default", category=PendingDeprecationWarning, module=only_wagtail + ) + elif args.deprecation == "imminent": + # Show only imminent deprecation warnings from wagtail + warnings.filterwarnings( + "default", category=DeprecationWarning, module=only_wagtail + ) + elif args.deprecation == "none": + # Deprecation warnings are ignored by default + pass + + argv = [sys.argv[0]] + rest + + try: + execute_from_command_line(argv) + finally: + from wagtail.test.settings import MEDIA_ROOT, STATIC_ROOT + + shutil.rmtree(STATIC_ROOT, ignore_errors=True) + shutil.rmtree(MEDIA_ROOT, ignore_errors=True) + + +if __name__ == "__main__": + runtests() diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/apps.py b/tests/apps.py new file mode 100644 index 0000000..5996104 --- /dev/null +++ b/tests/apps.py @@ -0,0 +1,7 @@ +from django.apps import AppConfig + + +class WagtailFootnotesTestAppConfig(AppConfig): + label = "tests" + name = "tests" + verbose_name = "Wagtail Footnotes tests" diff --git a/tests/blocks.py b/tests/blocks.py new file mode 100644 index 0000000..54927f8 --- /dev/null +++ b/tests/blocks.py @@ -0,0 +1,7 @@ +from wagtail import blocks + +from wagtail_footnotes.blocks import RichTextBlockWithFootnotes + + +class CustomBlock(blocks.StreamBlock): + paragraph = RichTextBlockWithFootnotes(features=["footnotes"]) diff --git a/tests/migrations/0001_initial.py b/tests/migrations/0001_initial.py new file mode 100644 index 0000000..8693d50 --- /dev/null +++ b/tests/migrations/0001_initial.py @@ -0,0 +1,53 @@ +# Generated by Django 4.1.2 on 2022-10-14 21:06 + +import django.db.models.deletion +import wagtail.fields as wagtail_fields + +from django.db import migrations, models + +import wagtail_footnotes.blocks + + +class Migration(migrations.Migration): + initial = True + + dependencies = [ + ("wagtailcore", "0040_page_draft_title"), + ] + + operations = [ + migrations.CreateModel( + name="TestPageStreamField", + fields=[ + ( + "page_ptr", + models.OneToOneField( + auto_created=True, + on_delete=django.db.models.deletion.CASCADE, + parent_link=True, + primary_key=True, + serialize=False, + to="wagtailcore.page", + ), + ), + ( + "body", + wagtail_fields.StreamField( + [ + ( + "paragraph", + wagtail_footnotes.blocks.RichTextBlockWithFootnotes( + features=["footnotes"] + ), + ) + ], + use_json_field=True, + ), + ), + ], + options={ + "abstract": False, + }, + bases=("wagtailcore.page",), + ), + ] diff --git a/tests/migrations/__init__.py b/tests/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/models.py b/tests/models.py new file mode 100644 index 0000000..827e53c --- /dev/null +++ b/tests/models.py @@ -0,0 +1,16 @@ +from wagtail.admin.panels import FieldPanel, InlinePanel +from wagtail.fields import StreamField +from wagtail.models import Page + +from .blocks import CustomBlock + + +class TestPageStreamField(Page): + template = "test/test_page_stream_field.html" + + body = StreamField(CustomBlock(), use_json_field=True) + + content_panels = Page.content_panels + [ + FieldPanel("body"), + InlinePanel("footnotes", label="Footnotes"), + ] diff --git a/tests/settings.py b/tests/settings.py new file mode 100644 index 0000000..f51d490 --- /dev/null +++ b/tests/settings.py @@ -0,0 +1,138 @@ +""" +Django settings for temp project. + +For more information on this file, see +https://docs.djangoproject.com/en/stable/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/stable/ref/settings/ +""" + +import os + + +# Build paths inside the project like this: os.path.join(PROJECT_DIR, ...) +PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) +BASE_DIR = os.path.dirname(PROJECT_DIR) + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/stable/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = "not-a-secret!" # noqa: S105 + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = ["localhost", "testserver"] + + +# Application definition + +INSTALLED_APPS = [ + "wagtail_footnotes", + "tests", + "wagtail.users", + "wagtail.snippets", + "wagtail.documents", + "wagtail.images", + "wagtail.search", + "wagtail.admin", + "wagtail.contrib.modeladmin", + "wagtail.sites", + "wagtail", + "taggit", + "rest_framework", + "django.contrib.admin", + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.staticfiles", +] + +MIDDLEWARE = [ + "django.middleware.security.SecurityMiddleware", + "django.contrib.sessions.middleware.SessionMiddleware", + "django.middleware.common.CommonMiddleware", + "django.middleware.csrf.CsrfViewMiddleware", + "django.contrib.auth.middleware.AuthenticationMiddleware", + "django.contrib.messages.middleware.MessageMiddleware", + "django.middleware.clickjacking.XFrameOptionsMiddleware", + "wagtail.contrib.redirects.middleware.RedirectMiddleware", +] + +ROOT_URLCONF = "tests.urls" + +TEMPLATES = [ + { + "BACKEND": "django.template.backends.django.DjangoTemplates", + "DIRS": [], + "APP_DIRS": True, + "OPTIONS": { + "context_processors": [ + "django.template.context_processors.debug", + "django.template.context_processors.request", + "django.contrib.auth.context_processors.auth", + "django.contrib.messages.context_processors.messages", + ] + }, + } +] + +# don't use the intentionally slow default password hasher +PASSWORD_HASHERS = ("django.contrib.auth.hashers.MD5PasswordHasher",) + +# Database +# https://docs.djangoproject.com/en/stable/ref/settings/#databases + +DATABASES = { + "default": { + "ENGINE": "django.db.backends.sqlite3", + "NAME": os.path.join(BASE_DIR, "test_wagtail_footnotes.db"), + } +} + + +# Password validation +# https://docs.djangoproject.com/en/stable/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator" + }, + {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"}, + {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"}, + {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"}, +] + + +# Internationalization +# https://docs.djangoproject.com/en/stable/topics/i18n/ + +USE_TZ = True + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/stable/howto/static-files/ + +STATICFILES_FINDERS = [ + "django.contrib.staticfiles.finders.FileSystemFinder", + "django.contrib.staticfiles.finders.AppDirectoriesFinder", +] + +STATIC_ROOT = os.path.join(BASE_DIR, "test-static") +STATIC_URL = "/static/" + +MEDIA_ROOT = os.path.join(BASE_DIR, "test-media") + +WAGTAIL_SITE_NAME = "Wagtail Footnotes test site" + +# Search +# https://docs.wagtail.org/en/stable/topics/search/backends.html +WAGTAILSEARCH_BACKENDS = { + "default": { + "BACKEND": "wagtail.search.backends.database", + } +} + +WAGTAILADMIN_BASE_URL = "http://localhost:8000" diff --git a/tests/templates/base.html b/tests/templates/base.html new file mode 100644 index 0000000..f0a8cf7 --- /dev/null +++ b/tests/templates/base.html @@ -0,0 +1,17 @@ +{% load wagtailuserbar %} + + + + + + + + Wagtail Footnotes + + + + {% wagtailuserbar %} + {% block content %}{% endblock %} + + + diff --git a/tests/templates/test/test_page_stream_field.html b/tests/templates/test/test_page_stream_field.html new file mode 100644 index 0000000..f0a5241 --- /dev/null +++ b/tests/templates/test/test_page_stream_field.html @@ -0,0 +1,12 @@ +{% extends "base.html" %} +{% load wagtailcore_tags %} + +{% block content %} + +

{{ page.title }}

+ +{% include_block page.body %} + +{% include "wagtail_footnotes/includes/footnotes.html" %} + +{% endblock content %} diff --git a/tests/test/__init__.py b/tests/test/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test/test_blocks.py b/tests/test/test_blocks.py new file mode 100644 index 0000000..ade57f0 --- /dev/null +++ b/tests/test/test_blocks.py @@ -0,0 +1,115 @@ +import json + +from django.test import TestCase +from wagtail import blocks +from wagtail.fields import StreamBlock +from wagtail.models import Page + +from wagtail_footnotes.blocks import RichTextBlockWithFootnotes +from wagtail_footnotes.models import Footnote + +from ..models import TestPageStreamField + + +class TestBlocks(TestCase): + def setUp(self): + home_page = Page.objects.get(title="Welcome to your new Wagtail site!") + + self.test_page_no_footnote = TestPageStreamField( + title="Test Page No Footnote", + slug="test-page-no-footnote", + body=json.dumps( + [ + { + "type": "paragraph", + "value": "

This is a paragraph with no footnote.

", + } + ] + ), + ) + home_page.add_child(instance=self.test_page_no_footnote) + self.test_page_no_footnote.save_revision().publish() + + uuid = "f291a4b7-5ac5-4030-b341-b1993efb2ad2" + self.test_page_with_footnote = TestPageStreamField( + title="Test Page With Footnote", + slug="test-page-with-footnote", + body=json.dumps( + [ + { + "type": "paragraph", + "value": f'

This is a paragraph with a footnote. 1

', + }, + ] + ), + ) + home_page.add_child(instance=self.test_page_with_footnote) + self.test_page_with_footnote.save_revision().publish() + self.footnote = Footnote.objects.create( + page=self.test_page_with_footnote, + uuid=uuid, + text="This is a footnote", + ) + + def test_block_with_no_features(self): + block = RichTextBlockWithFootnotes() + self.assertIsInstance(block, blocks.RichTextBlock) + self.assertEqual(block.features, ["footnotes"]) + + def test_block_with_features(self): + block = RichTextBlockWithFootnotes(features=["h1", "h2"]) + self.assertIsInstance(block, blocks.RichTextBlock) + self.assertEqual(block.features, ["h1", "h2", "footnotes"]) + + def test_block_with_stream_block(self): + block = StreamBlock([("rich_text", RichTextBlockWithFootnotes())]) + self.assertIsInstance(block, StreamBlock) + self.assertEqual(block.child_blocks["rich_text"].features, ["footnotes"]) + + def test_block_with_stream_block_with_features(self): + block = StreamBlock( + [("rich_text", RichTextBlockWithFootnotes(features=["h1", "h2"]))] + ) + self.assertIsInstance(block, StreamBlock) + self.assertEqual( + block.child_blocks["rich_text"].features, ["h1", "h2", "footnotes"] + ) + + def test_block_with_struct_block(self): + class StructBlock(blocks.StructBlock): + rich_text = RichTextBlockWithFootnotes() + + block = StructBlock() + self.assertIsInstance(block, blocks.StructBlock) + self.assertEqual(block.child_blocks["rich_text"].features, ["footnotes"]) + + def test_block_with_struct_block_with_features(self): + class StructBlock(blocks.StructBlock): + rich_text = RichTextBlockWithFootnotes(features=["h1", "h2"]) + + block = StructBlock() + self.assertIsInstance(block, blocks.StructBlock) + self.assertEqual( + block.child_blocks["rich_text"].features, ["h1", "h2", "footnotes"] + ) + + def test_block_replace_footnote_tags(self): + block = RichTextBlockWithFootnotes() + html = block.replace_footnote_tags(None, "foo") + self.assertEqual(html, "foo") + + def test_block_replace_footnote_render_basic(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 = '

This is a paragraph with a footnote. [1]

' + 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 = '

This is a paragraph with a footnote. [1]

' + self.assertEqual(out, result) diff --git a/tests/test/test_fields.py b/tests/test/test_fields.py new file mode 100644 index 0000000..20b7fa2 --- /dev/null +++ b/tests/test/test_fields.py @@ -0,0 +1,14 @@ +from django.test import TestCase + +from wagtail_footnotes.fields import CustomUUIDField + + +class TestFields(TestCase): + def test_custom_uuid_field(self): + uuid_field = CustomUUIDField() + self.assertEqual( + uuid_field.from_db_value( + "12345678-1234-5678-1234-567812345678", None, None + ), + "12345678-1234-5678-1234-567812345678", + ) diff --git a/tests/test/test_functional.py b/tests/test/test_functional.py new file mode 100644 index 0000000..9c25588 --- /dev/null +++ b/tests/test/test_functional.py @@ -0,0 +1,110 @@ +import json + +from bs4 import BeautifulSoup as bs4 +from django.contrib.auth.models import User +from django.test import TestCase +from wagtail.models import Page + +from wagtail_footnotes.models import Footnote + +from ..models import TestPageStreamField + + +class TestFunctional(TestCase): + def setUp(self): + home_page = Page.objects.get(title="Welcome to your new Wagtail site!") + + self.test_page_no_footnote = TestPageStreamField( + title="Test Page No Footnote", + slug="test-page-no-footnote", + body=json.dumps( + [ + { + "type": "paragraph", + "value": "

This is a paragraph with no footnote.

", + } + ] + ), + ) + home_page.add_child(instance=self.test_page_no_footnote) + self.test_page_no_footnote.save_revision().publish() + + uuid = "f291a4b7-5ac5-4030-b341-b1993efb2ad2" + self.test_page_with_footnote = TestPageStreamField( + title="Test Page With Footnote", + slug="test-page-with-footnote", + body=json.dumps( + [ + { + "type": "paragraph", + "value": f'

This is a paragraph with a footnote. 1

', + }, + ] + ), + ) + home_page.add_child(instance=self.test_page_with_footnote) + self.test_page_with_footnote.save_revision().publish() + self.footnote = Footnote.objects.create( + page=self.test_page_with_footnote, + uuid=uuid, + text="This is a footnote", + ) + + self.admin_user = User.objects.create_superuser( + username="admin", email="", password="password" # noqa: S106 + ) + + def test_no_footnote(self): + response = self.client.get("/test-page-no-footnote/") + self.assertEqual(response.status_code, 200) + + soup = bs4(response.content, "html.parser") + + # test that these html tags are not present + self.assertEqual(soup.find("sup"), None) + self.assertEqual(soup.find("a"), None) + self.assertEqual(soup.find("div", {"class": "footnotes"}), None) + self.assertEqual(soup.find("ol"), None) + self.assertEqual(soup.find("li"), None) + self.assertEqual(soup.find("p").text, "This is a paragraph with no footnote.") + + def test_with_footnote(self): + response = self.client.get("/test-page-with-footnote/") + self.assertEqual(response.status_code, 200) + + soup = bs4(response.content, "html.parser") + + # 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"}) + self.assertTrue(source_anchor) + + source_anchor_string = str(source_anchor) + self.assertIn("[1]", source_anchor_string) + self.assertIn('href="#footnote-1"', source_anchor_string) + self.assertIn('id="footnote-source-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) + + def test_edit_page_with_footnote(self): + self.client.force_login(self.admin_user) + + response = self.client.get( + f"/admin/pages/{self.test_page_with_footnote.id}/edit/" + ) + + data_block = ( + response.context["form"] + .fields["body"] + .get_bound_field(response.context["form"], "body") + ) + soup = bs4(str(data_block), "html.parser") + + # Test that the footnote uuid is present in the html + self.assertIn(self.footnote.uuid, str(soup)) diff --git a/tests/test/test_hooks.py b/tests/test/test_hooks.py new file mode 100644 index 0000000..cbc2ce2 --- /dev/null +++ b/tests/test/test_hooks.py @@ -0,0 +1,25 @@ +from django.test import TestCase + +from wagtail_footnotes.wagtail_hooks import ( + FootnotesEntityElementHandler, + footnotes_entity_decorator, +) + + +class TestHooks(TestCase): + def test_footnotes_entity_decorator(self): + props = {"footnote": "1", "children": ""} + dom = footnotes_entity_decorator(props) + self.assertEqual(dom.type, "footnote") + self.assertEqual(dom.children, []) + + def test_footnotes_entity_decorator_with_children(self): + props = {"footnote": "1", "children": "This is a footnote"} + dom = footnotes_entity_decorator(props) + self.assertEqual(dom.type, "footnote") + self.assertEqual(dom.children, ["This is a footnote"]) + + def test_footnotes_entity_element_handler(self): + attrs = {"id": "1ahyt67", "footnote": "1"} + element = FootnotesEntityElementHandler(attrs) + self.assertEqual(element.get_attribute_data(attrs), {"footnote": "1ahyt67"}) diff --git a/tests/test/test_widgets.py b/tests/test/test_widgets.py new file mode 100644 index 0000000..ce2b163 --- /dev/null +++ b/tests/test/test_widgets.py @@ -0,0 +1,18 @@ +from django import forms +from django.test import TestCase + +from wagtail_footnotes.widgets import ReadonlyUUIDInput + + +class TestWidgets(TestCase): + def test_read_only_uuid_input(self): + form = forms.Form() + form.fields["uuid"] = forms.CharField(widget=ReadonlyUUIDInput) + self.assertInHTML( + '', + form.as_p(), + ) + self.assertInHTML( + '', + form.as_p(), + ) diff --git a/tests/urls.py b/tests/urls.py new file mode 100644 index 0000000..2417fa8 --- /dev/null +++ b/tests/urls.py @@ -0,0 +1,16 @@ +from django.contrib import admin +from django.urls import include, path +from wagtail import urls as wagtail_urls +from wagtail.admin import urls as wagtailadmin_urls +from wagtail.documents import urls as wagtaildocs_urls + +from wagtail_footnotes import urls as footnotes_urls + + +urlpatterns = [ + path("django-admin/", admin.site.urls), + path("admin/", include(wagtailadmin_urls)), + path("documents/", include(wagtaildocs_urls)), + path("footnotes/", include(footnotes_urls)), + path("", include(wagtail_urls)), +] diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..c2fd6d5 --- /dev/null +++ b/tox.ini @@ -0,0 +1,47 @@ +[tox] +min_version = 4.0 + +envlist = + python{3.8,3.9,3.10}-django{3.2}-wagtail{4.1,5.1,5.2} + python{3.9,3.10,3.11}-django{4.1}-wagtail{4.1,5.1,5.2} + python{3.10,3.11}-django{4.2}-wagtail{5.1,5.2} + python3.12-django4.2-wagtail5.2 + +[gh-actions] +python = + 3.8: python3.8 + 3.9: python3.9 + 3.10: python3.10 + 3.11: python3.11 + 3.12: python3.12 + + +[testenv] +package = wheel +wheel_build_env = .pkg + +pass_env = + FORCE_COLOR + NO_COLOR + +deps = + coverage[toml]>=7.2,<8.0 + + django3.2: Django>=3.2,<4.0 + django4.1: Django>=4.1,<4.2 + django4.2: Django>=4.2,<4.3 + + wagtail4.1: wagtail>=4.1,<4.2 + wagtail5.1: wagtail>=5.1,<5.2 + wagtail5.2: wagtail>=5.2,<5.3 + + +install_command = python -Im pip install -U {opts} {packages} +commands = + python -Im coverage run testmanage.py test --deprecation all {posargs: -v 2} + + +[testenv:coverage-report] +commands = + python -Im coverage combine + python -Im coverage report -m diff --git a/wagtail_footnotes/__init__.py b/wagtail_footnotes/__init__.py index e69de29..6c0877e 100644 --- a/wagtail_footnotes/__init__.py +++ b/wagtail_footnotes/__init__.py @@ -0,0 +1,3 @@ +VERSION = (0, 10, 0) + +__version__ = ".".join(map(str, VERSION)) diff --git a/wagtail_footnotes/apps.py b/wagtail_footnotes/apps.py new file mode 100644 index 0000000..7746eb5 --- /dev/null +++ b/wagtail_footnotes/apps.py @@ -0,0 +1,8 @@ +from django.apps import AppConfig + + +class WagtailFootnotesAppConfig(AppConfig): + label = "wagtail_footnotes" + name = "wagtail_footnotes" + verbose_name = "Wagtail Footnotes" + default_auto_field = "django.db.models.AutoField" diff --git a/wagtail_footnotes/blocks.py b/wagtail_footnotes/blocks.py index c2152a5..4157de1 100644 --- a/wagtail_footnotes/blocks.py +++ b/wagtail_footnotes/blocks.py @@ -2,7 +2,10 @@ from django.core.exceptions import ValidationError from django.utils.safestring import mark_safe -from wagtail.core.blocks import RichTextBlock +from wagtail import VERSION as WAGTAIL_VERSION +from wagtail.blocks import RichTextBlock +from wagtail.models import Page + FIND_FOOTNOTE_TAG = re.compile(r'.*?') @@ -16,36 +19,57 @@ class RichTextBlockWithFootnotes(RichTextBlock): final template context. """ - def replace_footnote_tags(self, html, context=None): + def __init__(self, **kwargs): + super().__init__(**kwargs) + if not self.features: + self.features = [] + if "footnotes" not in self.features: + self.features.append("footnotes") + + 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): + return html + + page = new_context["page"] + if not hasattr(page, "footnotes_list"): + page.footnotes_list = [] + self.footnotes = { + str(footnote.uuid): footnote for footnote in page.footnotes.all() + } + def replace_tag(match): try: - index = self.process_footnote(match.group(1), context["page"]) + index = self.process_footnote(match.group(1), page) except (KeyError, ValidationError): return "" else: return f'[{index}]' - return mark_safe(FIND_FOOTNOTE_TAG.sub(replace_tag, html)) + + # 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(context=context): + kwargs = {"value": value} if WAGTAIL_VERSION >= (5, 2) else {} + + if not self.get_template(context=context, **kwargs): return self.render_basic(value, context=context) html = super().render(value, context=context) - return self.replace_footnote_tags(html, context=context) + return self.replace_footnote_tags(value, html, context=context) def render_basic(self, value, context=None): html = super().render_basic(value, context) - return self.replace_footnote_tags(html, context=context) + return self.replace_footnote_tags(value, html, context=context) def process_footnote(self, footnote_id, page): - footnotes = self.get_footnotes(page) - footnote = page.footnotes.get(uuid=footnote_id) - if footnote not in footnotes: - footnotes.append(footnote) - return footnotes.index(footnote) + 1 - - def get_footnotes(self, page): - if not hasattr(page, "footnotes_list"): - page.footnotes_list = [] - return page.footnotes_list + footnote = self.footnotes[footnote_id] + if footnote not in page.footnotes_list: + 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 diff --git a/wagtail_footnotes/fields.py b/wagtail_footnotes/fields.py index 9910d2a..de0bf90 100644 --- a/wagtail_footnotes/fields.py +++ b/wagtail_footnotes/fields.py @@ -2,7 +2,7 @@ class CustomUUIDField(UUIDField): - """ Returns database value as a string, so that dashes are preserved. """ + """Returns database value as a string, so that dashes are preserved.""" def from_db_value(self, value, expression, connection, context=None): return str(value) diff --git a/wagtail_footnotes/migrations/0001_initial.py b/wagtail_footnotes/migrations/0001_initial.py index 7384ad4..ff64154 100644 --- a/wagtail_footnotes/migrations/0001_initial.py +++ b/wagtail_footnotes/migrations/0001_initial.py @@ -2,13 +2,14 @@ import django.db.models.deletion import modelcluster.fields -import wagtail.core.fields -import wagtail_footnotes.fields +import wagtail.fields as wagtail_fields + from django.db import migrations, models +import wagtail_footnotes.fields -class Migration(migrations.Migration): +class Migration(migrations.Migration): initial = True dependencies = [ @@ -36,7 +37,7 @@ class Migration(migrations.Migration): verbose_name="ID", ), ), - ("text", wagtail.core.fields.RichTextField()), + ("text", wagtail_fields.RichTextField()), ( "page", modelcluster.fields.ParentalKey( diff --git a/wagtail_footnotes/migrations/0003_footnote_bootstrap_migration_2.py b/wagtail_footnotes/migrations/0003_footnote_bootstrap_migration_2.py index 4fa6503..fd3ff1c 100644 --- a/wagtail_footnotes/migrations/0003_footnote_bootstrap_migration_2.py +++ b/wagtail_footnotes/migrations/0003_footnote_bootstrap_migration_2.py @@ -1,15 +1,14 @@ # Generated by Django 3.1.11 on 2021-06-21 18:22 from django.db import migrations -from wagtail.core.models import BootstrapTranslatableModel +from wagtail.models import BootstrapTranslatableModel class Migration(migrations.Migration): - dependencies = [ - ('wagtail_footnotes', '0002_footnote_bootstrap_migration'), + ("wagtail_footnotes", "0002_footnote_bootstrap_migration"), ] operations = [ - BootstrapTranslatableModel('wagtail_footnotes.Footnote'), + BootstrapTranslatableModel("wagtail_footnotes.Footnote"), ] diff --git a/wagtail_footnotes/migrations/0005_alter_footnote_unique_together.py b/wagtail_footnotes/migrations/0005_alter_footnote_unique_together.py new file mode 100644 index 0000000..68dec39 --- /dev/null +++ b/wagtail_footnotes/migrations/0005_alter_footnote_unique_together.py @@ -0,0 +1,17 @@ +# Generated by Django 4.1.13 on 2024-01-16 17:31 + +from django.db import migrations + + +class Migration(migrations.Migration): + dependencies = [ + ("wagtailcore", "0078_referenceindex"), + ("wagtail_footnotes", "0004_footnote_translatable_mixin_migration"), + ] + + operations = [ + migrations.AlterUniqueTogether( + name="footnote", + unique_together={("translation_key", "locale"), ("page", "uuid")}, + ), + ] diff --git a/wagtail_footnotes/models.py b/wagtail_footnotes/models.py index 2d88b05..305af22 100644 --- a/wagtail_footnotes/models.py +++ b/wagtail_footnotes/models.py @@ -1,12 +1,13 @@ from django.conf import settings from django.db import models from modelcluster.fields import ParentalKey -from wagtail.admin.edit_handlers import FieldPanel, InlinePanel -from wagtail.core.fields import RichTextField -from wagtail.core.models import TranslatableMixin +from wagtail.admin.panels import FieldPanel +from wagtail.fields import RichTextField +from wagtail.models import TranslatableMixin + +from wagtail_footnotes.fields import CustomUUIDField +from wagtail_footnotes.widgets import ReadonlyUUIDInput -from .fields import CustomUUIDField -from .widgets import ReadonlyUUIDInput class Footnote(TranslatableMixin, models.Model): """ @@ -23,13 +24,15 @@ class Footnote(TranslatableMixin, models.Model): ) text = RichTextField( features=getattr( - settings, - 'WAGTAIL_FOOTNOTES_TEXT_FEATURES', - ["bold", "italic", "link"] + settings, "WAGTAIL_FOOTNOTES_TEXT_FEATURES", ["bold", "italic", "link"] ) ) panels = [FieldPanel("text"), FieldPanel("uuid", widget=ReadonlyUUIDInput)] class Meta(TranslatableMixin.Meta): + unique_together = [("page", "uuid"), ("translation_key", "locale")] verbose_name = "Translatable Footnote" + + def __str__(self): + return str(self.uuid) diff --git a/wagtail_footnotes/static/footnotes/js/footnotes.js b/wagtail_footnotes/static/footnotes/js/footnotes.js index 0e79c47..ae1ff2d 100644 --- a/wagtail_footnotes/static/footnotes/js/footnotes.js +++ b/wagtail_footnotes/static/footnotes/js/footnotes.js @@ -47,19 +47,19 @@ class FootnoteSource extends React.Component { table.empty(); var live_footnotes = document.querySelectorAll( - "#id_footnotes-FORMS > li:not(.deleted)" + "#id_footnotes-FORMS .w-panel" ); Array.prototype.forEach.call(live_footnotes, function (value) { var text = $(".public-DraftEditor-content", value).text(); var uuid = $('input[id*="-uuid"]', value)[0].value; var row = $( "" + - text + - "" + - uuid.substring(0, 6) + - "" + uuid + + ">" + + text + + "" + + uuid.substring(0, 6) + + "" ).css({ cursor: "pointer" }); table.append(row); @@ -112,6 +112,7 @@ class FootnoteSource extends React.Component { } render() { + console.log("FootnoteSource", this.props); return null; } } diff --git a/wagtail_footnotes/templates/wagtail_footnotes/admin/footnotes_modal.html b/wagtail_footnotes/templates/wagtail_footnotes/admin/footnotes_modal.html index 0837abf..0f1c0d6 100644 --- a/wagtail_footnotes/templates/wagtail_footnotes/admin/footnotes_modal.html +++ b/wagtail_footnotes/templates/wagtail_footnotes/admin/footnotes_modal.html @@ -1,17 +1,17 @@ {% comment %} - This template is used in wagtail CMS + This template is used in Wagtail CMS {% endcomment %} + {# /.modal-content #} + {# /.modal-dialog #} diff --git a/wagtail_footnotes/tests.py b/wagtail_footnotes/tests.py deleted file mode 100644 index a79ca8b..0000000 --- a/wagtail_footnotes/tests.py +++ /dev/null @@ -1,3 +0,0 @@ -# from django.test import TestCase - -# Create your tests here. diff --git a/wagtail_footnotes/urls.py b/wagtail_footnotes/urls.py index a56c8f7..e4ee6cb 100644 --- a/wagtail_footnotes/urls.py +++ b/wagtail_footnotes/urls.py @@ -1,6 +1,7 @@ from django.urls import path from django.views.generic import TemplateView + urlpatterns = [ path( "footnotes_modal/", diff --git a/wagtail_footnotes/wagtail_hooks.py b/wagtail_footnotes/wagtail_hooks.py index 270cd5b..cce7433 100644 --- a/wagtail_footnotes/wagtail_hooks.py +++ b/wagtail_footnotes/wagtail_hooks.py @@ -1,11 +1,10 @@ import wagtail.admin.rich_text.editors.draftail.features as draftail_features -from django.templatetags.static import static -from django.utils.html import format_html_join + from draftjs_exporter.dom import DOM +from wagtail import hooks from wagtail.admin.rich_text.converters.html_to_contentstate import ( InlineEntityElementHandler, ) -from wagtail.core import hooks @hooks.register("register_rich_text_features") @@ -25,7 +24,7 @@ def register_footnotes_feature(features): feature_name, draftail_features.EntityFeature( control, - js = ['wagtailadmin/js/draftail.js', 'footnotes/js/footnotes.js'] + js=["wagtailadmin/js/draftail.js", "footnotes/js/footnotes.js"], ), )