Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .claude/skills/shinyreact-build-app/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,9 @@ per-card state, because *any* output recomputing makes it `true`: use
`ReactApp(server, bookmark_store="url")`, `[r]` `enableBookmarking = "url"`
with a per-request UI function) and the client needs no code at all:
restored values seed `useShinyInput` initial values before the first paint.
The server **must** register an `onBookmarked()` / `on_bookmarked()` callback
(usually `updateQueryString()`): Shiny's default is a Bootstrap modal, which a
`page_react()` page cannot open.
See [`references/bookmarking.md`](references/bookmarking.md).

**Typed inputs** — `useShinyInput(id, default, { type: "shiny.datetime" })`
Expand Down
20 changes: 19 additions & 1 deletion .claude/skills/shinyreact-build-app/references/bookmarking.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,26 @@ app = ReactApp(server, bookmark_store="url")
shinyApp(ui = function(req) page_react(), server, enableBookmarking = "url")
```

**Register an `on_bookmarked()` callback — this is required.** With none,
Shiny shows the bookmark URL in a Bootstrap modal, and `page_react()` loads no
Bootstrap, so the modal cannot open (the browser console logs a `[shinyreact]`
error saying so). Writing the URL to the address bar is the usual choice:

```python
# [py]
session.bookmark.on_bookmarked(session.bookmark.update_query_string)
```
```r
# [r] -- inside server()
onBookmarked(function(url) updateQueryString(url))
```

Or show the URL your own way — a React dialog fed by `send_message()`, a copy
button — from the same callback.

Trigger it from an action-button input (`[py]` `await session.bookmark()`,
`[r]` `session$doBookmark()`), which rewrites the browser URL. On a later visit to that URL the page entry point
`[r]` `session$doBookmark()`), which runs that callback. On a later visit to
that URL the page entry point
embeds the saved values in the page, and the client seeds `useShinyInput`
initial values from them **before the first paint** — so a bookmarked link
renders restored state directly, with no flash of the defaults and no
Expand Down
2 changes: 2 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,8 @@ The two sanctioned cases, both mediated by a single accessor:
| `getReactRegistry()` | input/output values and their subscribers; two registries would split one input id's producers and consumers across them |
| `getMessageRegistry()` | Shiny gives **one dispatcher slot per message type**, so a second `addCustomMessageHandler("shinyReactMessage")` either replaces the first or throws — either way one copy's handlers go dead |

Not state, so not a third case: `installModalFallback()` fills an empty `jQuery.fn.modal` so Shiny's Bootstrap modal script logs a `[shinyreact]` error instead of throwing on a Bootstrap-free page (#326). Shiny's inline script calls the page's jQuery, so nothing narrower can answer it; it never overwrites an existing `modal`.

Rules if you find yourself adding a third:

- **Go through an accessor**, never a bare assignment at the point of use. One place attaches (`shiny.x ??= singleton`), everyone reads through it. Scattered assignments are how `window.Shiny.messageRegistry` ended up written from two places and read from none.
Expand Down
18 changes: 18 additions & 0 deletions FEATURES.md
Original file line number Diff line number Diff line change
Expand Up @@ -1391,6 +1391,24 @@ initial page.
already emits it as `"1.0"`
- keys like `__proto__` and `constructor` are ordinary own properties after
`JSON.parse`, so emitting them is safe
- bookmarking needs an app-registered `onBookmarked()` / `on_bookmarked()`
callback (#326)
- shinyreact registers none; with no callback, Shiny shows the URL in a
Bootstrap modal, which a Bootstrap-free page cannot open
- the documented callback is `updateQueryString(url)` /
`session.bookmark.update_query_string`, which writes the URL to the
address bar `(e2e)`
- `[js]` without it, the console logs a `[shinyreact]` error naming that fix
instead of `$(...).modal is not a function` `(e2e)`
- at bundle load, when `window.jQuery` exists and `jQuery.fn.modal` does
not, it fills `jQuery.fn.modal` with a function that logs the error and
returns its jQuery object
- Bootstrap already on the page, or a second bundle copy's fallback, is
left alone; a Bootstrap loaded later overwrites the fallback
- it covers every Shiny modal: `showModal()` / `modal_show()` log the same
error
- the modal's HTML is still inserted at the end of `<body>`, unstyled,
and its Dismiss button does nothing
- SECURITY: bookmarked values are visible in the page source
- in URL mode the values are already in the URL, so the tag adds no exposure
- in server-stored mode (`?_state_id_=`) the URL hides them but the tag
Expand Down
8 changes: 6 additions & 2 deletions examples/10-bookmarking/FEATURES.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,13 @@ a unit test; `(verify)` marks a claim not yet checked against the code.
- `txt` is `repr`'d, so it is quoted `(test)`
- it renders from the hook defaults (`""` / `0` / `false`), since the client
does not gate on `useShinyInitialized()` `(test)`
- `session.bookmark.on_bookmarked(session.bookmark.update_query_string)`
writes the bookmark URL to the address bar
- required: with no callback Shiny shows the URL in a Bootstrap modal, which
this Bootstrap-free page cannot open
- `@reactive.effect` + `@reactive.event(input.bookmark_clicks,
ignore_init=True)` → `await session.bookmark()`, which rewrites the browser
URL
ignore_init=True)` → `await session.bookmark()`, which runs the
`on_bookmarked()` callback above
- the mount-time `0` does not bookmark; the URL rewrite itself needs a
browser, so in-memory tests only assert the effect runs cleanly `(test)`
- `[py]` only — this example has no R server
Expand Down
15 changes: 15 additions & 0 deletions examples/10-bookmarking/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,21 @@ shiny run examples/10-bookmarking/app.py
string.
3. Copy the URL into a new tab — the inputs initialise from the URL.

