ray-so-code-snippet

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

ray.so Code Snippet Image Generator

ray.so 代码片段图片生成工具

Generate beautiful code snippet images using ray.so and save them locally.
使用ray.so生成精美的代码片段图片并保存到本地。

Requirements

要求

  • The user MUST provide the code snippet, either directly or by pointing to a file/selection in context
  • MUST ask the user for ALL styling parameters before generating, presenting ALL available options
  • MUST use
    agent-browser
    for screenshot capture (check availability first)
  • 用户必须提供代码片段,可以直接提供,也可以通过上下文指向文件/选中的内容
  • 生成前必须向用户询问所有样式参数,并展示所有可用选项
  • 必须使用
    agent-browser
    进行截图捕获(首先检查是否可用)

Workflow

工作流程

Step 1: Verify agent-browser Availability

步骤1:验证agent-browser是否可用

Before proceeding, verify that
agent-browser
is available:
bash
which agent-browser
If
agent-browser
is not found in the PATH, inform the user that this skill requires agent-browser and cannot proceed without it.
在开始前,验证
agent-browser
是否可用:
bash
which agent-browser
如果在PATH中未找到
agent-browser
,请告知用户此技能需要agent-browser,没有它无法继续。

Step 2: Fetch Available Options

步骤2:获取可用选项

Fetch the current themes and languages from ray.so's GitHub repository using curl:
bash
undefined
使用curl从ray.so的GitHub仓库获取当前的主题和语言:
bash
undefined

Fetch and parse available themes

获取并解析可用主题

curl -s "https://raw.githubusercontent.com/raycast/ray-so/main/app/(navigation)/(code)/store/themes.ts" | grep -oE 'id:\s*"[^"]+"' | sed 's/id:\s*"//;s/"//' | sort -u
curl -s "https://raw.githubusercontent.com/raycast/ray-so/main/app/(navigation)/(code)/store/themes.ts" | grep -oE 'id:\s*"[^"]+"' | sed 's/id:\s*"//;s/"//' | sort -u

Fetch and parse available languages

获取并解析可用语言

curl -s "https://raw.githubusercontent.com/raycast/ray-so/main/app/(navigation)/(code)/util/languages.ts" | grep -oE '^[[:space:]]"?[a-zA-Z0-9+#-]+"?\s:\s*{' | sed 's/[[:space:]]"//g;s/".//;s/:.*//' | sort -u
undefined
curl -s "https://raw.githubusercontent.com/raycast/ray-so/main/app/(navigation)/(code)/util/languages.ts" | grep -oE '^[[:space:]]"?[a-zA-Z0-9+#-]+"?\s:\s*{' | sed 's/[[:space:]]"//g;s/".//;s/:.*//' | sort -u
undefined

Step 3: Ask User for ALL Parameters

步骤3:向用户询问所有参数

MUST use AskUserQuestion to ask for EVERY parameter, presenting ALL available options. Ask for parameters in this order:
必须使用AskUserQuestion询问每一个参数,并展示所有可用选项。按以下顺序询问参数:

3.1 Theme Selection

3.1 主题选择

Present ALL available themes. In the question, list every theme fetched from step 2. Example:
Question: "Which theme would you like?"
Description: "Available themes: [list ALL themes from curl output]"
Options (pick 4 popular ones for quick select):
- breeze (default, purple gradient)
- midnight (cyan-blue)
- vercel (minimalist dark)
- sunset (warm orange)
Note: User can select "Other" to type any theme from the full list
展示所有可用主题。在问题中列出步骤2获取的所有主题。示例:
问题:"你想要使用哪个主题?"
说明:"可用主题:[列出curl输出的所有主题]"
快速选择选项(挑选4个热门主题):
- breeze(默认,紫色渐变)
- midnight(青蓝色)
- vercel(极简深色)
- sunset(暖橙色)
注意:用户可以选择“其他”来输入完整列表中的任意主题

3.2 Language Selection

3.2 语言选择

