Skip to content

Commit

Permalink
Only Once JS prototype
Browse files Browse the repository at this point in the history
  • Loading branch information
Archmonger committed Dec 20, 2024
1 parent 464b4e2 commit ef242db
Show file tree
Hide file tree
Showing 5 changed files with 66 additions and 6 deletions.
41 changes: 40 additions & 1 deletion src/js/src/components.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { DjangoFormProps } from "./types";
import { DjangoFormProps, OnlyOnceProps } from "./types";
import React from "react";
import ReactDOM from "react-dom";
/**
Expand Down Expand Up @@ -62,3 +62,42 @@ export function DjangoForm({

return null;
}

export function OnlyOnceJS({ jsPath, autoRemove }: OnlyOnceProps): null {
React.useEffect(() => {
// Check if the script element already exists
let el = document.head.querySelector(
"script.reactpy-staticfile[src='" + jsPath + "']",
);

// Create a new script element, if needed
if (el === null) {
el = document.createElement("script");
el.className = "reactpy-staticfile";
if (jsPath) {
el.setAttribute("src", jsPath);
}
document.head.appendChild(el);
}

// If requested, auto remove the script when it is no longer needed
if (autoRemove) {
// Keep track of the number of ReactPy components that are dependent on this script
let count = Number(el.getAttribute("data-count"));
count += 1;
el.setAttribute("data-count", count.toString());

// Remove the script element when the last dependent component is unmounted
return () => {
count -= 1;
if (count === 0) {
el.remove();
} else {
el.setAttribute("data-count", count.toString());
}
};
}
}, []);

return null;
}
2 changes: 1 addition & 1 deletion src/js/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export { DjangoForm, bind } from "./components";
export { OnlyOnceJS, DjangoForm, bind } from "./components";
export { mountComponent } from "./mount";
5 changes: 5 additions & 0 deletions src/js/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,8 @@ export interface DjangoFormProps {
onSubmitCallback: (data: Object) => void;
formId: string;
}

export interface OnlyOnceProps {
jsPath: string;
autoRemove: boolean;
}
23 changes: 19 additions & 4 deletions src/reactpy_django/components.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@
from __future__ import annotations

import json
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Union, cast
from urllib.parse import urlencode

from django.http import HttpRequest
from django.templatetags.static import static
from django.urls import reverse
from reactpy import component, hooks, html, utils
from reactpy import component, hooks, html, utils, web
from reactpy.types import ComponentType, Key, VdomDict

from reactpy_django.exceptions import ViewNotRegisteredError
Expand All @@ -25,6 +27,12 @@
from reactpy_django.types import AsyncFormEvent, SyncFormEvent, ViewToComponentConstructor, ViewToIframeConstructor


DjangoJS = web.export(
web.module_from_file("reactpy-django", file=Path(__file__).parent / "static" / "reactpy_django" / "client.js"),
("OnlyOnceJS"),
)


def view_to_component(
view: Callable | View | str,
transforms: Sequence[Callable[[VdomDict], Any]] = (),
Expand Down Expand Up @@ -97,7 +105,9 @@ def django_css(static_path: str, key: Key | None = None) -> ComponentType:
return _django_css(static_path=static_path, key=key)


def django_js(static_path: str, key: Key | None = None) -> ComponentType:
def django_js(
static_path: str, only_once: bool = False, only_once_auto_remove: bool = False, key: Key | None = None
) -> ComponentType:
"""Fetches a JS static file for use within ReactPy. This allows for deferred JS loading.
Args:
Expand All @@ -107,7 +117,9 @@ def django_js(static_path: str, key: Key | None = None) -> ComponentType:
immediate siblings
"""

return _django_js(static_path=static_path, key=key)
return _django_js(
static_path=static_path, only_once=only_once, only_once_auto_remove=only_once_auto_remove, key=key
)


def django_form(
Expand Down Expand Up @@ -278,5 +290,8 @@ def _django_css(static_path: str):


@component
def _django_js(static_path: str):
def _django_js(static_path: str, only_once: bool, only_once_auto_remove: bool):
if only_once:
return DjangoJS({"jsPath": static(static_path), "autoRemove": only_once_auto_remove})

return html.script(cached_static_file(static_path))
1 change: 1 addition & 0 deletions src/reactpy_django/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -492,6 +492,7 @@ def wrapper(*args, **kwargs):


def cached_static_file(static_path: str) -> str:
"""Fetches a static file from Django and caches it for future use."""
from reactpy_django.config import REACTPY_CACHE

# Try to find the file within Django's static files
Expand Down

0 comments on commit ef242db

Please sign in to comment.