## Register an `on_bookmarked()` callback

```python
session.bookmark.on_bookmarked(session.bookmark.update_query_string)
```

When an app has no `on_bookmarked()` callback, Shiny shows the bookmark URL in a
Bootstrap modal. `page_react()` loads no Bootstrap, so that modal cannot open
(the browser console says so). Register your own callback: this one writes the
URL to the address bar. In R:

```r
onBookmarked(function(url) updateQueryString(url))
```

## Bookmark modes

This example uses `bookmark_store="url"`, which encodes inputs into the URL
Expand Down
4 changes: 4 additions & 0 deletions examples/10-bookmarking/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ def greeting() -> str:
chk_label = "yes" if input.chk() else "no"
return f"text={input.txt()!r} num={input.num()} checked={chk_label}"

# Put the bookmark URL in the address bar. Without a callback, Shiny shows
# the URL in a Bootstrap modal, and this page loads no Bootstrap.
session.bookmark.on_bookmarked(session.bookmark.update_query_string)

@reactive.effect
@reactive.event(input.bookmark_clicks, ignore_init=True)
async def _on_bookmark_click() -> None:
Expand Down
5 changes: 5 additions & 0 deletions pkg-js/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@
- The stylesheet is also exported as `@posit-dev/shinyreact/styles.css`, so
TypeScript resolves the import with no `declare module` (#329).

- On a page with no Bootstrap, a Shiny modal (`showModal()`, or the bookmark
URL dialog Shiny falls back to when the app has no `onBookmarked()`
callback) now logs a `[shinyreact]` console error naming the fix, instead of
throwing `$(...).modal is not a function` (#326).

## 0.1.1

- First release published through CI with npm trusted publishing
Expand Down
22 changes: 11 additions & 11 deletions pkg-js/dist/shinyreact.js

Large diffs are not rendered by default.

45 changes: 45 additions & 0 deletions pkg-js/src/__tests__/modal-fallback.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { afterEach, describe, expect, it, vi } from "vitest";
import {
installModalFallback,
MODAL_FALLBACK_MESSAGE,
} from "../modal-fallback";

afterEach(() => {
delete (window as any).jQuery;
vi.restoreAllMocks();
});

describe("installModalFallback (#326)", () => {
it("fills an empty jQuery.fn.modal with a function that explains", () => {
(window as any).jQuery = { fn: {} };
const error = vi.spyOn(console, "error").mockImplementation(() => {});
installModalFallback();

// Shiny's modal script: `$('#shiny-modal').modal().focus()`.
const $el = { focus: vi.fn() };
const out = (window as any).jQuery.fn.modal.call($el);

expect(out).toBe($el);
expect(error).toHaveBeenCalledWith(MODAL_FALLBACK_MESSAGE);
});

it("leaves Bootstrap's modal alone", () => {
const bootstrapModal = () => {};
(window as any).jQuery = { fn: { modal: bootstrapModal } };
installModalFallback();
expect((window as any).jQuery.fn.modal).toBe(bootstrapModal);
});

it("does nothing without jQuery", () => {
expect(() => installModalFallback()).not.toThrow();
expect((window as any).jQuery).toBeUndefined();
});

it("names both bookmark fixes", () => {
expect(MODAL_FALLBACK_MESSAGE).toContain("updateQueryString(url)");
expect(MODAL_FALLBACK_MESSAGE).toContain(
"session.bookmark.on_bookmarked(session.bookmark.update_query_string)",
);
});
});
2 changes: 2 additions & 0 deletions pkg-js/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import "./shinyreact.css"; // side-effect import is how Vite bundles CSS — no

import { installDepDiscovery } from "./dep-discovery";
import { installGlobal } from "./global";
import { installModalFallback } from "./modal-fallback";

installGlobal();
installDepDiscovery();
installModalFallback();
32 changes: 32 additions & 0 deletions pkg-js/src/modal-fallback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Explain the missing Bootstrap modal instead of letting Shiny throw.
*
* Shiny shows a modal by running `$('#shiny-modal').modal()` — Bootstrap's
* jQuery plugin. That covers `showModal()` / `modal_show()`, and the bookmark
* URL dialog `session$doBookmark()` / `session.bookmark()` falls back to when
* the app registered no `onBookmarked()` callback. `page_react()` loads no
* Bootstrap (#285), so the browser threw a bare `$(...).modal is not a
* function` (#326).
*
* Page scope: this writes to `jQuery.fn`, because Shiny's inline modal script
* calls the page's jQuery and nothing else can answer it. It only fills an
* empty slot, so Bootstrap already on the page, or a second copy of this
* bundle, is left alone; Bootstrap loaded later overwrites it.
*/
export const MODAL_FALLBACK_MESSAGE =
"[shinyreact] Shiny tried to open a Bootstrap modal, but this page has no " +
"Bootstrap. If you are bookmarking, register your own callback: " +
"onBookmarked(function(url) updateQueryString(url)) in R, or " +
"session.bookmark.on_bookmarked(session.bookmark.update_query_string) in " +
"Python. For showModal() / modal_show(), build the dialog in React instead.";

export function installModalFallback(): void {
if (typeof window === "undefined") return;
const jQuery = (window as { jQuery?: { fn?: Record<string, unknown> } })
.jQuery;
if (!jQuery?.fn || jQuery.fn.modal) return;
jQuery.fn.modal = function <T>(this: T): T {
console.error(MODAL_FALLBACK_MESSAGE);
return this;
};
}
4 changes: 4 additions & 0 deletions pkg-js/src/npm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import "./shinyreact.css";

import { installDepDiscovery } from "./dep-discovery";
import { installModalFallback } from "./modal-fallback";

// Two copies on one page: this app bundles `@posit-dev/shinyreact` AND the server
// served shinyreact.js, because the page entry point left `shinyreact_js` at its
Expand Down Expand Up @@ -67,6 +68,9 @@ if (
// dep-discovery.ts.
installDepDiscovery();

// Same as the IIFE bundle: explain a Shiny modal on a Bootstrap-free page.
installModalFallback();

export {
useSetShinyInput,
useShinyBusy,
Expand Down
6 changes: 6 additions & 0 deletions pkg-py/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@
IDs were found" warning grew and the console logged `Output <id> not found`
(#330).

* Bookmarking on a `page_react()` page needs an app-registered callback such as
`session.bookmark.on_bookmarked(session.bookmark.update_query_string)`. Without one, Shiny shows the bookmark URL in a Bootstrap modal, which
a page with no Bootstrap cannot open, so `session.bookmark()` failed with
`$(...).modal is not a function`. The browser console now logs a
`[shinyreact]` error naming the fix instead (#326).

## 0.1.0

* Initial PyPI release.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,9 @@ per-card state, because *any* output recomputing makes it `true`: use
`ReactApp(server, bookmark_store="url")`, `[r]` `enableBookmarking = "url"`
with a per-request UI function) and the client needs no code at all:
restored values seed `useShinyInput` initial values before the first paint.
The server **must** register an `onBookmarked()` / `on_bookmarked()` callback
(usually `updateQueryString()`): Shiny's default is a Bootstrap modal, which a
`page_react()` page cannot open.
See [`references/bookmarking.md`](references/bookmarking.md).

**Typed inputs** — `useShinyInput(id, default, { type: "shiny.datetime" })`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,26 @@ app = ReactApp(server, bookmark_store="url")
shinyApp(ui = function(req) page_react(), server, enableBookmarking = "url")
```

**Register an `on_bookmarked()` callback — this is required.** With none,
Shiny shows the bookmark URL in a Bootstrap modal, and `page_react()` loads no
Bootstrap, so the modal cannot open (the browser console logs a `[shinyreact]`
error saying so). Writing the URL to the address bar is the usual choice:

```python
# [py]
session.bookmark.on_bookmarked(session.bookmark.update_query_string)
```
```r
# [r] -- inside server()
onBookmarked(function(url) updateQueryString(url))
```

Or show the URL your own way — a React dialog fed by `send_message()`, a copy
button — from the same callback.

Trigger it from an action-button input (`[py]` `await session.bookmark()`,
`[r]` `session$doBookmark()`), which rewrites the browser URL. On a later visit to that URL the page entry point
`[r]` `session$doBookmark()`), which runs that callback. On a later visit to
that URL the page entry point
embeds the saved values in the page, and the client seeds `useShinyInput`
initial values from them **before the first paint** — so a bookmarked link
renders restored state directly, with no flash of the defaults and no
Expand Down
Loading
Loading