Skip to content

feat: add Try It button to CLI code examples#3380

Open
paoloredis wants to merge 6 commits into
mainfrom
DOC-6675
Open

feat: add Try It button to CLI code examples#3380
paoloredis wants to merge 6 commits into
mainfrom
DOC-6675

Conversation

@paoloredis
Copy link
Copy Markdown
Collaborator

@paoloredis paoloredis commented May 28, 2026

Adds a 'Try it' button to code examples that opens redis.io/cli with pre-populated commands and autorun enabled.

  • Extracts CLI commands from shortcode inner content (lines with '> ' or 'redis> ' prefix)
  • Renders a red 'Try it' button in the codetabs header
  • Button only visible when the Redis CLI tab is selected
  • Clicking opens https://redis.io/cli?commands=[...]&autorun=true in a new tab

Note

Low Risk
Docs-site UI and outbound links to redis.io/cli; no auth or data-store changes, though duplicated openTryItCli in the shortcode could drift from the shared implementation.

Overview
Adds a Try it control on multi-language code tabs and standalone redis-cli shortcodes so readers can open redis.io/cli with the example commands preloaded and autorun=true. Commands are taken from > / redis> lines in tabbed examples (or non-empty lines in the shortcode) and sent as URL-safe base64 JSON instead of raw query encoding to reduce WAF false positives.

The redis-cli tab in tabbed examples is no longer a static highlighted block: it renders an interactive form.redis-cli for inline execution via cli.js, which is now included on develop pages. cli.js also honors ?commands= + autorun=true on the current page. Copy-to-clipboard in codetabs reads data-cli-source when the visible panel is the interactive CLI. The Try it button is shown only when the redis-cli language tab is selected.

Reviewed by Cursor Bugbot for commit d69cbd1. Bugbot is set up for automated code reviews on this repo. Configure here.

Adds a 'Try it' button to code examples that opens redis.io/cli
with pre-populated commands and autorun enabled.

- Extracts CLI commands from shortcode inner content (lines with '> ' or 'redis> ' prefix)
- Renders a red 'Try it' button in the codetabs header
- Button only visible when the Redis CLI tab is selected
- Clicking opens https://redis.io/cli?commands=[...]&autorun=true in a new tab
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 28, 2026

DOC-6675

@jit-ci
Copy link
Copy Markdown

jit-ci Bot commented May 28, 2026

🛡️ Jit Security Scan Results

CRITICAL HIGH MEDIUM

✅ No security findings were detected in this PR


Security scan by Jit

The htmlEscape filter was applied on top of Hugo's automatic attribute
escaping, causing double-encoding (e.g. " instead of ").
This broke JSON.parse in the browser when clicking the Try It button.
Comment thread layouts/partials/tabs/wrapper.html Outdated
HTML data attributes with JSON values suffer from double-escaping issues
in Hugo (jsonify returns template.HTML, htmlEscape returns string which
Hugo then re-escapes). Moving the commands to a JavaScript object
(window._tryItCommands) populated via safeJS avoids all escaping issues.
Use printf with safeHTMLAttr to produce the complete attribute
key-value pair, preventing Hugo's contextual auto-escaping from
double-encoding the htmlEscape output. This matches the correct
Hugo pattern for embedding JSON in HTML attributes.
button.classList.remove('flex');
}
});
};
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing Try It button update in tab switching path

Medium Severity

The updatePanelVisibility function in codetabs.js calls window.updateAllCliOutputToggles() and window.updateAllBinderLinks() but not the new window.updateAllTryItButtons(). When codetabs.js restores a saved language preference from localStorage/URL during initialization, it calls updatePanelVisibility — which won't update Try It button visibility. The 100ms setTimeout in wrapper.html may fire before codetabs.js (which is deferred) runs, leaving the button in the wrong visibility state after the tab is restored.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit aac21dd. Configure here.

JSON-stringified commands produced repeated %5C%22 sequences in the URL after encodeURIComponent, which Cloudflare's managed SQLi/XSS-bypass rules flagged, returning a 'you have been blocked' page instead of the CLI.

Encode the JSON payload as URL-safe base64 (no padding) before placing it in the commands query parameter, and add a getCommandsFromUrl helper in cli.js that decodes the payload when autorun=true is set.
<a id="{{ $exampleId }}" class="relative"{{ if $description }} data-description="{{ $description | htmlEscape }}"{{ end }}{{ if $difficulty }} data-difficulty="{{ $difficulty | htmlEscape }}"{{ end }}{{ if $buildsUpon }} data-builds-upon="{{ delimit $buildsUpon "," }}"{{ end }} data-codetabs-id="{{ $id }}"></a>
{{- end -}}
<div class="codetabs cli group box-border rounded-lg mt-0 mb-0 mx-auto bg-slate-900" id="{{ $id }}" data-codetabs-meta="{{ $codetabsMetaJson | htmlEscape }}">
<div class="codetabs cli group box-border rounded-lg mt-0 mb-0 mx-auto bg-slate-900" id="{{ $id }}" data-codetabs-meta="{{ $codetabsMetaJson | htmlEscape }}"{{ if $tryItCommands }} {{ printf "data-tryit-commands=\"%s\"" ($tryItCommands | jsonify | htmlEscape) | safeHTMLAttr }}{{ end }}>
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unused data-tryit-commands HTML data attribute

