Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 164e3a3

Browse files
committedDec 5, 2024·
format
1 parent ebd87bf commit 164e3a3

File tree

3 files changed

+45
-41
lines changed

3 files changed

+45
-41
lines changed
 

‎CHANGELOG.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ Don't forget to remove deprecated code on each major release!
2525

2626
### Fixed
2727

28-
- Fixed bregression from the previous release where components would sometimes not output debug messages when `settings.py:DEBUG` is enabled.
28+
- Fixed regression from the previous release where components would sometimes not output debug messages when `settings.py:DEBUG` is enabled.
2929

3030
### Changed
3131

‎src/reactpy_django/components.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import json
44
import os
55
from pathlib import Path
6-
from typing import TYPE_CHECKING, Any, Callable, Type, Union, cast
6+
from typing import TYPE_CHECKING, Any, Callable, Union, cast
77
from urllib.parse import urlencode
88
from uuid import uuid4
99

@@ -129,7 +129,7 @@ def django_js(static_path: str, key: Key | None = None):
129129

130130

131131
def django_form(
132-
form: Type[Form],
132+
form: type[Form],
133133
*,
134134
top_children: Sequence = (),
135135
bottom_children: Sequence = (),
@@ -265,7 +265,7 @@ def _django_js(static_path: str):
265265

266266
@component
267267
def _django_form(
268-
form: Type[Form], top_children: Sequence, bottom_children: Sequence, auto_submit: bool, auto_submit_wait: int
268+
form: type[Form], top_children: Sequence, bottom_children: Sequence, auto_submit: bool, auto_submit_wait: int
269269
):
270270
# TODO: Implement form restoration on page reload. Probably want to create a new setting called
271271
# form_restoration_method that can be set to "URL", "CLIENT_STORAGE", "SERVER_SESSION", or None.
@@ -284,18 +284,20 @@ def _django_form(
284284

285285
# Don't allow the count of top and bottom children to change
286286
if len(top_children) != top_children_count.current or len(bottom_children) != bottom_children_count.current:
287-
raise ValueError("Dynamically changing the number of top or bottom children is not allowed.")
287+
msg = "Dynamically changing the number of top or bottom children is not allowed."
288+
raise ValueError(msg)
288289

289290
# Try to initialize the form with the provided data
290291
try:
291292
initialized_form = form(data=submitted_data)
292293
except Exception as e:
293294
if not isinstance(form, type(Form)):
294-
raise ValueError(
295+
msg = (
295296
"The provided form must be an uninitialized Django Form. "
296297
"Do NOT initialize your form by calling it (ex. `MyForm()`)."
297-
) from e
298-
raise e
298+
)
299+
raise TypeError(msg) from e
300+
raise
299301

300302
# Run the form validation, if data was provided
301303
if submitted_data:

‎src/reactpy_django/transforms.py

Lines changed: 35 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
from __future__ import annotations
22

3-
from typing import Callable
3+
from typing import TYPE_CHECKING, Callable
44

55
from reactpy.core.events import EventHandler, to_event_handler_function
6-
from reactpy.core.types import VdomDict
6+
7+
if TYPE_CHECKING:
8+
from reactpy.core.types import VdomDict
79

810
# TODO: Move all this logic to `reactpy.utils._mutate_vdom()` and remove this file.
911

@@ -112,7 +114,7 @@ def _add_on_change_event(event_func, vdom_tree: VdomDict) -> VdomDict:
112114
return vdom_tree
113115

114116
vdom_tree.setdefault("eventHandlers", {})
115-
if vdom_tree["tagName"] in ["input", "textarea"]:
117+
if vdom_tree["tagName"] in {"input", "textarea"}:
116118
if "onChange" in vdom_tree["eventHandlers"]:
117119
pass
118120
elif isinstance(event_func, EventHandler):
@@ -136,7 +138,7 @@ def mutation(vdom_tree: VdomDict) -> VdomDict:
136138
return vdom_tree
137139

138140
vdom_tree.setdefault("eventHandlers", {})
139-
if vdom_tree["tagName"] in ["input", "textarea"]:
141+
if vdom_tree["tagName"] in {"input", "textarea"}:
140142
if "onChange" in vdom_tree["eventHandlers"]:
141143
pass
142144
elif isinstance(event_func, EventHandler):
@@ -164,18 +166,18 @@ def do_nothing_event(*args, **kwargs):
164166

165167
SPECIAL_PROPS = r"""
166168
children: A React node (an element, a string, a number, a portal, an empty node like null, undefined and booleans, or an array of other React nodes). Specifies the content inside the component. When you use JSX, you will usually specify the children prop implicitly by nesting tags like <div><span /></div>.
167-
dangerouslySetInnerHTML: An object of the form { __html: '<p>some html</p>' } with a raw HTML string inside. Overrides the innerHTML property of the DOM node and displays the passed HTML inside. This should be used with extreme caution! If the HTML inside isnt trusted (for example, if its based on user data), you risk introducing an XSS vulnerability. Read more about using dangerouslySetInnerHTML.
169+
dangerouslySetInnerHTML: An object of the form { __html: '<p>some html</p>' } with a raw HTML string inside. Overrides the innerHTML property of the DOM node and displays the passed HTML inside. This should be used with extreme caution! If the HTML inside isn't trusted (for example, if it's based on user data), you risk introducing an XSS vulnerability. Read more about using dangerouslySetInnerHTML.
168170
ref: A ref object from useRef or createRef, or a ref callback function, or a string for legacy refs. Your ref will be filled with the DOM element for this node. Read more about manipulating the DOM with refs.
169-
suppressContentEditableWarning: A boolean. If true, suppresses the warning that React shows for elements that both have children and contentEditable={true} (which normally do not work together). Use this if youre building a text input library that manages the contentEditable content manually.
170-
suppressHydrationWarning: A boolean. If you use server rendering, normally there is a warning when the server and the client render different content. In some rare cases (like timestamps), it is very hard or impossible to guarantee an exact match. If you set suppressHydrationWarning to true, React will not warn you about mismatches in the attributes and the content of that element. It only works one level deep, and is intended to be used as an escape hatch. Dont overuse it. Read more about suppressing hydration errors.
171-
style: An object with CSS styles, for example { fontWeight: 'bold', margin: 20 }. Similarly to the DOM style property, the CSS property names need to be written as camelCase, for example fontWeight instead of font-weight. You can pass strings or numbers as values. If you pass a number, like width: 100, React will automatically append px (“pixels”) to the value unless its a unitless property. We recommend using style only for dynamic styles where you dont know the style values ahead of time. In other cases, applying plain CSS classes with className is more efficient. Read more about applying CSS with className and styles.
172-
""" # noqa: E501
171+
suppressContentEditableWarning: A boolean. If true, suppresses the warning that React shows for elements that both have children and contentEditable={true} (which normally do not work together). Use this if you're building a text input library that manages the contentEditable content manually.
172+
suppressHydrationWarning: A boolean. If you use server rendering, normally there is a warning when the server and the client render different content. In some rare cases (like timestamps), it is very hard or impossible to guarantee an exact match. If you set suppressHydrationWarning to true, React will not warn you about mismatches in the attributes and the content of that element. It only works one level deep, and is intended to be used as an escape hatch. Don't overuse it. Read more about suppressing hydration errors.
173+
style: An object with CSS styles, for example { fontWeight: 'bold', margin: 20 }. Similarly to the DOM style property, the CSS property names need to be written as camelCase, for example fontWeight instead of font-weight. You can pass strings or numbers as values. If you pass a number, like width: 100, React will automatically append px (“pixels”) to the value unless it's a unitless property. We recommend using style only for dynamic styles where you don't know the style values ahead of time. In other cases, applying plain CSS classes with className is more efficient. Read more about applying CSS with className and styles.
174+
"""
173175

174176
STANDARD_PROPS = r"""
175177
accessKey: A string. Specifies a keyboard shortcut for the element. Not generally recommended.
176178
aria-*: ARIA attributes let you specify the accessibility tree information for this element. See ARIA attributes for a complete reference. In React, all ARIA attribute names are exactly the same as in HTML.
177179
autoCapitalize: A string. Specifies whether and how the user input should be capitalized.
178-
className: A string. Specifies the elements CSS class name. Read more about applying CSS styles.
180+
className: A string. Specifies the element's CSS class name. Read more about applying CSS styles.
179181
contentEditable: A boolean. If true, the browser lets the user edit the rendered element directly. This is used to implement rich text input libraries like Lexical. React warns if you try to pass React children to an element with contentEditable={true} because React will not be able to update its content after user edits.
180182
data-*: Data attributes let you attach some string data to the element, for example data-fruit="banana". In React, they are not commonly used because you would usually read data from props or state instead.
181183
dir: Either 'ltr' or 'rtl'. Specifies the text direction of the element.
@@ -286,7 +288,7 @@ def do_nothing_event(*args, **kwargs):
286288
tabIndex: A number. Overrides the default Tab button behavior. Avoid using values other than -1 and 0.
287289
title: A string. Specifies the tooltip text for the element.
288290
translate: Either 'yes' or 'no'. Passing 'no' excludes the element content from being translated.
289-
""" # noqa: E501
291+
"""
290292

291293
FORM_PROPS = r"""
292294
onReset: An Event handler function. Fires when a form gets reset.
@@ -300,34 +302,34 @@ def do_nothing_event(*args, **kwargs):
300302
onCancelCapture: A version of onCancel that fires in the capture phase. capture-phase-events)
301303
onClose: An Event handler function. Fires when a dialog has been closed.
302304
onCloseCapture: A version of onClose that fires in the capture phase.
303-
""" # noqa: E501
305+
"""
304306

305307
DETAILS_PROPS = r"""
306308
onToggle: An Event handler function. Fires when the user toggles the details.
307309
onToggleCapture: A version of onToggle that fires in the capture phase. capture-phase-events)
308-
""" # noqa: E501
310+
"""
309311

310312
IMG_IFRAME_OBJECT_EMBED_LINK_IMAGE_PROPS = r"""
311313
onLoad: An Event handler function. Fires when the resource has loaded.
312314
onLoadCapture: A version of onLoad that fires in the capture phase.
313315
onError: An Event handler function. Fires when the resource could not be loaded.
314316
onErrorCapture: A version of onError that fires in the capture phase.
315-
""" # noqa: E501
317+
"""
316318

317319
AUDIO_VIDEO_PROPS = r"""
318320
onAbort: An Event handler function. Fires when the resource has not fully loaded, but not due to an error.
319321
onAbortCapture: A version of onAbort that fires in the capture phase.
320-
onCanPlay: An Event handler function. Fires when theres enough data to start playing, but not enough to play to the end without buffering.
322+
onCanPlay: An Event handler function. Fires when there's enough data to start playing, but not enough to play to the end without buffering.
321323
onCanPlayCapture: A version of onCanPlay that fires in the capture phase.
322-
onCanPlayThrough: An Event handler function. Fires when theres enough data that its likely possible to start playing without buffering until the end.
324+
onCanPlayThrough: An Event handler function. Fires when there's enough data that it's likely possible to start playing without buffering until the end.
323325
onCanPlayThroughCapture: A version of onCanPlayThrough that fires in the capture phase.
324326
onDurationChange: An Event handler function. Fires when the media duration has updated.
325327
onDurationChangeCapture: A version of onDurationChange that fires in the capture phase.
326328
onEmptied: An Event handler function. Fires when the media has become empty.
327329
onEmptiedCapture: A version of onEmptied that fires in the capture phase.
328330
onEncrypted: An Event handler function. Fires when the browser encounters encrypted media.
329331
onEncryptedCapture: A version of onEncrypted that fires in the capture phase.
330-
onEnded: An Event handler function. Fires when the playback stops because theres nothing left to play.
332+
onEnded: An Event handler function. Fires when the playback stops because there's nothing left to play.
331333
onEndedCapture: A version of onEnded that fires in the capture phase.
332334
onError: An Event handler function. Fires when the resource could not be loaded.
333335
onErrorCapture: A version of onError that fires in the capture phase.
@@ -363,7 +365,7 @@ def do_nothing_event(*args, **kwargs):
363365
onVolumeChangeCapture: A version of onVolumeChange that fires in the capture phase.
364366
onWaiting: An Event handler function. Fires when the playback stopped due to temporary lack of data.
365367
onWaitingCapture: A version of onWaiting that fires in the capture phase.
366-
""" # noqa: E501
368+
"""
367369

368370
INPUT_PROPS = r"""
369371
checked: A boolean. For a checkbox input or a radio button, controls whether it is selected.
@@ -375,10 +377,10 @@ def do_nothing_event(*args, **kwargs):
375377
capture: A string. Specifies the media (microphone, video, or camera) captured by a type="file" input.
376378
autoComplete: A string. Specifies one of the possible autocomplete behaviors.
377379
autoFocus: A boolean. If true, React will focus the element on mount.
378-
dirname: A string. Specifies the form field name for the elements directionality.
380+
dirname: A string. Specifies the form field name for the element's directionality.
379381
disabled: A boolean. If true, the input will not be interactive and will appear dimmed.
380382
children: <input> does not accept children.
381-
form: A string. Specifies the id of the <form> this input belongs to. If omitted, its the closest parent form.
383+
form: A string. Specifies the id of the <form> this input belongs to. If omitted, it's the closest parent form.
382384
formAction: A string. Overrides the parent <form action> for type="submit" and type="image".
383385
formEnctype: A string. Overrides the parent <form enctype> for type="submit" and type="image".
384386
formMethod: A string. Overrides the parent <form method> for type="submit" and type="image".
@@ -391,8 +393,8 @@ def do_nothing_event(*args, **kwargs):
391393
min: A number. Specifies the minimum value of numerical and datetime inputs.
392394
minLength: A number. Specifies the minimum length of text and other inputs.
393395
multiple: A boolean. Specifies whether multiple values are allowed for <type="file" and type="email".
394-
name: A string. Specifies the name for this input thats submitted with the form.
395-
onChange: An Event handler function. Required for controlled inputs. Fires immediately when the inputs value is changed by the user (for example, it fires on every keystroke). Behaves like the browser input event.
396+
name: A string. Specifies the name for this input that's submitted with the form.
397+
onChange: An Event handler function. Required for controlled inputs. Fires immediately when the input's value is changed by the user (for example, it fires on every keystroke). Behaves like the browser input event.
396398
onChangeCapture: A version of onChange that fires in the capture phase.
397399
onInput: An Event handler function. Fires immediately when the value is changed by the user. For historical reasons, in React it is idiomatic to use onChange instead which works similarly.
398400
onInputCapture: A version of onInput that fires in the capture phase.
@@ -409,7 +411,7 @@ def do_nothing_event(*args, **kwargs):
409411
step: A positive number or an 'any' string. Specifies the distance between valid values.
410412
type: A string. One of the input types.
411413
width: A string. Specifies the image width for a type="image" input.
412-
""" # noqa: E501
414+
"""
413415

414416
SELECT_PROPS = r"""
415417
value: A string (or an array of strings for multiple={true}). Controls which option is selected. Every value string match the value of some <option> nested inside the <select>.
@@ -418,9 +420,9 @@ def do_nothing_event(*args, **kwargs):
418420
autoFocus: A boolean. If true, React will focus the element on mount.
419421
children: <select> accepts <option>, <optgroup>, and <datalist> components as children. You can also pass your own components as long as they eventually render one of the allowed components. If you pass your own components that eventually render <option> tags, each <option> you render must have a value.
420422
disabled: A boolean. If true, the select box will not be interactive and will appear dimmed.
421-
form: A string. Specifies the id of the <form> this select box belongs to. If omitted, its the closest parent form.
423+
form: A string. Specifies the id of the <form> this select box belongs to. If omitted, it's the closest parent form.
422424
multiple: A boolean. If true, the browser allows multiple selection.
423-
name: A string. Specifies the name for this select box thats submitted with the form.
425+
name: A string. Specifies the name for this select box that's submitted with the form.
424426
onChange: An Event handler function. Required for controlled select boxes. Fires immediately when the user picks a different option. Behaves like the browser input event.
425427
onChangeCapture: A version of onChange that fires in the capture phase.
426428
onInput: An Event handler function. Fires immediately when the value is changed by the user. For historical reasons, in React it is idiomatic to use onChange instead which works similarly.
@@ -429,19 +431,19 @@ def do_nothing_event(*args, **kwargs):
429431
onInvalidCapture: A version of onInvalid that fires in the capture phase.
430432
required: A boolean. If true, the value must be provided for the form to submit.
431433
size: A number. For multiple={true} selects, specifies the preferred number of initially visible items.
432-
""" # noqa: E501
434+
"""
433435

434436
TEXTAREA_PROPS = r"""
435437
autoComplete: Either 'on' or 'off'. Specifies the autocomplete behavior.
436438
autoFocus: A boolean. If true, React will focus the element on mount.
437439
children: <textarea> does not accept children. To set the initial value, use defaultValue.
438440
cols: A number. Specifies the default width in average character widths. Defaults to 20.
439441
disabled: A boolean. If true, the input will not be interactive and will appear dimmed.
440-
form: A string. Specifies the id of the <form> this input belongs to. If omitted, its the closest parent form.
442+
form: A string. Specifies the id of the <form> this input belongs to. If omitted, it's the closest parent form.
441443
maxLength: A number. Specifies the maximum length of text.
442444
minLength: A number. Specifies the minimum length of text.
443-
name: A string. Specifies the name for this input thats submitted with the form.
444-
onChange: An Event handler function. Required for controlled text areas. Fires immediately when the inputs value is changed by the user (for example, it fires on every keystroke). Behaves like the browser input event.
445+
name: A string. Specifies the name for this input that's submitted with the form.
446+
onChange: An Event handler function. Required for controlled text areas. Fires immediately when the input's value is changed by the user (for example, it fires on every keystroke). Behaves like the browser input event.
445447
onChangeCapture: A version of onChange that fires in the capture phase.
446448
onInput: An Event handler function. Fires immediately when the value is changed by the user. For historical reasons, in React it is idiomatic to use onChange instead which works similarly.
447449
onInputCapture: A version of onInput that fires in the capture phase.
@@ -454,7 +456,7 @@ def do_nothing_event(*args, **kwargs):
454456
required: A boolean. If true, the value must be provided for the form to submit.
455457
rows: A number. Specifies the default height in average character heights. Defaults to 2.
456458
wrap: Either 'hard', 'soft', or 'off'. Specifies how the text should be wrapped when submitting a form.
457-
""" # noqa: E501
459+
"""
458460

459461
LINK_PROPS = r"""
460462
disabled: a boolean. Disables the stylesheet.
@@ -471,15 +473,15 @@ def do_nothing_event(*args, **kwargs):
471473
hrefLang: a string. The language of the linked resource.
472474
integrity: a string. A cryptographic hash of the resource, to verify its authenticity.
473475
type: a string. The MIME type of the linked resource.
474-
""" # noqa: E501
476+
"""
475477

476478
META_PROPS = r"""
477479
name: a string. Specifies the kind of metadata to be attached to the document.
478480
charset: a string. Specifies the character set used by the document. The only valid value is "utf-8".
479481
httpEquiv: a string. Specifies a directive for processing the document.
480482
itemProp: a string. Specifies metadata about a particular item within the document rather than the document as a whole.
481483
content: a string. Specifies the metadata to be attached when used with the name or itemProp props or the behavior of the directive when used with the httpEquiv prop.
482-
""" # noqa: E501
484+
"""
483485

484486
SCRIPT_PROPS = r"""
485487
async: a boolean. Allows the browser to defer execution of the script until the rest of the document has been processed — the preferred behavior for performance.
@@ -490,7 +492,7 @@ def do_nothing_event(*args, **kwargs):
490492
nonce: a string. A cryptographic nonce to allow the resource when using a strict Content Security Policy.
491493
referrer: a string. Says what Referer header to send when fetching the script and any resources that the script fetches in turn.
492494
type: a string. Says whether the script is a classic script, ES module, or import map.
493-
""" # noqa: E501
495+
"""
494496

495497
KNOWN_REACT_PROPS = react_props_set(
496498
SPECIAL_PROPS

0 commit comments

Comments
 (0)
Please sign in to comment.