Infer the language when possible. Skip this question if:
  • The user explicitly specified a language
  • The code comes from a file with a clear extension (e.g.,
    .py
    → python,
    .js
    → javascript,
    .ts
    → typescript,
    .rs
    → rust,
    .go
    → go, etc.)
  • The syntax is unmistakably identifiable (e.g.,
    def
    /
    import
    → python,
    func
    /
    package
    → go,
    fn
    /
    let mut
    → rust)
Only ask this question if the language cannot be confidently inferred:
Question: "Which language for syntax highlighting?"
Description: "Available languages: [list ALL languages from curl output]"
Options:
- auto (auto-detect)
- javascript
- python
- typescript
Note: User can select "Other" to type any language from the full list
尽可能推断语言。 在以下情况跳过此问题:
  • 用户明确指定了语言
  • 代码来自带有明确扩展名的文件(例如
    .py
    →python,
    .js
    →javascript,
    .ts
    →typescript,
    .rs
    →rust,
    .go
    →go等)
  • 语法具有明确辨识度(例如
    def
    /
    import
    →python,
    func
    /
    package
    →go,
    fn
    /
    let mut
    →rust)
仅当无法可靠推断语言时才询问此问题:
问题:"使用哪种语言进行语法高亮?"
说明:"可用语言:[列出curl输出的所有语言]"
选项:
- auto(自动检测)
- javascript
- python
- typescript
注意:用户可以选择“其他”来输入完整列表中的任意语言

3.3 Dark/Light Mode

3.3 深色/浅色模式

Question: "Dark or light mode?"
Options:
- Dark mode (default)
- Light mode
问题:"深色模式还是浅色模式?"
选项:
- 深色模式(默认)
- 浅色模式

3.4 Background

3.4 背景

Question: "Show the gradient background?"
Options:
- Yes, show background (default)
- No, transparent/minimal background
问题:"显示渐变背景吗?"
选项:
- 是,显示背景(默认)
- 否,透明/极简背景

3.5 Padding

3.5 内边距

Question: "How much padding around the code?"
Options:
- 16 (compact)
- 32 (small)
- 64 (medium, default)
- 128 (large)
问题:"代码周围的内边距设置为多少?"
选项:
- 16(紧凑)
- 32(小)
- 64(中等,默认)
- 128(大)

3.6 Line Numbers

3.6 行号

Question: "Show line numbers?"
Options:
- No (default)
- Yes
问题:"显示行号吗?"
选项:
- 不显示(默认)
- 显示

3.7 Title

3.7 标题

Question: "Add a title above the code? (e.g., filename)"
Options:
- No title (default)
- Yes, add title
If yes, ask for the title text.
Note: Do NOT ask about output path/filename. Save to the current working directory with a sensible filename (e.g.,
rayso-snippet.png
, or based on the title if provided like
fibonacci.png
). Only use a different path if the user explicitly specifies one in their original request.
问题:"在代码上方添加标题吗?(例如文件名)"
选项:
- 不添加标题(默认)
- 是,添加标题
如果选择是,询问标题文本。
注意:不要询问输出路径/文件名。将图片保存到当前工作目录,使用合理的文件名(例如
rayso-snippet.png
,如果提供了标题则使用类似
fibonacci.png
的名称)。仅当用户在原始请求中明确指定时才使用其他路径。

Step 4: Build the ray.so URL

步骤4:构建ray.so链接