Low Severity

The data-tryit-commands attribute is written to the HTML div but never read by any JavaScript on the page. The actual mechanism uses window._tryItCommands[codetabsId] (populated at line 486) and openTryItCli reads from that registry — not from the DOM attribute. This is unused/dead output that adds JSON payload bloat to every codetabs container with Try It commands.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit b1580b3. Configure here.

@paoloredis
Copy link
Copy Markdown
Collaborator Author

This change adds a Try it button for redis-cli commands, which when clicked launches redis.io/cli with the commands specific to the code block. What do you think?

https://redis.io/docs/staging/DOC-6675/develop/data-types/strings/#set_get?lang=redis-cli

@andy-stark-redis
Copy link
Copy Markdown
Contributor

@paoloredis It would definitely be useful to have a feature to run CLI examples like this. However, the commands don't seem to appear in the CLI page when you go to it (you get a working prompt, but it just doesn't seem to receive the commands in the example).

Also, we've already got those interactive CLIs that work within the page (eg, https://redis.io/docs/latest/commands/set/#examples). Is there a way we could incorporate those into the CLI tab so that the CLI example just works the same as the client lib examples?

@dwdougherty
Copy link
Copy Markdown
Collaborator

dwdougherty commented May 28, 2026

@paoloredis It would definitely be useful to have a feature to run CLI examples like this. However, the commands don't seem to appear in the CLI page when you go to it (you get a working prompt, but it just doesn't seem to receive the commands in the example).

I tried this example, https://redis.io/docs/staging/DOC-6675/commands/hset/#hset?lang=redis-cli, and I see the following output:

