Skip to content

Commit

Permalink
- use css from cdn
Browse files Browse the repository at this point in the history
- support display_as=html
  • Loading branch information
mhuebert committed Jan 16, 2025
1 parent f34525a commit c34ea19
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 27 deletions.
21 changes: 9 additions & 12 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -94,24 +94,24 @@ jobs:
run: |
VERSION=$(poetry version -s)
# Convert to npm version format if it's a dev version
if [[ $VERSION == *.dev ]]; then
DATE_TIME=$(echo $VERSION | sed 's/\.dev$//')
NPM_VERSION="0.0.0-dev.$(echo $DATE_TIME | sed 's/\.//g')"
else
NPM_VERSION=$VERSION
fi
JSDELIVR_URL="https://cdn.jsdelivr.net/npm/@probcomp/genstudio@${NPM_VERSION}/dist/widget_build.js"
NPM_BASE="https://cdn.jsdelivr.net/npm/@probcomp/genstudio@${NPM_VERSION}/dist"
JSDELIVR_JS_URL="${NPM_BASE}/widget_build.js"
JSDELIVR_CSS_URL="${NPM_BASE}/widget.css"
# Update the widget URL in the source
sed -i "s|_esm = WIDGET_URL|_esm = \"${JSDELIVR_URL}\"|" src/genstudio/widget.py
# Update both URLs in the source
sed -i "s|CDN_SCRIPT_URL = None|CDN_SCRIPT_URL = \"${JSDELIVR_JS_URL}\"|" src/genstudio/util.py
sed -i "s|CDN_CSS_URL = None|CDN_CSS_URL = \"${JSDELIVR_CSS_URL}\"|" src/genstudio/util.py
# Build with modified source
poetry build
# Restore the file using git
git checkout src/genstudio/widget.py
git checkout src/genstudio/util.py
- name: Deploy to Artifact Registry
run: |
Expand All @@ -138,22 +138,19 @@ jobs:
run: |
VERSION=$(poetry version -s)
# Convert Python version to npm-compatible version
if [[ $VERSION == *.dev ]]; then
# Extract date and time parts, removing .dev suffix
DATE_TIME=$(echo $VERSION | sed 's/\.dev$//')
# Format as 0.0.0-dev.YYYYMMDDHHMMSS
NPM_VERSION="0.0.0-dev.$(echo $DATE_TIME | sed 's/\.//g')"
else
NPM_VERSION=$VERSION
fi
# Update package.json version to match npm version
npm version $NPM_VERSION --no-git-tag-version
# Copy the bundle to a more standard location for npm
# Copy both files to npm dist directory
mkdir -p dist
cp src/genstudio/js/widget_build.js dist/
cp src/genstudio/widget.css dist/
echo "Publishing npm package version $NPM_VERSION"
npm publish --access public
Expand Down
28 changes: 22 additions & 6 deletions src/genstudio/layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from html2image import Html2Image
from PIL import Image

from genstudio.util import CONFIG, PARENT_PATH
from genstudio.util import CONFIG, WIDGET_URL, CSS_URL
from genstudio.widget import Widget, to_json_with_initialState, WidgetState


Expand All @@ -16,6 +16,24 @@ def create_parent_dir(path: str) -> None:
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)


def get_script_content():
"""Get the JS content either from CDN or local file"""
if isinstance(WIDGET_URL, str): # It's a CDN URL
return f'import {{ renderData }} from "{WIDGET_URL}";'
else: # It's a local Path
with open(WIDGET_URL, "r") as js_file:
return js_file.read()


def get_style_content():
"""Get the CSS content either from CDN or local file"""
if isinstance(CSS_URL, str): # It's a CDN URL
return f'@import "{CSS_URL}";'
else: # It's a local Path
with open(CSS_URL, "r") as css_file:
return css_file.read()


def html_snippet(ast, id=None):
id = id or f"genstudio-widget-{uuid.uuid4().hex}"
buffers = []
Expand All @@ -27,11 +45,9 @@ def html_snippet(ast, id=None):
]
buffers_array = f"[{','.join(encoded_buffers)}]"

# Read and inline the JS and CSS files
with open(PARENT_PATH / "js/widget_build.js", "r") as js_file:
js_content = js_file.read()
with open(PARENT_PATH / "widget.css", "r") as css_file:
css_content = css_file.read()
# Get JS and CSS content
js_content = get_script_content()
css_content = get_style_content()

html_content = f"""
<style>{css_content}</style>
Expand Down
18 changes: 14 additions & 4 deletions src/genstudio/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,20 @@ class Config(TypedDict):
defaults: dict[Any, Any]


try:
PARENT_PATH = pathlib.Path(importlib.util.find_spec("genstudio.util").origin).parent # type: ignore
except AttributeError:
raise ImportError("Cannot find the genstudio.util module")

# CDN URLs for published assets - set during package build
CDN_SCRIPT_URL = None
CDN_CSS_URL = None

# Local development paths
WIDGET_URL = CDN_SCRIPT_URL or (PARENT_PATH / "js/widget_build.js")
CSS_URL = CDN_CSS_URL or (PARENT_PATH / "widget.css")


CONFIG: Config = {"display_as": "widget", "dev": False, "defaults": {}}


Expand Down Expand Up @@ -54,10 +68,6 @@ def __exit__(self, *args):
self.time = t


try:
PARENT_PATH = pathlib.Path(importlib.util.find_spec("genstudio.util").origin).parent # type: ignore
except AttributeError:
raise ImportError("Cannot find the genstudio.util module")
# %%


Expand Down
7 changes: 2 additions & 5 deletions src/genstudio/widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import traitlets
import warnings

from genstudio.util import CONFIG, PARENT_PATH
from genstudio.util import CONFIG, WIDGET_URL, CSS_URL


class SubscriptableNamespace(SimpleNamespace):
Expand Down Expand Up @@ -392,12 +392,9 @@ def init_state(self, collected_state):
self._state[key] = value


WIDGET_URL = PARENT_PATH / "js/widget_build.js"


class Widget(anywidget.AnyWidget):
_esm = WIDGET_URL
_css = PARENT_PATH / "widget.css"
_css = CSS_URL
callback_registry: Dict[str, Callable] = {}
data = traitlets.Any().tag(sync=True, to_json=to_json_with_initialState)

Expand Down

0 comments on commit c34ea19

Please sign in to comment.