CRITICAL: ALL parameters must be in the URL hash (after #), NOT in the query string.
Build the URL using shell commands:
bash
undefined
重要:所有参数必须放在URL的哈希部分(#之后),而不是查询字符串中。
使用shell命令构建链接:
bash
undefined

1. Base64 encode the code

1. 对代码进行Base64编码

CODE_BASE64=$(echo -n 'YOUR_CODE_HERE' | base64)
CODE_BASE64=$(echo -n 'YOUR_CODE_HERE' | base64)

2. URL encode the base64 string

2. 对Base64字符串进行URL编码

CODE_ENCODED=$(python3 -c "import urllib.parse; print(urllib.parse.quote('$CODE_BASE64'))")
CODE_ENCODED=$(python3 -c "import urllib.parse; print(urllib.parse.quote('$CODE_BASE64'))")

3. Build the URL with ALL parameters in the hash

3. 构建包含所有参数的哈希部分的链接

Do NOT include width parameter - let ray.so auto-size to fit content

不要包含width参数 - 让ray.so自动调整大小以适配内容

Add optional parameters if needed:

如果需要,添加可选参数:

If lineNumbers: add "&lineNumbers=true" before &code=

如果显示行号:在&code=之前添加"&lineNumbers=true"

If title: add "&title=URL_ENCODED_TITLE" before &code=

如果有标题:在&code=之前添加"&title=URL_ENCODED_TITLE"


**URL Hash Parameters:**
| Parameter | Values | Default |
|-----------|--------|---------|
| theme | Any theme from list | breeze |
| padding | 16, 32, 64, 128 | 64 |
| background | true, false | true |
| darkMode | true, false | true |
| language | Any language from list, or "auto" | auto |
| lineNumbers | true, false | false |
| title | URL-encoded string | (none) |
| width | Number (pixels) | auto |
| code | Base64-encoded, then URL-encoded | (required) |

**Note on width:** Do NOT include the `width` parameter unless you specifically need a fixed width. Without it, ray.so auto-sizes the frame to fit the code content, avoiding unnecessary empty space.

**Example URL construction:**
```bash

**URL哈希参数:**
| 参数 | 取值 | 默认值 |
|-----------|--------|---------|
| theme | 列表中的任意主题 | breeze |
| padding | 16, 32, 64, 128 | 64 |
| background | true, false | true |
| darkMode | true, false | true |
| language | 列表中的任意语言,或"auto" | auto |
| lineNumbers | true, false | false |
| title | URL编码的字符串 | (无) |
| width | 数字(像素) | auto |
| code | Base64编码后再进行URL编码 | (必填) |

**关于width的注意事项:** 除非你需要固定宽度,否则不要包含`width`参数。不添加此参数时,ray.so会自动调整框架大小以适配代码内容,避免不必要的空白。

**链接构建示例:**
```bash

For code: for i in range(23):\n print(i)

代码:for i in range(23):\n print(i)

Theme: midnight, Padding: 64, Dark mode: true, Background: true, Language: python, Title: test.py

主题:midnight,内边距:64,深色模式:开启,背景:开启,语言:python,标题:test.py

CODE='for i in range(23): print(i)' CODE_BASE64=$(echo -n "$CODE" | base64) CODE_ENCODED=$(python3 -c "import urllib.parse; print(urllib.parse.quote('$CODE_BASE64'))") TITLE_ENCODED=$(python3 -c "import urllib.parse; print(urllib.parse.quote('test.py'))") URL="https://ray.so/#theme=midnight&padding=64&background=true&darkMode=true&language=python&title=${TITLE_ENCODED}&code=${CODE_ENCODED}" echo "$URL"
undefined
CODE='for i in range(23): print(i)' CODE_BASE64=$(echo -n "$CODE" | base64) CODE_ENCODED=$(python3 -c "import urllib.parse; print(urllib.parse.quote('$CODE_BASE64'))") TITLE_ENCODED=$(python3 -c "import urllib.parse; print(urllib.parse.quote('test.py'))") URL="https://ray.so/#theme=midnight&padding=64&background=true&darkMode=true&language=python&title=${TITLE_ENCODED}&code=${CODE_ENCODED}" echo "$URL"
undefined

Step 5: Capture High-Quality Image with agent-browser

步骤5:使用agent-browser捕获高质量图片

MUST use agent-browser (verified in Step 1). This approach uses the
html-to-image
library (same as ray.so's internal export) with high pixelRatio for crisp, sharp text rendering.
IMPORTANT: Always use a unique session name with
--session
to avoid stale session issues.
bash
undefined
必须使用agent-browser(步骤1已验证)。此方法使用
html-to-image
库(与ray.so内部导出使用的库相同),并设置高pixelRatio以获得清晰锐利的文本渲染效果。
重要提示: 始终使用
--session
参数指定唯一的会话名称,以避免会话过期问题。
bash
undefined

Generate unique session name

生成唯一会话名称

SESSION="rayso-$(date +%s)"
SESSION="rayso-$(date +%s)"

1. Set viewport

1. 设置视口

agent-browser --session $SESSION set viewport 1400 900
agent-browser --session $SESSION set viewport 1400 900

2. Open the URL

2. 打开链接

agent-browser --session $SESSION open "$URL"
agent-browser --session $SESSION open "$URL"

3. Wait for the page to fully render

3. 等待页面完全渲染

agent-browser --session $SESSION wait --load networkidle agent-browser --session $SESSION wait 3000
agent-browser --session $SESSION wait --load networkidle agent-browser --session $SESSION wait 3000

4. Load html-to-image library (same library ray.so uses internally)

加载html-to-image库(与ray.so内部使用的库相同)

agent-browser --session $SESSION eval 'new Promise((r,e)=>{const s=document.createElement("script");s.src="https://cdn.jsdelivr.net/npm/html-to-image@1.11.11/dist/html-to-image.js";s.onload=r;s.onerror=e;document.head.appendChild(s)})'
agent-browser --session $SESSION eval 'new Promise((r,e)=>{const s=document.createElement("script");s.src="https://cdn.jsdelivr.net/npm/html-to-image@1.11.11/dist/html-to-image.js";s.onload=r;s.onerror=e;document.head.appendChild(s)})'

5. Capture at 4x resolution using html-to-image (produces crisp text)

4. 使用html-to-image以4倍分辨率捕获(生成清晰文本)

agent-browser --session $SESSION eval 'htmlToImage.toPng(document.querySelector("#frame > div"),{pixelRatio:4,skipAutoScale:true})' > /tmp/rayso-dataurl-$SESSION.txt
agent-browser --session $SESSION eval 'htmlToImage.toPng(document.querySelector("#frame > div"),{pixelRatio:4,skipAutoScale:true})' > /tmp/rayso-dataurl-$SESSION.txt

6. Close the browser

5. 关闭浏览器

agent-browser --session $SESSION close
agent-browser --session $SESSION close

7. Convert data URL to PNG file

6. 将数据URL转换为PNG文件

DATAURL=$(cat /tmp/rayso-dataurl-$SESSION.txt | tr -d '"' | tr -d '\n') echo "$DATAURL" | sed 's/data:image/png;base64,//' | base64 -d > /path/to/output.png
DATAURL=$(cat /tmp/rayso-dataurl-$SESSION.txt | tr -d '"' | tr -d '\n') echo "$DATAURL" | sed 's/data:image/png;base64,//' | base64 -d > /path/to/output.png

8. Clean up temp file

7. 清理临时文件

rm /tmp/rayso-dataurl-$SESSION.txt

**Critical notes:**
- Uses `html-to-image` library which is what ray.so uses for its own export feature
- `pixelRatio: 4` produces high-DPI images with crisp, sharp text (4x native resolution)
- The data URL is captured directly from the library, not from a screenshot
- No ImageMagick required - pure browser-based rendering at high resolution
- Output is correctly sized with no extra whitespace
rm /tmp/rayso-dataurl-$SESSION.txt

**重要注意事项:**
- 使用`html-to-image`库,这是ray.so自身导出功能使用的库
- `pixelRatio: 4`生成高DPI图片,文本清晰锐利(4倍原生分辨率)
- 直接从库中捕获数据URL,而不是从截图中获取
- 不需要ImageMagick - 纯基于浏览器的高分辨率渲染
- 输出尺寸正确,无额外空白

Step 6: Confirm Output and STOP

步骤6:确认输出并结束

Report the saved file location to the user. The task is complete - do not perform any additional checks, explorations, or verifications after the screenshot is saved.
向用户报告保存的文件位置。任务完成 - 截图保存后不要执行任何额外的检查、探索或验证操作。

Complete Example

完整示例

User: "Create a code snippet image of this Python function"
python
def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)
  1. Check
    which agent-browser
    - confirmed available
  2. Fetch themes and languages:
bash
curl -s "https://raw.githubusercontent.com/raycast/ray-so/main/app/(navigation)/(code)/store/themes.ts" | grep -oE 'id:\s*"[^"]+"' | sed 's/id:\s*"//;s/"//' | sort -u
  1. Ask user for parameters via AskUserQuestion:
    • Theme: user selects "midnight"
    • Language: inferred as python from
      def
      syntax - not asked
    • Dark mode: user selects "Dark mode"
    • Background: user selects "Yes"
    • Padding: user selects "64"
    • Line numbers: user selects "No"
    • Title: user selects "No title"
  2. Build URL (all params in hash, no width for auto-sizing):
bash
CODE='def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)'
CODE_BASE64=$(echo -n "$CODE" | base64)
CODE_ENCODED=$(python3 -c "import urllib.parse; print(urllib.parse.quote('$CODE_BASE64'))")
URL="https://ray.so/#theme=midnight&padding=64&background=true&darkMode=true&language=python&code=${CODE_ENCODED}"
  1. Capture high-quality image:
bash
SESSION="rayso-$(date +%s)"

agent-browser --session $SESSION set viewport 1400 900
agent-browser --session $SESSION open "$URL"
agent-browser --session $SESSION wait --load networkidle
agent-browser --session $SESSION wait 3000
用户:"创建这个Python函数的代码片段图片"
python
def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)
  1. 执行
    which agent-browser
    - 确认可用
  2. 获取主题和语言:
bash
curl -s "https://raw.githubusercontent.com/raycast/ray-so/main/app/(navigation)/(code)/store/themes.ts" | grep -oE 'id:\s*"[^"]+"' | sed 's/id:\s*"//;s/"//' | sort -u
  1. 通过AskUserQuestion向用户询问参数:
    • 主题:用户选择"midnight"
    • 语言:
      def
      语法推断为python - 无需询问
    • 深色模式:用户选择"深色模式"
    • 背景:用户选择"是"
    • 内边距:用户选择"64"
    • 行号:用户选择"不显示"
    • 标题:用户选择"不添加标题"
  2. 构建链接(所有参数在哈希部分,不添加width参数以自动调整大小):
bash
CODE='def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)'
CODE_BASE64=$(echo -n "$CODE" | base64)
CODE_ENCODED=$(python3 -c "import urllib.parse; print(urllib.parse.quote('$CODE_BASE64'))")
URL="https://ray.so/#theme=midnight&padding=64&background=true&darkMode=true&language=python&code=${CODE_ENCODED}"
  1. 捕获高质量图片:
bash
SESSION="rayso-$(date +%s)"

agent-browser --session $SESSION set viewport 1400 900
agent-browser --session $SESSION open "$URL"
agent-browser --session $SESSION wait --load networkidle
agent-browser --session $SESSION wait 3000

Load html-to-image library

加载html-to-image库

agent-browser --session $SESSION eval 'new Promise((r,e)=>{const s=document.createElement("script");s.src="https://cdn.jsdelivr.net/npm/html-to-image@1.11.11/dist/html-to-image.js";s.onload=r;s.onerror=e;document.head.appendChild(s)})'
agent-browser --session $SESSION eval 'new Promise((r,e)=>{const s=document.createElement("script");s.src="https://cdn.jsdelivr.net/npm/html-to-image@1.11.11/dist/html-to-image.js";s.onload=r;s.onerror=e;document.head.appendChild(s)})'

Capture at 4x resolution

以4倍分辨率捕获

agent-browser --session $SESSION eval 'htmlToImage.toPng(document.querySelector("#frame > div"),{pixelRatio:4,skipAutoScale:true})' > /tmp/rayso-dataurl-$SESSION.txt agent-browser --session $SESSION close
agent-browser --session $SESSION eval 'htmlToImage.toPng(document.querySelector("#frame > div"),{pixelRatio:4,skipAutoScale:true})' > /tmp/rayso-dataurl-$SESSION.txt agent-browser --session $SESSION close

Save as PNG

保存为PNG

DATAURL=$(cat /tmp/rayso-dataurl-$SESSION.txt | tr -d '"' | tr -d '\n') echo "$DATAURL" | sed 's/data:image/png;base64,//' | base64 -d > ./fibonacci.png rm /tmp/rayso-dataurl-$SESSION.txt

6. Report: "Saved code snippet image to ./fibonacci.png"
DATAURL=$(cat /tmp/rayso-dataurl-$SESSION.txt | tr -d '"' | tr -d '\n') echo "$DATAURL" | sed 's/data:image/png;base64,//' | base64 -d > ./fibonacci.png rm /tmp/rayso-dataurl-$SESSION.txt

6. 报告:"代码片段图片已保存到./fibonacci.png"

Image Resolution and Quality

图片分辨率与质量

This skill uses the
html-to-image
library with
pixelRatio: 4
to produce high-quality images with crisp, sharp text. This is the same rendering approach that ray.so uses for its built-in export feature.
Output quality:
  • Default: 4x native resolution (frame auto-sizes to content, then rendered at 4x)
  • Text is rendered at high DPI, not upscaled from low resolution
  • Gradient backgrounds and all CSS styling are preserved
  • No unnecessary empty space (frame auto-sizes to fit code)
Adjusting resolution:
  • For smaller files: Change
    pixelRatio:4
    to
    pixelRatio:2
    in the eval command
  • For maximum quality: Use
    pixelRatio:6
    (same as ray.so's "6x" export option)
Forcing a specific width:
  • Only add
    &width=NUMBER
    to the URL if you need a fixed width (e.g., for consistent sizing across multiple images)
此技能使用
html-to-image
库并设置
pixelRatio: 4
来生成高质量、文本清晰锐利的图片。这与ray.so内置导出功能使用的渲染方式相同。
输出质量:
  • 默认:4倍原生分辨率(框架自动调整大小以适配内容,然后以4倍分辨率渲染)
  • 文本以高DPI渲染,而非从低分辨率放大
  • 渐变背景和所有CSS样式均被保留
  • 无不必要的空白(框架自动调整大小以适配代码)
调整分辨率:
  • 如需更小的文件:在eval命令中将
    pixelRatio:4
    改为
    pixelRatio:2
  • 如需最高质量:使用
    pixelRatio:6
    (与ray.so的“6x”导出选项相同)
强制固定宽度:
  • 仅当需要固定宽度时才在URL中添加
    &width=NUMBER
    (例如,为了保持多张图片尺寸一致)

Troubleshooting

故障排除

  • If agent-browser is not available: Inform the user and do not proceed
  • If curl fails to fetch themes/languages, use these common defaults:
    • Themes: breeze, midnight, candy, crimson, falcon, meadow, raindrop, sunset, vercel, supabase, tailwind
    • Languages: auto, javascript, typescript, python, rust, go, java, ruby, swift, kotlin, css, html, json, yaml, bash
  • If parameters aren't applied: Ensure ALL parameters are in the URL hash (after #), not the query string
  • If title isn't showing: The title parameter must be in the hash:
    #title=filename.py&code=...
  • If html-to-image fails to load: Check network connectivity; the library loads from jsdelivr CDN
  • If capture returns empty: The frame selector
    #frame > div
    may have changed; inspect the page structure
  • For very long code snippets, ray.so may truncate; consider splitting into multiple images
  • If the page doesn't load properly, increase the wait time (try 4000ms or more)
  • If you get a blank page: Use a fresh unique session name with
    --session
    flag
  • If data URL is malformed: Ensure quotes and newlines are stripped before base64 decoding
  • 如果agent-browser不可用: 告知用户此技能需要agent-browser,无法继续
  • 如果curl获取主题/语言失败,使用以下常用默认值:
    • 主题:breeze, midnight, candy, crimson, falcon, meadow, raindrop, sunset, vercel, supabase, tailwind
    • 语言:auto, javascript, typescript, python, rust, go, java, ruby, swift, kotlin, css, html, json, yaml, bash
  • 如果参数未生效: 确保所有参数都在URL的哈希部分(#之后),而非查询字符串中
  • 如果标题未显示: 标题参数必须在哈希部分:
    #title=filename.py&code=...
  • 如果html-to-image加载失败: 检查网络连接;该库从jsdelivr CDN加载
  • 如果捕获返回空内容: 框架选择器
    #frame > div
    可能已更改;检查页面结构
  • 对于非常长的代码片段,ray.so可能会截断;考虑拆分为多张图片
  • 如果页面加载不正常,增加等待时间(尝试4000ms或更长)
  • 如果出现空白页面: 使用
    --session
    标志指定新的唯一会话名称
  • 如果数据URL格式错误: 确保在Base64解码前去除引号和换行符