-
Notifications
You must be signed in to change notification settings - Fork 7
Add component formatting support with Table class #113
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
chrisdedman
wants to merge
9
commits into
main
Choose a base branch
from
component-formatting-class
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
1651edd
Add support for sending component-formatted messages in Room and Context
chrisdedman 410f1b0
Add MatrixTable component for structured message rendering
chrisdedman e78ee0c
renamed MatrixTable to Table class
chrisdedman 7094255
added feature example for Table component
chrisdedman 1fd5832
move component param placement
chrisdedman 57802f3
remove blackquote
chrisdedman a35052d
fix html formatting
chrisdedman 2b76240
unit test coverage for component feature
chrisdedman 89fe3b9
added docs string for Table class and methods
chrisdedman File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| from matrix import Bot, Table | ||
|
|
||
| bot = Bot() | ||
|
|
||
|
|
||
| @bot.command() | ||
| async def weather(ctx): | ||
| weather = Table(title="Los Angeles", columns=2) | ||
|
|
||
| weather.add_field("Description", "Clear Sky") | ||
| weather.add_field("Visibility", "10000m | 32808ft") | ||
| weather.add_field("Temperature", "71.33°F | 21.85°C") | ||
| weather.add_field("Feels Like", "71.33°F | 21.85°C") | ||
| weather.add_field("Atmospheric Pressure", "1012 hPa") | ||
| weather.add_field("Humidity", "66%") | ||
|
|
||
| await ctx.reply(component=weather) | ||
|
|
||
|
|
||
| bot.start(config="config.yaml") | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| from html import escape | ||
| from abc import ABC, abstractmethod | ||
|
|
||
| CELL_TEMPLATE = "<td><strong>{name}</strong><br>{value}</td>" | ||
|
|
||
| ROW_TEMPLATE = "<tr>{cells}</tr>" | ||
|
|
||
| TABLE_TEMPLATE = "<h2>{title}</h2><table><tbody>{rows}</tbody></table>" | ||
|
|
||
|
|
||
| class Component(ABC): | ||
| """Base class for message components.""" | ||
|
|
||
| @abstractmethod | ||
| def to_plain_text(self) -> str: | ||
| pass | ||
|
|
||
| @abstractmethod | ||
| def render(self) -> str: | ||
| pass | ||
|
|
||
|
|
||
| class Table(Component): | ||
| """A component that renders labeled fields as a table. | ||
|
|
||
| Fields are displayed in rows using the configured number of columns. | ||
| Incomplete rows are padded with empty cells. Field names, values, and the | ||
| table title are HTML-escaped when rendered. | ||
| """ | ||
|
|
||
| def __init__(self, *, title: str, columns: int = 2) -> None: | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think we should add a validation on columns to in case someone puts 0 or a negative amount of columns: if columns < 1:
raise ValueError(...)nit: I think we should call that |
||
| self.title: str = title | ||
| self.columns: int = columns | ||
| self.fields: list[tuple[str, str]] = [] | ||
|
|
||
| def __str__(self) -> str: | ||
| return self.render() | ||
|
|
||
| def add_field(self, name: str, value: str) -> None: | ||
| """Add a labeled field to the table. | ||
|
|
||
| ## Example | ||
|
|
||
| ```python | ||
| table = Table(title="User Info") | ||
| table.add_field("Name", "Astra") | ||
| ``` | ||
| """ | ||
| self.fields.append((name, value)) | ||
|
|
||
| def to_plain_text(self) -> str: | ||
| """Render the table as plain text. | ||
|
|
||
| ## Example | ||
|
|
||
| ```python | ||
| table = Table(title="User Info") | ||
| table.add_field("Name", "Astra") | ||
|
|
||
| result = table.to_plain_text() | ||
| # User Info | ||
| # Name: Astra | ||
| ``` | ||
| """ | ||
| return "\n".join( | ||
| [self.title, *[f"{name}: {value}" for name, value in self.fields]] | ||
| ) | ||
|
|
||
| def render(self) -> str: | ||
| """Render the table as HTML with escaped field content. | ||
|
|
||
| Incomplete rows are padded with empty cells based on the configured | ||
| column count. | ||
|
|
||
| ## Example | ||
|
|
||
| ```python | ||
| table = Table(title="User Info") | ||
| table.add_field("Name", "Astra") | ||
| table.add_field("Role", "Engineer") | ||
|
|
||
| html = table.render() | ||
| ``` | ||
| """ | ||
| cells = [] | ||
| for name, value in self.fields: | ||
| cells.append( | ||
| CELL_TEMPLATE.format( | ||
| name=escape(name), | ||
| value=escape(value), | ||
| ) | ||
| ) | ||
|
|
||
| rows = [] | ||
| for i in range(0, len(cells), self.columns): | ||
| row_cells = cells[i : i + self.columns] | ||
|
|
||
| while len(row_cells) < self.columns: | ||
| row_cells.append("<td></td>") | ||
|
|
||
| rows.append(ROW_TEMPLATE.format(cells="".join(row_cells))) | ||
|
|
||
| return TABLE_TEMPLATE.format( | ||
| title=escape(self.title), | ||
| rows="".join(rows), | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| import pytest | ||
| from matrix.component import Table | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def table(): | ||
| return Table(title="User Info") | ||
|
|
||
|
|
||
| def test_to_plain_text__expect_title_and_fields(table): | ||
| table.add_field("Name", "Astra") | ||
| table.add_field("Role", "Engineer") | ||
|
|
||
| result = table.to_plain_text() | ||
|
|
||
| assert result == "User Info\nName: Astra\nRole: Engineer" | ||
|
|
||
|
|
||
| def test_to_plain_text__with_no_fields__expect_title_only(table): | ||
| result = table.to_plain_text() | ||
|
|
||
| assert result == "User Info" | ||
|
|
||
|
|
||
| def test_render__expect_html_table(table): | ||
| table.add_field("Name", "Astra") | ||
| table.add_field("Role", "Engineer") | ||
|
|
||
| result = table.render() | ||
|
|
||
| assert "<h2>User Info</h2>" in result | ||
| assert "<table>" in result | ||
| assert "<strong>Name</strong>" in result | ||
| assert "Astra" in result | ||
| assert "<strong>Role</strong>" in result | ||
| assert "Engineer" in result | ||
|
|
||
|
|
||
| def test_render__with_odd_number_of_fields__expect_empty_padding_cell(table): | ||
| table.add_field("Name", "Astra") | ||
| table.add_field("Role", "Engineer") | ||
| table.add_field("Location", "CA") | ||
|
|
||
| result = table.render() | ||
|
|
||
| assert result.count("<tr>") == 2 | ||
| assert result.count("<td>") == 4 | ||
| assert result.count("<td></td>") == 1 | ||
| assert result.count("<strong>") == 3 | ||
|
|
||
|
|
||
| def test_render__with_custom_columns__expect_rows_grouped_by_column_count(): | ||
| table = Table(title="User Info", columns=3) | ||
| table.add_field("Name", "Astra") | ||
| table.add_field("Role", "Engineer") | ||
| table.add_field("Location", "CA") | ||
| table.add_field("Status", "Active") | ||
|
|
||
| result = table.render() | ||
|
|
||
| assert result.count("<tr>") == 2 | ||
| assert result.count("<td>") == 6 | ||
| assert result.count("<td></td>") == 2 | ||
| assert result.count("<strong>") == 4 | ||
|
|
||
|
|
||
| def test_render__with_html_content__expect_escaped_html(): | ||
| table = Table(title="<User Info>") | ||
| table.add_field("<Name>", "<Astra & Co>") | ||
|
|
||
| result = table.render() | ||
|
|
||
| assert "<User Info>" in result | ||
| assert "<Name>" in result | ||
| assert "<Astra & Co>" in result | ||
|
|
||
| assert "<User Info>" not in result | ||
| assert "<Name>" not in result | ||
| assert "<Astra & Co>" not in result | ||
|
|
||
|
|
||
| def test_str__expect_rendered_html(table): | ||
| table.add_field("Name", "Astra") | ||
|
|
||
| assert str(table) == table.render() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit: I would remove
columns=2since it's the default value.