1:C 2026-05-28T13:45:04.464Z # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
1:C 2026-05-28T13:45:04.464Z # Configuration loaded
                  _._
            _.-``__ ''-._
      _.-``    `.  `_.  ''-._            Redis 8.8.0 (00000000/1) 64 bit
    .-`` .-```.  ```/    _.,_ ''-._
  (    '      ,       .-`  | `,    )     Running in standalone mode
  |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
  |    `-._   `._    /     _.-'    |     PID: 1
  `-._    `-._  `-./  _.-'    _.-'
  |`-._`-._    `-.__.-'    _.-'_.-'|
  |    `-._`-._        _.-'_.-'    |           https://redis.io
  `-._    `-._`-.__.-'_.-'    _.-'
  |`-._`-._    `-.__.-'    _.-'_.-'|
  |    `-._`-._        _.-'_.-'    |
  `-._    `-._`-.__.-'_.-'    _.-'
      `-._    `-.__.-'    _.-'
          `-._        _.-'
              `-.__.-'

1:M 2026-05-28T13:45:04.464Z # Server initialized
1:M 2026-05-28T13:45:04.464Z * Ready to accept connections
redis:6379> HSET myhash field1 "Hello"
(integer) 1
redis:6379> HGET myhash field1
"Hello"
redis:6379> HSET myhash field2 "Hi" field3 "World"
(integer) 2
redis:6379> HGET myhash field2
"Hi"
redis:6379> HGET myhash field3
"World"
redis:6379> HGETALL myhash
1) "field1"
2) "Hello"
3) "field2"
4) "Hi"
5) "field3"
6) "World"
redis:6379>

Also, we've already got those interactive CLIs that work within the page (eg, https://redis.io/docs/latest/commands/set/#examples). Is there a way we could incorporate those into the CLI tab so that the CLI example just works the same as the client lib examples?

We have both the TCE and CLI widget on some command pages, though we could certainly change that.

One other thought... a lot of examples aren't complete (for example, they rely on a dataset that might not be present in the fenced code block), so this can't really be global.

@andy-stark-redis
Copy link
Copy Markdown
Contributor

@dwdougherty Did you try that in a local build? Maybe it's just the staging that doesn't show the command correctly.

Also, regarding the missing dataset issue, maybe we could have hidden sections in the CLI text to set the data up? They wouldn't be shown in the page but still get run during an interactive session.

@dwdougherty
Copy link
Copy Markdown
Collaborator

dwdougherty commented May 28, 2026

@andy-stark-redis I forget to include the URL (I just added it to my comment). I used a staging link that @paoloredis gave to me in Slack.

Er... okay, it's there now. 🫠

@paoloredis
Copy link
Copy Markdown
Collaborator Author

@andy-stark-redis is it working for you now? so are you suggesting we make the redis cli examples in the tabbed code examples interactive, without the external button taking you to redis.io/cli ?

@andy-stark-redis
Copy link
Copy Markdown
Contributor

@andy-stark-redis is it working for you now?

Yes, the staging link works fine now, thanks.

so are you suggesting we make the redis cli examples in the tabbed code examples interactive, without the external button taking you to redis.io/cli ?

Yeah, I'm just thinking that the system we've got for the client examples where they can run in the page is really nice.
I guess the interactive CLIs we have on the command pages aren't exactly the same as this because they don't run the commands before your eyes (they just show results and let you type new stuff).

If the in-page client examples rely on a Jupyter kernel behind the scenes then I guess one (crazy) idea might be to implement our own Jupyter kernel for Redis CLI commands? Probably not all that far-fetched when we've got our AI friends to do the work :-)

Anyway, TBH, it's really good just to have the "Try it" button you've already implemented, so I'd certainly approve going ahead with that. I just thought I'd throw in a few ideas while we're thinking about it.

@andy-stark-redis
Copy link
Copy Markdown
Contributor

@paoloredis @dwdougherty OK, I've had Claude look into this and it turns out you can add new "magic" commands to a notebook quite easily (you start off with Python and register Python handlers for the commands). So, we could have essentially a Python notebook with something like this in the first cell:

%load_ext redis_magic
%redis_connect redis://localhost:6379
>>>     Connected to redis://localhost:6379

Then, in subsequent cells we would have:

%%redis
     SET user:1 "alice"
     SET user:2 "bob"
     HSET profile:1 name alice age 30
     HGETALL profile:1
     ──────
 >>> OK
     OK
     (integer) 2
     1) "name"
     2) "alice"
     3) "age"
     4) "30"

I don't know if this is more trouble than it's worth, but possibly worth exploring if it enables in-page examples for CLI?

- Render the redis-cli tab in clients-example blocks as an interactive
  form.redis-cli terminal instead of a static highlighted code block
- Load cli.js on develop single pages so the terminals initialize
- Guard codetabs copy button against interactive cli panels (no <code>),
  copying commands from data-cli-source instead
- Add Try It button to the redis-cli shortcode header bar
Copy link
Copy Markdown

@cursor cursor Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

There are 3 total unresolved issues (including 2 from previous reviews).

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit d69cbd1. Configure here.

Comment thread static/js/codetabs.js
}
return;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Try It button visibility not updated on URL navigation

Medium Severity

The updatePanelVisibility function in codetabs.js calls window.updateAllCliOutputToggles() and window.updateAllBinderLinks() but never calls window.updateAllTryItButtons(). When language is changed via applyLanguageFromUrl (triggered by hashchange, popstate, or URL polling), dropdown values are set programmatically without dispatching change events, so the wrapper.html event listener won't fire. This leaves the Try It button visible when a non-CLI language is active, or hidden when redis-cli becomes active through URL-based navigation.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit d69cbd1. Configure here.

@paoloredis
Copy link
Copy Markdown
Collaborator Author

@andy-stark-redis @dwdougherty I've now modified the tabbed code examples so that redis-cli code is executable. What do you think? This means that some pages like redis.io/docs/commands/hget/ will need to be updated to only include the tabbed code example. With this feature should we keep the "Try it" button or maybe not?

@andy-stark-redis
Copy link
Copy Markdown
Contributor

@andy-stark-redis @dwdougherty I've now modified the tabbed code examples so that redis-cli code is executable. What do you think?

That's basically what I was thinking of. I'd say that looks really neat now :-)

With this feature should we keep the "Try it" button or maybe not?

If we go ahead with the notebooks then maybe it could just say "Run in browser" like the others? I guess having links to redis.io/cli is a good idea though, since it's a nice feature. Maybe we could have a link in the footer? ("Try online or check out our other client tools...")

@paoloredis
Copy link
Copy Markdown
Collaborator Author

To be honest I'm not really sure I see the point in having a jupyter notebook for the redis cli commands.
What if we keep the "Try it" button for the redis-cli and we change the "Run in browser" jupyter links to use the same "Try it" button? To have some consistency

@dwdougherty
Copy link
Copy Markdown
Collaborator

dwdougherty commented May 29, 2026

@andy-stark-redis, @paoloredis: do you want me to go ahead and remove the CLI widget from pages that also have TCEs? It's only a handful of command pages:

AUTH,DEL,EXISTS,EXPIRE,FLUSHALL,GET,HDEL,HEXPIRE,HGET,HGETALL,HMGET,HSET,HVALS,INCR,INFO,KEYS,LLEN,LPOP,LPUSH,LRANGE,MGET,RPOP,RPUSH,SADD,SCAN,SET,SMEMBERS,TTL,XADD,ZADD,ZRANGE

@andy-stark-redis
Copy link
Copy Markdown
Contributor

@andy-stark-redis, @paoloredis: do you want me to go ahead and remove the CLI widget from pages that also have TCEs? It's only a handful of command pages...

I think the CLI widgets sometimes have different commands from the ones used in the nearby TCEs (eg, here)? The TCEs don't have Redis CLI tabs in those cases, so you'd need to create a new CLI example corresponding to the client code. So, only a handful of pages but maybe a big-ish job. However, if you're up for it then I think it would tidy those pages up very nicely.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants