Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b69a90501d | ||
|
|
7ff881f506 | ||
|
|
9acbe10986 | ||
|
|
81989a26d7 | ||
|
|
cf0ba6dccd | ||
|
|
0de703f86a | ||
|
|
4907f92d84 | ||
|
|
eac6921524 |
No files matched your search
@@ -0,0 +1,48 @@
|
|||||||
|
name: capture-procurement-marketing-assets
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [docs/executable-skill-showcase-271]
|
||||||
|
paths:
|
||||||
|
- "scripts/capture-procurement-showcase.py"
|
||||||
|
- ".github/workflows/capture-procurement-marketing.yml"
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
capture:
|
||||||
|
if: github.ref_name == 'docs/executable-skill-showcase-271'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
persist-credentials: true
|
||||||
|
- uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: "3.11"
|
||||||
|
- name: Prepare Chrome, Chinese fonts and Python imaging
|
||||||
|
run: |
|
||||||
|
python -m pip install --quiet pillow selenium
|
||||||
|
sudo apt-get update -qq
|
||||||
|
sudo apt-get install -y -qq fonts-noto-cjk
|
||||||
|
google-chrome --version
|
||||||
|
- name: Download Marqdo v2.7.1 Linux release
|
||||||
|
run: |
|
||||||
|
mkdir -p /tmp/marqdo-marketing-cli
|
||||||
|
curl -fL --retry 3 "https://github.com/cflmy/marqdo/releases/download/v2.7.1/marqdo-2.7.1-x86_64-unknown-linux-gnu.zip" -o /tmp/marqdo-marketing.zip
|
||||||
|
unzip -q /tmp/marqdo-marketing.zip -d /tmp/marqdo-marketing-cli
|
||||||
|
BIN="$(find /tmp/marqdo-marketing-cli -type f -name marqdo | head -n 1)"
|
||||||
|
test -n "$BIN"
|
||||||
|
chmod +x "$BIN"
|
||||||
|
echo "CLI_BIN=$BIN" >> "$GITHUB_ENV"
|
||||||
|
- name: Record real command outputs and capture real View
|
||||||
|
run: python scripts/capture-procurement-showcase.py --cli "$CLI_BIN"
|
||||||
|
- name: Commit reproducible promotional assets
|
||||||
|
run: |
|
||||||
|
git config user.name "github-actions[bot]"
|
||||||
|
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||||
|
git add assets/marketing/procurement-cli.gif assets/marketing/procurement-view.png
|
||||||
|
git diff --cached --quiet || git commit -m "docs: capture live procurement CLI GIF and View screenshot"
|
||||||
|
git push origin HEAD:docs/executable-skill-showcase-271
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
name: procurement-example-smoke
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main, docs/executable-skill-showcase-271]
|
||||||
|
paths: ["examples/procurement/**", ".github/workflows/procurement-example.yml"]
|
||||||
|
pull_request:
|
||||||
|
paths: ["examples/procurement/**", ".github/workflows/procurement-example.yml"]
|
||||||
|
jobs:
|
||||||
|
smoke:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Fetch released v2.7.1 Linux CLI
|
||||||
|
run: |
|
||||||
|
curl -fL --retry 3 "https://github.com/cflmy/marqdo/releases/download/v2.7.1/marqdo-2.7.1-x86_64-unknown-linux-gnu.zip" -o /tmp/marqdo.zip
|
||||||
|
unzip -q /tmp/marqdo.zip -d /tmp
|
||||||
|
BIN="$(find /tmp -type f -name marqdo | head -n 1)"
|
||||||
|
test -n "$BIN"
|
||||||
|
chmod +x "$BIN"
|
||||||
|
echo "CLI_BIN=$BIN" >> "$GITHUB_ENV"
|
||||||
|
- name: Check and run procurement skill
|
||||||
|
run: |
|
||||||
|
"$CLI_BIN" check examples/procurement/index.mq.md
|
||||||
|
"$CLI_BIN" call examples/procurement/index.mq.md 查询余额 已花费=120 --json
|
||||||
|
"$CLI_BIN" call examples/procurement/index.mq.md 向采购商发工单 "采购商标识符='SUP_JN'" 数量=8 单价=36 已花费=120 交付要求天数=7 --effects time.read,process.control --json | tee /tmp/allowed.json
|
||||||
|
"$CLI_BIN" call examples/procurement/index.mq.md 向采购商发工单 "采购商标识符='SUP_JN'" 数量=8 单价=36 已花费=360 交付要求天数=7 --effects time.read,process.control --json | tee /tmp/denied.json
|
||||||
|
grep -q '本地模拟' /tmp/allowed.json
|
||||||
|
grep -q '采购金额超过' /tmp/denied.json
|
||||||
@@ -118,6 +118,7 @@ jobs:
|
|||||||
echo "VSIX=$vsix" >> $env:GITHUB_ENV
|
echo "VSIX=$vsix" >> $env:GITHUB_ENV
|
||||||
echo "SOURCE=$source" >> $env:GITHUB_ENV
|
echo "SOURCE=$source" >> $env:GITHUB_ENV
|
||||||
echo "PUBLIC=$public" >> $env:GITHUB_ENV
|
echo "PUBLIC=$public" >> $env:GITHUB_ENV
|
||||||
|
echo "PUBLISH_EXT=$((Get-Content ext/VERSION -Raw).Trim() -eq $ver)" >> $env:GITHUB_ENV
|
||||||
echo "EXT=$extZip" >> $env:GITHUB_ENV
|
echo "EXT=$extZip" >> $env:GITHUB_ENV
|
||||||
echo "NATIVE=$nativeZip" >> $env:GITHUB_ENV
|
echo "NATIVE=$nativeZip" >> $env:GITHUB_ENV
|
||||||
|
|
||||||
@@ -129,8 +130,6 @@ jobs:
|
|||||||
dist/${{ env.EXE }}
|
dist/${{ env.EXE }}
|
||||||
dist/${{ env.ZIP }}
|
dist/${{ env.ZIP }}
|
||||||
dist/${{ env.STDLIB }}
|
dist/${{ env.STDLIB }}
|
||||||
dist/${{ env.EXT }}
|
|
||||||
dist/${{ env.NATIVE }}
|
|
||||||
dist/${{ env.VSIX }}
|
dist/${{ env.VSIX }}
|
||||||
dist/${{ env.SOURCE }}
|
dist/${{ env.SOURCE }}
|
||||||
dist/${{ env.PUBLIC }}
|
dist/${{ env.PUBLIC }}
|
||||||
@@ -138,6 +137,17 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Upload independently versioned extension assets
|
||||||
|
if: env.PUBLISH_EXT == 'True'
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
with:
|
||||||
|
files: |
|
||||||
|
dist/${{ env.EXT }}
|
||||||
|
dist/${{ env.NATIVE }}
|
||||||
|
fail_on_unmatched_files: true
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
linux:
|
linux:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
# Wait until Windows has created the GitHub Release, then attach Linux zips
|
# Wait until Windows has created the GitHub Release, then attach Linux zips
|
||||||
@@ -169,6 +179,9 @@ jobs:
|
|||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
VER="${GITHUB_REF_NAME#v}"
|
VER="${GITHUB_REF_NAME#v}"
|
||||||
TARGET="x86_64-unknown-linux-gnu"
|
TARGET="x86_64-unknown-linux-gnu"
|
||||||
|
if [[ "$(tr -d '[:space:]' < ext/VERSION)" == "$VER" ]]; then
|
||||||
|
echo "PUBLISH_EXT=true" >> "$GITHUB_ENV"
|
||||||
|
fi
|
||||||
mkdir -p dist/stage-native/native
|
mkdir -p dist/stage-native/native
|
||||||
for lib in libweb.so libagent.so libquantum.so liblinalg.so libllm.so libengineering.so; do
|
for lib in libweb.so libagent.so libquantum.so liblinalg.so libllm.so libengineering.so; do
|
||||||
src="target/release/${lib}"
|
src="target/release/${lib}"
|
||||||
@@ -197,8 +210,16 @@ jobs:
|
|||||||
uses: softprops/action-gh-release@v2
|
uses: softprops/action-gh-release@v2
|
||||||
with:
|
with:
|
||||||
files: |
|
files: |
|
||||||
dist/${{ env.NATIVE }}
|
|
||||||
dist/${{ env.LINUX_ZIP }}
|
dist/${{ env.LINUX_ZIP }}
|
||||||
fail_on_unmatched_files: true
|
fail_on_unmatched_files: true
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Upload independently versioned Linux native pack
|
||||||
|
if: env.PUBLISH_EXT == 'true'
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
with:
|
||||||
|
files: dist/${{ env.NATIVE }}
|
||||||
|
fail_on_unmatched_files: true
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
@@ -2,6 +2,14 @@
|
|||||||
|
|
||||||
## Unreleased
|
## Unreleased
|
||||||
|
|
||||||
|
## v2.7.1 — 2026-11-11
|
||||||
|
|
||||||
|
CLI 修复发布:View 实际逻辑的手动开合不再被布局重排或运行结果刷新覆盖;函数、链接、列表和记录按内容排版,手机详情整行展示。核心仍为 19 个构造;拓展库保留 2.7.0。
|
||||||
|
|
||||||
|
CLI fix release: implementation disclosures retain mouse/keyboard choices across resize, nested source reading and live replacement. Typed call/link/value details preserve real navigation and read-only inspection. Independent extension packs remain 2.7.0.
|
||||||
|
|
||||||
|
详见 [双语发布说明](doc/releases/v2.7.1.md)。旧静态站点需要用新 CLI 重新导出。
|
||||||
|
|
||||||
## v2.7.0 — 2026-11-10
|
## v2.7.0 — 2026-11-10
|
||||||
|
|
||||||
### Highlights / 亮点
|
### Highlights / 亮点
|
||||||
|
|||||||
Generated
+2
-2
@@ -615,7 +615,7 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "marqdo"
|
name = "marqdo"
|
||||||
version = "2.7.0"
|
version = "2.7.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"assert_cmd",
|
"assert_cmd",
|
||||||
@@ -656,7 +656,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "marqdo-wasm"
|
name = "marqdo-wasm"
|
||||||
version = "2.7.0"
|
version = "2.7.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"marqdo",
|
"marqdo",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "marqdo"
|
name = "marqdo"
|
||||||
version = "2.7.0"
|
version = "2.7.1"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
description = "Marqdo — Markdown markers as an interpreted programming language"
|
description = "Marqdo — Markdown markers as an interpreted programming language"
|
||||||
|
|||||||
@@ -1,20 +1,105 @@
|
|||||||
# Marqdo
|
# Marqdo — Your SKILL is now a TOOL.
|
||||||
|
|
||||||
**代码即文档。文档即知识库。知识即可执行。**
|
<p align="center"><strong>Write it. Inspect it. Call it.</strong></p>
|
||||||
|
<p align="center"><em>让 SKILL 真正成为工具:文档即知识,知识即可执行。</em></p>
|
||||||
|
|
||||||
Marqdo 把 Markdown **标记当作编程语法**:同一个 `.mq.md` 文件,既是给人读的文稿,也是给机器跑的程序。写文档的过程就是在写可执行逻辑——大型项目里,说明、示例与实现不再分叉成三份真相。它不是「又一个 Markdown 编程语言」,而是**文档原生的编程运行时(Document-native runtime)**——一门关于**可执行知识(Executable Knowledge)**的语言。
|
<p align="center">
|
||||||
|
<a href="https://github.com/cflmy/marqdo/releases/tag/v2.7.1"><img alt="release" src="https://img.shields.io/badge/release-v2.7.1-DDBA86?style=flat-square"></a>
|
||||||
|
<a href="LICENSE"><img alt="Apache-2.0" src="https://img.shields.io/badge/license-Apache--2.0-blue?style=flat-square"></a>
|
||||||
|
<img alt="Rust runtime" src="https://img.shields.io/badge/runtime-Rust-B38E68?style=flat-square">
|
||||||
|
<img alt="Pure by default" src="https://img.shields.io/badge/call-pure_by_default-467C83?style=flat-square">
|
||||||
|
</p>
|
||||||
|
|
||||||
v2.2.0 起,`marqdo call` 可以直接调用这份文件里的一个函数。读的是同一页说明,跑的是同一个实现。知识因此可以当工具用,测试也不必再包一层 `# main`。
|
**Marqdo is a Rust-based, document-native runtime for executable AI skills and tools.** Write human-readable prose, GFM tables, parameter contracts, and real functions in one `.mq.md` document. Call a function by its heading, inspect the implementation, and grant side effects explicitly.
|
||||||
|
|
||||||
欢迎访问 [marqdo 官方网站](https://www.marqdo.com/) 阅读更多特性与可执行文档。
|
**Not a prompt wrapper.** The document is interpreted as a program by Marqdo; its tool functions are not merely natural-language instructions.
|
||||||
|
|
||||||
**链接语法**:[doc/design/link-syntax.md](doc/design/link-syntax.md) · 语法宪法:[doc/design/markdown-mapping.md](doc/design/markdown-mapping.md) · 对象:[objects.md](doc/design/objects.md) · 调用实参:[call-arguments.md](doc/design/call-arguments.md) · 用户站:[user-site.md](doc/design/user-site.md) · 浏览:[view.md](doc/design/view.md) · 调试:[view-debug.md](doc/design/view-debug.md) · OKF 清单:[catalog-cli.md](doc/design/catalog-cli.md) · Engineering Knowledge:[engineering-knowledge.md](doc/design/engineering-knowledge.md) · VS Code 扩展:[vscode-extension.md](doc/design/vscode-extension.md)(分支 **`vscode-extension`**;提交约定 [vscode-extension-commit.md](doc/design/vscode-extension-commit.md)) · **AI Skill**:[skills/marqdo/](skills/marqdo/)(说明 [ai-skill.md](doc/design/ai-skill.md)) · 官方扩展:[ext-llm.md](doc/design/ext-llm.md)(`ext/llm`)· [ext-agent.md](doc/design/ext-agent.md)(智能体开发框架)· [ext-cli.md](doc/design/ext-cli.md)(`marqdo ext list/add/remove`) · 原生插件 ABI:[ext-abi.md](doc/design/ext-abi.md)(`lib/plugin`) · 金样例:[tests/](tests/) · 用户文档:[public/](public/) · 变更:[CHANGELOG.md](CHANGELOG.md)
|
<p align="center">
|
||||||
|
<a href="#quickstart--one-function-one-command">Quickstart</a> ·
|
||||||
|
<a href="#a-procurement-skill-with-a-600-budget">Procurement demo</a> ·
|
||||||
|
<a href="#explore-the-view">View</a> ·
|
||||||
|
<a href="doc/library-development.mq.md">Guide</a> ·
|
||||||
|
<a href="https://www.marqdo.com/">Website</a> ·
|
||||||
|
<a href="doc/releases/v2.7.1.md">Release notes</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
<sub>Animated walkthrough assembled from **real Marqdo 2.7.1 function-call results**, including the accepted **simulated** order and an over-budget refusal. Curated frames, not a recording of typing or a production transaction. [Reproduce the capture](scripts/capture-procurement-showcase.py) · [CI run](https://github.com/cflmy/marqdo/actions/runs/43358103498).</sub>
|
||||||
|
|
||||||
|
## Quickstart — one function, one command
|
||||||
|
|
||||||
|
Install the [2.7.1 CLI release for Windows or Linux](https://github.com/cflmy/marqdo/releases/tag/v2.7.1), then run from this repository's root:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
marqdo call examples/calculator.mq.md 计算器.加法 a=2 b=3
|
||||||
|
# => 5
|
||||||
|
```
|
||||||
|
|
||||||
|
The function heading is the callable name. The function's explanation, parameters, return contract, and implementation live **in the same source file**. Use `--json` for machine-readable call results and diagnostics. No LLM key is needed for this quickstart.
|
||||||
|
|
||||||
|
## A procurement skill with a ¥600 budget
|
||||||
|
|
||||||
|
[Read the complete executable procurement document](examples/procurement/index.mq.md) · [How to run and verify the example](examples/procurement/README.md)
|
||||||
|
|
||||||
|
This is a **seven-tool, offline demonstration**. It knows the local supplier directory, queries a static price catalog, checks the budget, and conditionally creates a **simulated** work order. It also documents receipt handling, negotiation and supplier switching as unconnected stubs.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. Approve suppliers: paused or blacklisted entries are excluded.
|
||||||
|
marqdo call examples/procurement/index.mq.md 查询采购商 "采购商状态='正常'" --json
|
||||||
|
|
||||||
|
# 2. Quote: SUP_JN, 8 ball bearings × ¥36 = ¥288 (sample price).
|
||||||
|
marqdo call examples/procurement/index.mq.md 查询采购商价格 "采购商标识符='SUP_JN'" 数量=8 有效秒数=300 --json
|
||||||
|
|
||||||
|
# 3. Budget: ¥600 - ¥120 = ¥480.
|
||||||
|
marqdo call examples/procurement/index.mq.md 查询余额 已花费=120 --json
|
||||||
|
|
||||||
|
# 4. Recheck supplier, quote, delivery and budget before a local mock order.
|
||||||
|
marqdo call examples/procurement/index.mq.md 向采购商发工单 "采购商标识符='SUP_JN'" 数量=8 单价=36 已花费=120 交付要求天数=7 --effects time.read,process.control --json
|
||||||
|
|
||||||
|
# 5. Over budget: ¥600 - ¥360 = ¥240 < ¥288. The mock work order must be denied.
|
||||||
|
marqdo call examples/procurement/index.mq.md 向采购商发工单 "采购商标识符='SUP_JN'" 数量=8 单价=36 已花费=360 交付要求天数=7 --effects time.read,process.control --json
|
||||||
|
```
|
||||||
|
|
||||||
|
| Case | Budget check | Expected business result |
|
||||||
|
|---|---|---|
|
||||||
|
| `已花费=120` | ¥480 available ≥ ¥288 | `ok: true`, **local simulation only, not sent** |
|
||||||
|
| `已花费=360` | ¥240 available < ¥288 | `ok: false`, budget denial |
|
||||||
|
| `SUP_YY` | Supplier on blacklist | Excluded from quote / order |
|
||||||
|
|
||||||
|
**Why this matters:** The document doesn't merely tell an agent to obey a limit. The work-order **function itself** calls supplier validation, price lookup, and `查询余额` before returning an order record. Agent instructions and callable business logic can be inspected together.
|
||||||
|
|
||||||
|
> **Important limits:** Price and supplier records are fixtures; `已花费` is caller supplied. No authoritative budget ledger, concurrent reservation, live supplier prices, ERP messaging, real receipt, or payment is implemented. A successful **simulated** order is **not** a real transaction. The demo is a testable starting point, not a financial safety guarantee.
|
||||||
|
|
||||||
|
## Explore the View
|
||||||
|
|
||||||
|
Marqdo 2.7.1 improves the interactive reading experience: implementation details stay open when manually expanded, structured values are presented more clearly, and function/source links are easier to inspect. It **does not introduce new language syntax or APIs**.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
marqdo view examples/procurement --no-open
|
||||||
|
```
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
<sub>**Actual screenshot** captured in Chromium from a Marqdo **2.7.1** View static export, scrolled to `向采购商发工单`. It shows the real rendered document, not a promotional mockup. [Screenshot generation source](scripts/capture-procurement-showcase.py).</sub>
|
||||||
|
|
||||||
|
## One document, multiple uses
|
||||||
|
|
||||||
|
| Prompt-oriented agent skill | Marqdo executable skill |
|
||||||
|
|---|---|
|
||||||
|
| Natural-language tool instructions | Natural-language guidance **and** executable functions |
|
||||||
|
| Description and code often separated | Heading, parameter table, return table and implementation in one `.mq.md` |
|
||||||
|
| Validation may require separate wiring | Named function calls can be checked, executed and tested |
|
||||||
|
| Prompts ask a model to comply | Runtime permissions control **declared** effects of a function call |
|
||||||
|
| Hard to follow implementation through files | View links readable content and implementation details |
|
||||||
|
|
||||||
|
Agent Skills already support scripts; Marqdo's claim is **one document-native language surface** for authoring, inspecting, executing and reusing functions. This is **not** a claim of full formal verification, zero-delay execution, or OS-level isolation of all plugin/process behavior.
|
||||||
|
|
||||||
|
**Resources:** [Release v2.7.1](https://github.com/cflmy/marqdo/releases/tag/v2.7.1) · [Procurement example](examples/procurement/index.mq.md) · [Executable library authoring](doc/library-development.mq.md) · [Function calling](public/features/22-函数调用.mq.md) · [Link syntax](doc/design/link-syntax.md) · [Website](https://www.marqdo.com/)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
标准库单文件本身就是手册:直接阅读[文件库](lib/文件.mq.md)、[集合库](lib/表.mq.md)等源码,按函数标题下的参数表、返回契约和动作说明调用;[工程实践](examples/stdlib-handbook/索引.mq.md)演示文件整理、CSV 汇总与文档维护。
|
## Deep dive · 语言、设计与执行系统
|
||||||
开发标准库和拓展库请直接阅读[可执行库开发指南](doc/library-development.mq.md):契约表、叙述式实现、遮蔽调用与多文件工程组织均有可运行示范。
|
|
||||||
|
|
||||||
|
|
||||||
## 核心优势:可执行知识(Executable Knowledge)
|
## 核心优势:可执行知识(Executable Knowledge)
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 139 KiB |
@@ -0,0 +1,42 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="1340" height="720" viewBox="0 0 1340 720" role="img" aria-label="Animated illustration of a procurement skill being called, including a budget denial">
|
||||||
|
<defs><linearGradient id="night" x1="0" y1="0" x2="1" y2="1"><stop stop-color="#0b1324"/><stop offset="1" stop-color="#1a2335"/></linearGradient></defs>
|
||||||
|
<rect x="0" y="0" width="1340" height="720" rx="0" fill="url(#night)" stroke="none"/>
|
||||||
|
<text x="46" y="52" fill="#f6d39c" font-size="30" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="700">Marqdo</text>
|
||||||
|
<text x="207" y="50" fill="#9eacc1" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">/ EXECUTABLE SKILLS</text>
|
||||||
|
<rect x="1137" y="25" width="165" height="38" rx="19" fill="#283348" stroke="#4b5b6b"/>
|
||||||
|
<text x="1154" y="50" fill="#d3d9e4" font-size="15" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">2.7.1 · DEMO</text>
|
||||||
|
<text x="46" y="109" fill="#f6f5ee" font-size="37" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="700">Your SKILL is now a TOOL.</text>
|
||||||
|
<text x="47" y="141" fill="#a8b6c7" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">A human-readable document → callable business logic → structured results</text>
|
||||||
|
<rect x="43" y="168" width="608" height="493" rx="18" fill="#182235" stroke="#38485c"/>
|
||||||
|
<rect x="677" y="168" width="620" height="493" rx="18" fill="#111a2b" stroke="#38485c"/>
|
||||||
|
<rect x="43" y="168" width="608" height="57" rx="18" fill="#263349" stroke="none"/>
|
||||||
|
<rect x="677" y="168" width="620" height="57" rx="18" fill="#263349" stroke="none"/>
|
||||||
|
<text x="65" y="204" fill="#f5dba9" font-size="20" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="600">index.mq.md</text>
|
||||||
|
<text x="707" y="204" fill="#e5eaf4" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">$ marqdo call ... 向采购商发工单</text>
|
||||||
|
<text x="66" y="266" fill="#faf7f1" font-size="27" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="700">## 向采购商发工单</text>
|
||||||
|
<text x="66" y="307" fill="#a2b2ca" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">Read the rules. Call the function.</text>
|
||||||
|
<rect x="65" y="328" width="564" height="166" rx="9" fill="#101a2a" stroke="none"/>
|
||||||
|
<text x="86" y="365" fill="#abd6fa" font-size="19" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">报价 = 查询采购商价格(...)</text>
|
||||||
|
<text x="86" y="407" fill="#abd6fa" font-size="19" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">预算 = 查询余额(已花费=...)</text>
|
||||||
|
<text x="86" y="453" fill="#e9ba84" font-size="19" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">1. 剩余额度 < 本单金额 → 拒绝</text>
|
||||||
|
<text x="65" y="552" fill="#d4e0ee" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">One file: prose + contracts + tables</text>
|
||||||
|
<text x="65" y="588" fill="#d4e0ee" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">+ executable functions + result records</text>
|
||||||
|
<text x="706" y="272" fill="#d7deef" font-size="19" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">SUP_JN 数量=8 单价=36</text>
|
||||||
|
<text x="706" y="311" fill="#98aec9" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">最高预算 = ¥600</text>
|
||||||
|
<g opacity=".18"><animate attributeName="opacity" values="0.18;0.18;1;1;0.18" keyTimes="0;0.04;0.09;0.91;1" dur="13s" repeatCount="indefinite"/><rect x="704" y="345" width="565" height="45" rx="9" fill="#233248" stroke="none"/><text x="719" y="374" fill="#9db5cf" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">01 SUPPLIER</text><text x="920" y="374" fill="#f5d8aa" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">SUP_JN · active</text></g>
|
||||||
|
<g opacity=".18"><animate attributeName="opacity" values="0.18;0.18;1;1;0.18" keyTimes="0;0.19;0.24;0.91;1" dur="13s" repeatCount="indefinite"/><rect x="704" y="399" width="565" height="45" rx="9" fill="#233248" stroke="none"/><text x="719" y="428" fill="#9db5cf" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">02 QUOTE</text><text x="920" y="428" fill="#f5d8aa" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">8 × ¥36 = ¥288</text></g>
|
||||||
|
<g opacity=".18"><animate attributeName="opacity" values="0.18;0.18;1;1;0.18" keyTimes="0;0.35;0.39999999999999997;0.91;1" dur="13s" repeatCount="indefinite"/><rect x="704" y="453" width="565" height="45" rx="9" fill="#233248" stroke="none"/><text x="719" y="482" fill="#9db5cf" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">03 BALANCE</text><text x="920" y="482" fill="#f5d8aa" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">¥600 - already spent</text></g>
|
||||||
|
<g opacity=".18"><animate attributeName="opacity" values="0.18;0.18;1;1;0.18" keyTimes="0;0.53;0.5800000000000001;0.91;1" dur="13s" repeatCount="indefinite"/><rect x="704" y="507" width="565" height="45" rx="9" fill="#233248" stroke="none"/><text x="719" y="536" fill="#9db5cf" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">04 DECISION</text><text x="920" y="536" fill="#f5d8aa" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">check requested amount</text></g>
|
||||||
|
<g opacity="0"><animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.62;0.66;0.85;1" dur="13s" repeatCount="indefinite"/>
|
||||||
|
<rect x="704" y="572" width="565" height="68" rx="10" fill="#193a34" stroke="#478a71"/>
|
||||||
|
<text x="718" y="600" fill="#b5ebcb" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="600">✓ 已花费=120 ¥480 ≥ ¥288</text>
|
||||||
|
<text x="718" y="625" fill="#d9f7e8" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">ok: true · 本地模拟,未发送</text>
|
||||||
|
</g>
|
||||||
|
<g opacity="0"><animate attributeName="opacity" values="0;0;0;1;1;0" keyTimes="0;0.78;0.84;0.88;0.95;1" dur="13s" repeatCount="indefinite"/>
|
||||||
|
<rect x="704" y="572" width="565" height="68" rx="10" fill="#42252d" stroke="#a45a67"/>
|
||||||
|
<text x="718" y="600" fill="#f8b1bc" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="600">✕ 已花费=360 ¥240 < ¥288</text>
|
||||||
|
<text x="718" y="625" fill="#fde7ea" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">ok: false · 预算不足,拒绝工单</text>
|
||||||
|
</g>
|
||||||
|
<path d="M 652 430 C 665 429 674 429 688 430" fill="none" stroke="#f0c58c" stroke-width="3"/><circle cx="665" cy="429" r="4" fill="#f0c58c"><animate attributeName="cx" values="656;681;656" dur="2.5s" repeatCount="indefinite"/></circle>
|
||||||
|
<text x="44" y="698" fill="#7e90a7" font-size="14" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">ILLUSTRATED EXPECTED FLOW · NOT A TERMINAL CAPTURE · NO REAL PURCHASE</text>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 7.4 KiB |
@@ -0,0 +1,35 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="1340" height="740" viewBox="0 0 1340 740" role="img" aria-label="View-inspired editorial concept for the procurement function, not a real screenshot">
|
||||||
|
<rect x="0" y="0" width="1340" height="740" rx="0" fill="#f8f6f0" stroke="none"/>
|
||||||
|
<rect x="0" y="0" width="1340" height="68" rx="0" fill="#f2ede4" stroke="none"/>
|
||||||
|
<text x="69" y="45" fill="#8d7358" font-size="29" font-family="Georgia,serif" font-weight="600">marqdo</text>
|
||||||
|
<text x="577" y="43" fill="#665d53" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">文档 函数 执行 变量</text>
|
||||||
|
<text x="1030" y="44" fill="#998773" font-size="13" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">VIEW CONCEPT / NOT CAPTURE</text>
|
||||||
|
<line x1="325" y1="113" x2="325" y2="688" stroke="#e0d5c7"/><line x1="1032" y1="113" x2="1032" y2="688" stroke="#e0d5c7"/>
|
||||||
|
<text x="374" y="128" fill="#b0895e" font-size="16" font-family="Georgia,'Noto Serif CJK SC',serif" font-weight="400">采购智能体</text>
|
||||||
|
<text x="372" y="196" fill="#39352d" font-size="37" font-family="'Noto Serif CJK SC',Georgia,serif" font-weight="600">向采购商发工单</text>
|
||||||
|
<text x="374" y="238" fill="#5d5851" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">核对准入、价格、交付与预算之后,生成本地模拟工单。</text>
|
||||||
|
<line x1="374" y1="267" x2="993" y2="267" stroke="#b69b78"/>
|
||||||
|
<text x="375" y="309" fill="#514a41" font-size="21" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="600">参数</text>
|
||||||
|
<text x="375" y="348" fill="#5b5146" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">采购商标识符</text>
|
||||||
|
<text x="625" y="348" fill="#96754f" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">text</text>
|
||||||
|
<text x="811" y="348" fill="#8e8171" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">必填</text>
|
||||||
|
<line x1="374" y1="365" x2="994" y2="365" stroke="#ded6c9"/>
|
||||||
|
<text x="375" y="392" fill="#5b5146" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">数量 / 单价 / 已花费</text>
|
||||||
|
<text x="625" y="392" fill="#96754f" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">number</text>
|
||||||
|
<text x="811" y="392" fill="#8e8171" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">必填</text>
|
||||||
|
<line x1="374" y1="408" x2="994" y2="408" stroke="#ded6c9"/>
|
||||||
|
<text x="374" y="463" fill="#5e584f" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">发单前,必须再次查询并核对本轮的可用余额。</text>
|
||||||
|
<rect x="373" y="483" width="618" height="48" rx="8" fill="#ebe3d5" stroke="none"/>
|
||||||
|
<text x="391" y="513" fill="#805b35" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">预算 = [重新查询预算](查询余额(...))</text>
|
||||||
|
<text x="374" y="565" fill="#7b5b4b" font-size="19" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">1. 剩余额度 < 本单金额</text>
|
||||||
|
<text x="374" y="612" fill="#a06b5f" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400"> 返回 [预算不足,拒绝模拟工单](...)</text>
|
||||||
|
<text x="375" y="682" fill="#8c8276" font-size="16" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">仅在全部检查通过时产生“本地模拟、未发送”的结果。</text>
|
||||||
|
<path d="M 408 503 C 295 503 278 339 146 339" stroke="#ba9a75" stroke-width="1.7" fill="none"/><circle cx="408" cy="503" r="4.3" fill="#ba9a75"/>
|
||||||
|
<text x="73" y="281" fill="#a78255" font-size="15" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">BUDGET CHECK</text>
|
||||||
|
<text x="73" y="315" fill="#756350" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">已花费 ¥360</text>
|
||||||
|
<text x="73" y="343" fill="#756350" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">剩余额度 ¥240</text>
|
||||||
|
<path d="M 823 602 C 1010 586 1026 396 1122 396" stroke="#b7837e" stroke-width="1.7" fill="none"/><circle cx="823" cy="602" r="4.3" fill="#b7837e"/>
|
||||||
|
<text x="1080" y="319" fill="#a67871" font-size="15" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">REJECTION</text>
|
||||||
|
<text x="1080" y="354" fill="#945e55" font-size="22" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="700">¥240 < ¥288</text>
|
||||||
|
<text x="1080" y="393" fill="#945e55" font-size="19" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">拒绝工单</text>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 4.9 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 204 KiB |
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "marqdo-wasm"
|
name = "marqdo-wasm"
|
||||||
version = "2.7.0"
|
version = "2.7.1"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
description = "Marqdo interpreter as WebAssembly (browser host bridge)"
|
description = "Marqdo interpreter as WebAssembly (browser host bridge)"
|
||||||
|
|||||||
Vendored
+8
@@ -1,3 +1,11 @@
|
|||||||
|
marqdo (2.7.1-1ppa2) noble; urgency=medium
|
||||||
|
|
||||||
|
* Release 2.7.1; see the reviewed upstream CHANGELOG.
|
||||||
|
* Stop reapplying the engineering compatibility fix already in upstream.
|
||||||
|
* Include cached orig bytes until publication is confirmed by Launchpad.
|
||||||
|
|
||||||
|
-- Marqdo Maintainers <cflmy@users.noreply.github.com> Wed, 11 Nov 2026 00:03:29 +0800
|
||||||
|
|
||||||
marqdo (2.7.0-1ppa2) noble; urgency=medium
|
marqdo (2.7.0-1ppa2) noble; urgency=medium
|
||||||
|
|
||||||
* Repair engineering plugin compatibility for this 2.7.0 release.
|
* Repair engineering plugin compatibility for this 2.7.0 release.
|
||||||
|
|||||||
Vendored
+2
-1
@@ -1 +1,2 @@
|
|||||||
engineering-stable-option.patch
|
# engineering-stable-option.patch
|
||||||
|
# The fix is already in upstream 2.7.1.
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
# Marqdo 2.7.1
|
||||||
|
|
||||||
|
本次为 CLI 修复发布,重点修复 View 中“实际逻辑”展开后立即折叠的问题,并完成描述链接的细节排版。官方拓展库继续使用 2.7.0,不发布新的独立拓展包,也不移动 CDN VERSION。
|
||||||
|
|
||||||
|
This CLI release fixes implementation disclosures that collapsed immediately after opening and improves typed details for descriptive links. Official extension packs remain at 2.7.0; no independent extension assets or CDN VERSION update are included.
|
||||||
|
|
||||||
|
## 修复与改进 / Fixes and improvements
|
||||||
|
|
||||||
|
- View 布局只记录自己的自动开合,不再覆盖用户选择;鼠标、键盘、窗口变化、嵌套原始写法及同一文档的运行结果刷新均保留手动状态。
|
||||||
|
- Disclosure choices survive layout, resize and live DOM replacement. Layout-generated toggle events do not become user intent or trigger another reset loop.
|
||||||
|
- 函数调用按函数名、命名参数和嵌套调用排版;本页函数可以定位到定义。链接在正文及侧注中保留跳转,相对 mq.md 链接适配实时和离线页面。
|
||||||
|
- Lists, records and prose have typed presentation with optional original source. Empty payloads remain explicit placeholders; reading details never runs payloads.
|
||||||
|
- 手机详情按整行排列,展开卡片不再撑高相邻卡片。新增可执行阅读示例 examples/view-details.mq.md。
|
||||||
|
|
||||||
|
## 核心表面与范围 / Core surface and scope
|
||||||
|
|
||||||
|
核心构造仍为 19 个,没有新增语法、标准库接口或插件 ABI。变更属于 CLI 内嵌 View 前端、只读渲染与发布产物选择。浏览器不会因查看详情而执行实现或自动抓取链接预览。
|
||||||
|
|
||||||
|
The core surface stays at 19 constructs. Standard-library and extension APIs are unchanged. CLI and WASM manifest versions are 2.7.1; extension source packs stay 2.7.0. The matching VS Code package is built from its separate source branch. This release does not deploy gh-pages.
|
||||||
|
|
||||||
|
## 下载与安装 / Downloads and installation
|
||||||
|
|
||||||
|
| 产物 / Asset | 内容 / Contents |
|
||||||
|
|---|---|
|
||||||
|
| marqdo-2.7.1-x86_64-pc-windows-msvc.exe | Windows CLI,内嵌标准库 / CLI with embedded standard library |
|
||||||
|
| marqdo-2.7.1-x86_64-pc-windows-msvc.zip | Windows CLI 与配套库及原生插件 / complete Windows bundle |
|
||||||
|
| marqdo-2.7.1-x86_64-unknown-linux-gnu.zip | Linux CLI 与配套库及原生插件 / complete Linux bundle |
|
||||||
|
| marqdo-2.7.1-stdlib.zip | 标准库源码,API 未变 / standard-library sources with unchanged APIs |
|
||||||
|
| marqdo-2.7.1-source.zip | 本标签源码 / tagged source snapshot |
|
||||||
|
| marqdo-2.7.1.vsix | 独立编辑器分支构建 / editor extension from its separate branch |
|
||||||
|
| marqdo-2.7.1-public.zip | 使用修复后的 View 导出的用户文档 / public docs exported with the fixed View |
|
||||||
|
|
||||||
|
下载并解压对应平台 ZIP,使用其中的 CLI;独立 Windows EXE 内嵌标准库。Ubuntu noble 用户可使用 ppa:cflmy/marqdo 安装或升级,实际包可用性由发版最终验证单独检查。旧的静态导出需用新 CLI 重新执行 marqdo view output,才能包含修复后的前端。
|
||||||
|
|
||||||
|
Unpack the matching platform bundle, or use the standalone Windows executable. The maintained Ubuntu noble installation route is ppa:cflmy/marqdo. Regenerate older static exports with marqdo view output to include the fixed reader script. A CLI-only release keeps the existing official extension installation version.
|
||||||
|
|
||||||
|
## 验证范围 / Validation
|
||||||
|
|
||||||
|
本地全量 Rust 验收为 1039 通过、0 失败、2 个原有忽略项;用户文档成功导出 102 页。本地验收覆盖真实详情点击、键盘开合、原始写法、反复布局、窗口变化、实时 DOM 替换,以及静态/实时页面、桌面/手机和无脚本阅读。另验证只读导出不会触发逻辑、现有运行标注与连线、文档间跳转和示例函数调用。
|
||||||
|
|
||||||
|
Windows and Linux builds, exact-commit Release/EK jobs, archive contents and hashes, and Ubuntu source/build/apt availability are independent final release gates. Local browser tests do not establish Windows build success, and upload acceptance does not establish apt availability.
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# Procurement skill · reproducible demo
|
||||||
|
|
||||||
|
This is a **local simulation** in one callable `.mq.md` source. It has no external purchase side effects and does not require an LLM API key.
|
||||||
|
|
||||||
|
## What it demonstrates
|
||||||
|
|
||||||
|
- A `¥600` spending limit with a caller-supplied balance.
|
||||||
|
- An active supplier `SUP_JN`, quoting `¥36` for a sample bearing.
|
||||||
|
- Eight units total `¥288` with an estimated seven-day delivery.
|
||||||
|
- Supplier approval, quote comparison, budget check and local work-order generation as direct Marqdo function calls.
|
||||||
|
- Unconnected capabilities (live quotes, real work orders and receipts, negotiation and supplier switching) explicitly labeled as stubs.
|
||||||
|
|
||||||
|
## Run from the repository root
|
||||||
|
|
||||||
|
```bash
|
||||||
|
marqdo check examples/procurement/index.mq.md --narrative-ratio
|
||||||
|
marqdo call examples/procurement/index.mq.md 查询采购商 "采购商状态='正常'" --json
|
||||||
|
marqdo call examples/procurement/index.mq.md 查询采购商价格 "采购商标识符='SUP_JN'" 数量=8 有效秒数=300 --json
|
||||||
|
marqdo call examples/procurement/index.mq.md 查询余额 已花费=120 --json
|
||||||
|
marqdo call examples/procurement/index.mq.md 向采购商发工单 "采购商标识符='SUP_JN'" 数量=8 单价=36 已花费=120 交付要求天数=7 --effects time.read,process.control --json
|
||||||
|
marqdo call examples/procurement/index.mq.md 向采购商发工单 "采购商标识符='SUP_JN'" 数量=8 单价=36 已花费=360 交付要求天数=7 --effects time.read,process.control --json
|
||||||
|
marqdo call examples/procurement/index.mq.md 查询采购商价格 "采购商标识符='SUP_YY'" 数量=8 --json
|
||||||
|
```
|
||||||
|
|
||||||
|
## Interpret the result
|
||||||
|
|
||||||
|
The return from `向采购商发工单` is a **business-level** `ok/value/error` map. In the low-spend case it should contain `ok=True`, `工单金额=288` and `状态="本地模拟,未发送"`. When already spent reaches `360`, the function should return `ok=False` and a budget rejection reason. The CLI's outer JSON call envelope is separate from this nested domain result.
|
||||||
|
|
||||||
|
These are **expected outcomes**, not independently verified terminal captures. The workflow [procurement-example.yml](../../.github/workflows/procurement-example.yml) exercises the commands using the released Linux CLI.
|
||||||
|
|
||||||
|
## Inspect in View
|
||||||
|
|
||||||
|
```bash
|
||||||
|
marqdo view examples/procurement --no-open
|
||||||
|
```
|
||||||
|
|
||||||
|
Open `向采购商发工单` and expand the annotations for `查询采购商价格`, `查询余额`, and `剩余额度`. Merely reading and expanding details does not execute side effects.
|
||||||
|
|
||||||
|
## Production integration boundaries
|
||||||
|
|
||||||
|
The real supplier quote API, persistent authoritative ledger, concurrent budget reservation, ERP transaction, order receipt, negotiation, and supplier switching are **not connected**. Before any real purchase, integrate server-side budget reservations, quote signatures/evidence, idempotent transactions, durable logs and an explicit human authorization policy.
|
||||||
|
|
||||||
|
The GIF-like animated [SVG storyboard](../../assets/marketing/procurement-flow.svg) and the [View-inspired concept](../../assets/marketing/procurement-view-concept.svg) are illustrations, not instrumented evidence.
|
||||||
@@ -0,0 +1,469 @@
|
|||||||
|
---
|
||||||
|
markup: occlusion
|
||||||
|
title: 采购智能体
|
||||||
|
version: v1.1-demo
|
||||||
|
description: 600 元采购预算下的供应商筛选、示例询价、预算审核和模拟工单;真实采购接口尚未接通。
|
||||||
|
import:
|
||||||
|
table: lib/table.mq.md
|
||||||
|
time: lib/time.mq.md
|
||||||
|
---
|
||||||
|
|
||||||
|
# main
|
||||||
|
|
||||||
|
这是一份可阅读、可调用的采购工作手册,也是一份开发中的采购 SKILL。
|
||||||
|
它把采购制度、供应商知识、模拟数据与操作工具放在同一个 Marqdo 文档里。
|
||||||
|
当前版本只支持本地模拟采购,不会向真实供应商发消息、扣款或确认采购。
|
||||||
|
|
||||||
|
采购目标是在最高 600 元 的预算内,从状态正常、报价可接受且预计交期满足要求的供应商中,
|
||||||
|
选择总成本最低的方案。价格相同时,应优先考虑交付可靠性,并保留供老板决策的理由。
|
||||||
|
所有费用均以人民币元计算;样例不包含税费、运费、折扣及多币种换算。
|
||||||
|
|
||||||
|
采购工具不是自动取得授权的交易权限。智能体可解释和比较工具返回的数据,
|
||||||
|
但必须遵守下面的门禁;真实下单、持久化预算占用、实时报价和最终回执都需要后续接入。
|
||||||
|
|
||||||
|
| 业务能力 | 本地状态 | 可信边界 |
|
||||||
|
|---|---|---|
|
||||||
|
| 查询采购商 | 已接通示例名录 | 只反映下文静态目录,不是在线主数据 |
|
||||||
|
| 查询采购商价格 | 示例数据 | 价格与交期为测试样例,不是实时承诺 |
|
||||||
|
| 查询余额 | 已接通计算逻辑 | `已花费` 由调用方提供,尚未读取持久账本 |
|
||||||
|
| 向采购商发工单 | 本地模拟 | 会再次检查供应商、报价和预算,不真正发送 |
|
||||||
|
| 检查工单 | 模拟回复 | 不能验证真实工单,也不会确认真实下单 |
|
||||||
|
| 讲价 | 未接通,保留示例请求 | 不代表供应商已收到议价 |
|
||||||
|
| 更换采购商 | 未接通,保留示例请求 | 不代表已经切换或重新询价 |
|
||||||
|
|
||||||
|
采购工作原则(阅读说明,非函数)
|
||||||
|
|
||||||
|
这里的工作原则是叙述知识,供智能体阅读;不是可调用函数。
|
||||||
|
实际调用的函数均在下面的二级标题中定义。需要让规则成为真正的技术门禁时,
|
||||||
|
必须在相应函数中重复检查,不能认为写在本节的文字会自动执行。
|
||||||
|
|
||||||
|
| 阶段 | 工具 | 通过条件 | 需要保留的证据 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 1. 准入 | 查询采购商 | 只考虑状态为“正常”的供应商 | 名录快照、筛选结果 |
|
||||||
|
| 2. 比价 | 查询采购商价格 | 对候选逐家询价,比较相同商品、数量、交期与总额 | 各家报价及数据来源 |
|
||||||
|
| 3. 预算 | 查询余额 | 每次拟发单前重新查询;剩余额度不小于本单总额 | 已花费、可用余额、本单金额 |
|
||||||
|
| 4. 工单 | 向采购商发工单 | 准入、报价、交期和预算校验同时通过 | 模拟工单和校验摘要 |
|
||||||
|
| 5. 回执 | 检查工单 | 只有真实回执和真实下单接口接通后才能确认交易 | 回执、处置决定 |
|
||||||
|
|
||||||
|
不可突破的边界是:黑名单供应商不询价、不发单;已暂停供应商也不参与比价。
|
||||||
|
没有报价不得发单,超预算不得发单;回执不清楚时不能擅自认为已经下单。
|
||||||
|
如果某家缺货,可以考虑另询一家;议价成功之前,不能用目标价格充当已确认价格。
|
||||||
|
|
||||||
|
示例演练。 采购 8 件深沟球轴承,假设本轮已花费 120 元、交付要求为 7 天。
|
||||||
|
静态目录里,正常供应商的示例单价为江南配件 36 元、粤海精工 39 元、华东金属 42 元。
|
||||||
|
在样例条件下江南配件报价总额为 288 元,余额为 480 元,能够生成模拟工单。
|
||||||
|
北岭工贸虽然报价更低,但已经暂停;远洋贸易属于黑名单,两者都必须排除。
|
||||||
|
|
||||||
|
从本文件所在目录调用,建议使用结构化输出,以便把每次调用的入参和返回值另行归档:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
marqdo call index.mq.md 查询采购商 "采购商状态='正常'" --json
|
||||||
|
marqdo call index.mq.md 查询采购商价格 "采购商标识符='SUP_JN'" "商品='深沟球轴承'" 数量=8 --json
|
||||||
|
marqdo call index.mq.md 查询余额 已花费=120 --json
|
||||||
|
marqdo call index.mq.md 向采购商发工单 "采购商标识符='SUP_JN'" 数量=8 单价=36 已花费=120 交付要求天数=7 --effects time.read,process.control --json
|
||||||
|
marqdo call index.mq.md 检查工单 "工单号='MOCK-WO-示例'" "模拟回复='缺货'" --json
|
||||||
|
```
|
||||||
|
|
||||||
|
以上第五条是独立的回执模拟,不是第四条工单的真实回执。
|
||||||
|
将来接入真实系统以后,应使用实际返回的工单号,并从系统查询实际状态。
|
||||||
|
示例中的 `--json` 是输出格式,不会自动建立审计账本;目前由调用方保存记录。
|
||||||
|
|
||||||
|
|
||||||
|
维护约定:以后真正接通报价、ERP、账本与议价通道时,务必把“模拟”状态替换为真实的失败可恢复结果,
|
||||||
|
并增加后端校验、并发预算占用、幂等与日志持久化。在真实验收之前,不得修改文档宣称已经完成交易。
|
||||||
|
|
||||||
|
建议使用以下命令对本文件做实际检查;这些命令是待在已安装 Marqdo 的工程环境中执行的验收步骤,
|
||||||
|
不是本文件声称已经通过的测试结果:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
marqdo check index.mq.md --narrative-ratio
|
||||||
|
marqdo call index.mq.md 查询采购商 "采购商状态='正常'" --json
|
||||||
|
marqdo call index.mq.md 查询采购商价格 "采购商标识符='SUP_YY'" 数量=8 --json
|
||||||
|
marqdo call index.mq.md 查询余额 已花费=550 --json
|
||||||
|
marqdo call index.mq.md 向采购商发工单 "采购商标识符='SUP_JN'" 数量=8 单价=36 已花费=550 --effects time.read,process.control --json
|
||||||
|
marqdo call index.mq.md 向采购商发工单 "采购商标识符='SUP_BL'" 数量=8 单价=30 已花费=0 --effects time.read,process.control --json
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 查询采购商
|
||||||
|
|
||||||
|
| 参数 | 类型 | 默认 | 说明 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 采购商状态 | text | "全部" | 按状态筛选;可选“全部 / 正常 / 已暂停 / 黑名单” |
|
||||||
|
|
||||||
|
| 返回 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| result | list | 供应商记录列表;名称、标识符、状态、老板的评价、采购商的喜好;无匹配则为空列表 |
|
||||||
|
|
||||||
|
根据调用者传入的`采购商状态`="全部"筛选供应商目录。这份目录是可执行的本地样例,
|
||||||
|
将来接入供应商主数据后,应在这里替换数据来源,保留相同的记录字段和筛选契约。
|
||||||
|
|
||||||
|
“全部”用于名录展示和审计;采购决策必须显式传入“正常”,
|
||||||
|
不能因为全部名录里列出了黑名单供应商,就把它们作为可采购对象。
|
||||||
|
这里的列表包含带首列“行”的 GFM 表格,因此每行都是一条可检索的记录。
|
||||||
|
|
||||||
|
`采购商名录` =
|
||||||
|
|
||||||
|
| 行 | 名称 | 标识符 | 状态 | 老板的评价 | 采购商的喜好 |
|
||||||
|
|---|---|---|---|---|---|
|
||||||
|
| 1 | 华东金属 | SUP_HD | 正常 | 交付稳定,价格较高 | 大批量,账期短 |
|
||||||
|
| 2 | 江南配件 | SUP_JN | 正常 | 价格较低,偶有拖期 | 小批量,快单 |
|
||||||
|
| 3 | 北岭工贸 | SUP_BL | 已暂停 | 曾出现质检不合格 | 定制订单 |
|
||||||
|
| 4 | 粤海精工 | SUP_YH | 正常 | 老合作伙伴,可沟通价格 | 长期协议,年框 |
|
||||||
|
| 5 | 远洋贸易 | SUP_YY | 黑名单 | 曾收款后失联 | 无 |
|
||||||
|
|
||||||
|
当筛选状态为“全部”时,提供完整目录供查看;
|
||||||
|
这是查询目录,不代表所有供应商均允许交易。
|
||||||
|
|
||||||
|
1. `采购商状态` == "全部"
|
||||||
|
我们返回*[返回完整示例名录](`采购商名录`)*。
|
||||||
|
|
||||||
|
其他状态使用表库的相等过滤,不直接手写循环。
|
||||||
|
|
||||||
|
我们返回*[按状态筛选采购商](table.where(list=`采购商名录`, key="状态", value=`采购商状态`))*。
|
||||||
|
|
||||||
|
## 查询采购商价格
|
||||||
|
|
||||||
|
| 参数 | 类型 | 默认 | 说明 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 采购商标识符 | text | 必填 | 需要询价的供应商标识,例如 SUP_JN |
|
||||||
|
| 商品 | text | "深沟球轴承" | 本次询价的品名;样例目录目前只有这一种商品 |
|
||||||
|
| 数量 | number | 1 | 采购件数,必须为正整数 |
|
||||||
|
| 有效秒数 | number | 300 | 预留给真实报价接口的有效期参数;模拟价格不产生有效报价凭证 |
|
||||||
|
|
||||||
|
| 返回 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| result | any | 示例报价 map,含商品、数量、单价、总额、交期、来源及真实性标记;不允许询价或无数据时为 None |
|
||||||
|
|
||||||
|
使用`采购商标识符`查询`商品`="深沟球轴承"的示例价格,按`数量`=1计算总额。
|
||||||
|
`有效秒数`=300只是将来真实询价服务的预留输入;它不会让静态价格自动变成实时价格。
|
||||||
|
一个报价必须同时说明价格、来源及是否允许真实交易,不能仅凭生成时间认定报价有效。
|
||||||
|
|
||||||
|
先检查数量和保留的有效期是否合理。无效输入不应返回看似正常的价格。
|
||||||
|
|
||||||
|
1. `数量` <= 0 or int(`数量`) != `数量` or `有效秒数` <= 0
|
||||||
|
我们返回*[数量或有效期不合法,拒绝询价](None)*。
|
||||||
|
|
||||||
|
询价前重新从准入目录检查供应商状态。即使示例价格表里包含已暂停或黑名单商户,
|
||||||
|
也不能将它们的价格返回给采购智能体,防止“最低价优先”覆盖供应商准入规则。
|
||||||
|
|
||||||
|
我们先**正常名录 = [只读取可参与询价的供应商](查询采购商(采购商状态="正常"))**,
|
||||||
|
再**候选 = [匹配当前供应商标识](table.where(list=`正常名录`, key="标识符", value=`采购商标识符`))**。
|
||||||
|
|
||||||
|
1. table.len(xs=`候选`) == 0
|
||||||
|
我们返回*[供应商不存在或当前不可询价](None)*。
|
||||||
|
|
||||||
|
以下表格是用于开发与验收的静态价格及交期样例。所有行都不是实时供应商承诺。
|
||||||
|
接入线上报价系统时,只替换“取得原始报价”的部分,并保留准入、总额和来源检查。
|
||||||
|
|
||||||
|
`示例价格目录` =
|
||||||
|
|
||||||
|
| 行 | 采购商标识符 | 商品 | 报价单价 | 预计交付天数 |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| 1 | SUP_HD | 深沟球轴承 | 42 | 3 |
|
||||||
|
| 2 | SUP_JN | 深沟球轴承 | 36 | 7 |
|
||||||
|
| 3 | SUP_BL | 深沟球轴承 | 30 | 2 |
|
||||||
|
| 4 | SUP_YH | 深沟球轴承 | 39 | 5 |
|
||||||
|
| 5 | SUP_YY | 深沟球轴承 | 20 | 1 |
|
||||||
|
|
||||||
|
取得单家供应商的目录条目,再匹配商品,避免将别的商品的价格用于本次采购。
|
||||||
|
我们先**报价目录 = [供应商实时报价接口未接通,暂用本地示例价格](`示例价格目录`)**,
|
||||||
|
让没有接通的服务状态在可检索标签中明确可见。
|
||||||
|
|
||||||
|
我们再**同商报价 = [从示例目录查找指定供应商](table.where(list=`报价目录`, key="采购商标识符", value=`采购商标识符`))**,
|
||||||
|
再**命中报价 = [限定本次询价商品](table.where(list=`同商报价`, key="商品", value=`商品`))**。
|
||||||
|
|
||||||
|
1. table.len(xs=`命中报价`) == 0
|
||||||
|
我们返回*[没有这件商品的示例报价](None)*。
|
||||||
|
|
||||||
|
从唯一一条样例记录取得单价和交期,然后计算相同数量的总金额。
|
||||||
|
因为目前没有真实接口,返回的数据必须永久带有“模拟”标记,直到服务真正接入并验证。
|
||||||
|
|
||||||
|
我们先**报价条目 = [取出命中的示例记录](table.first(list=`命中报价`))**,
|
||||||
|
然后**单价 = [读取单件报价](access(`报价条目`, "报价单价"))**,
|
||||||
|
以及**交付周期 = [读取样例交付天数](access(`报价条目`, "预计交付天数"))**。
|
||||||
|
本次报价的**报价总额 = [单价乘以购买数量](`单价` * `数量`)**。
|
||||||
|
|
||||||
|
`报价` =
|
||||||
|
|
||||||
|
| 采购商标识符 | 商品 | 单价 | 数量 | 报价总额 | 预计交付天数 | 报价来源 | 报价时间 | 报价生效至 | 可真实下单 |
|
||||||
|
|---|---|---|---|---|---|---|---|---|---|
|
||||||
|
| `采购商标识符` | `商品` | `单价` | `数量` | `报价总额` | `交付周期` | 示例目录(未接实时接口) | None | None | False |
|
||||||
|
|
||||||
|
我们返回*[这条可测试、不可用于真实下单的报价](`报价`)*,
|
||||||
|
供后续比价和本地模拟使用;真实业务必须另外验证供应商提供的报价凭证。
|
||||||
|
|
||||||
|
## 查询余额
|
||||||
|
|
||||||
|
| 参数 | 类型 | 默认 | 说明 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 已花费 | number | 0 | 调用方已确认的本轮占用金额;不得为负,模拟运行期间不自动累加 |
|
||||||
|
|
||||||
|
| 返回 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| result | any | 预算 map,含最高预算、已花费、可用余额、还能下单;负数输入时为 None |
|
||||||
|
|
||||||
|
预算上限固定为 600 元。输入`已花费`=0代表一轮新的采购演练;
|
||||||
|
后续每次准备发单时,必须传入已经确认或占用的实际累计金额。
|
||||||
|
当前没有持久账本,这个数字由调用方维护;工具不会自动记账,也不能防止两个独立进程并发超支。
|
||||||
|
|
||||||
|
当已花费为负数时,拒绝计算,避免用负债务造出虚假的可用余额。
|
||||||
|
|
||||||
|
1. `已花费` < 0
|
||||||
|
我们返回*[累计支出不允许为负数](None)*。
|
||||||
|
|
||||||
|
这次计算先**最高预算 = [读取采购预算上限](600)**,
|
||||||
|
再**可用余额 = [计算还未占用的额度](`最高预算` - `已花费`)**。
|
||||||
|
如果余额已经为零或更少,返回中应明确写“不能”,防止后续误发工单。
|
||||||
|
|
||||||
|
1. `可用余额` > 0
|
||||||
|
`余额` =
|
||||||
|
|
||||||
|
| 最高预算 | 已花费 | 可用余额 | 还能下单 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `最高预算` | `已花费` | `可用余额` | 可以 |
|
||||||
|
|
||||||
|
我们返回*[预算仍有剩余额度](`余额`)*。
|
||||||
|
|
||||||
|
`余额` =
|
||||||
|
|
||||||
|
| 最高预算 | 已花费 | 可用余额 | 还能下单 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `最高预算` | `已花费` | `可用余额` | 不能 |
|
||||||
|
|
||||||
|
我们返回*[预算已用尽或已超支](`余额`)*。
|
||||||
|
|
||||||
|
## 向采购商发工单
|
||||||
|
|
||||||
|
| 参数 | 类型 | 默认 | 说明 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 采购商标识符 | text | 必填 | 接受模拟工单的供应商标识 |
|
||||||
|
| 数量 | number | 必填 | 拟采购件数,必须为正整数 |
|
||||||
|
| 单价 | number | 必填 | 本次拟采用的单价,必须与本次重新取得的示例报价一致 |
|
||||||
|
| 已花费 | number | 必填 | 拟发单时的累计已占用金额;不得遗漏或默认为零 |
|
||||||
|
| 商品 | text | "深沟球轴承" | 拟采购商品 |
|
||||||
|
| 交付要求天数 | number | 7 | 最晚可接受交期;以自然日计,本地样例仅作演示 |
|
||||||
|
| 采购文字 | text | "按标准规格采购" | 本单采购要求与备注 |
|
||||||
|
| 休息秒数 | number | 0 | 仅用于测试等待效应的模拟延迟;并非真实供应商回执窗口 |
|
||||||
|
|
||||||
|
| 返回 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| result | map | 含 ok 状态的结构化结果;成功时 value 为模拟工单,失败时 error 为原因;不代表已真实发送 |
|
||||||
|
|
||||||
|
根据调用者提供的`采购商标识符`、`数量`、`单价`、`已花费`,
|
||||||
|
以及`商品`="深沟球轴承"、`交付要求天数`=7、`采购文字`="按标准规格采购"、`休息秒数`=0
|
||||||
|
尝试创建一份本地模拟工单。这是整个采购流程的最后一道可执行防线;
|
||||||
|
即使智能体漏做了前面的检查,本函数仍会再次询价并调用查询余额。
|
||||||
|
|
||||||
|
单次函数调用可以拒绝非法金额,但不能证明调用者传入的已花费真实,也没有跨调用的报价令牌或持久预算锁。
|
||||||
|
后续要接通真实 ERP 时,必须增加服务端事务、幂等键、报价凭证核验和权威预算余额。
|
||||||
|
在这些能力上线之前,此函数只返回本地模拟数据,不允许被当成真实采购指令。
|
||||||
|
|
||||||
|
基础输入必须合理。金额或天数为负、数量非正整数、等待时间过长都应在本阶段直接拒绝。
|
||||||
|
使用内部失败助手统一构造 `ok=False` 的回执,避免产生半成品工单。
|
||||||
|
|
||||||
|
1. `数量` <= 0 or int(`数量`) != `数量` or `单价` <= 0 or `已花费` < 0 or `交付要求天数` < 0 or `休息秒数` < 0 or `休息秒数` > 300
|
||||||
|
我们返回*[拒绝无效工单输入](_拒绝模拟工单(原因="数量、单价、金额或期限参数不合法"))*。
|
||||||
|
|
||||||
|
第一道业务门禁重新读取正常供应商,不信任调用方单独提供的标识符。
|
||||||
|
|
||||||
|
我们先**正常商户 = [从本地名录获取正常供应商](查询采购商(采购商状态="正常"))**,
|
||||||
|
再**供应商命中 = [核实供应商仍然处于正常状态](table.where(list=`正常商户`, key="标识符", value=`采购商标识符`))**。
|
||||||
|
|
||||||
|
1. table.len(xs=`供应商命中`) == 0
|
||||||
|
我们返回*[拒绝黑名单、暂停或不存在的供应商](_拒绝模拟工单(原因="供应商未通过准入审核"))*。
|
||||||
|
|
||||||
|
第二道门禁在本次调用中重新询价,既避免凭记忆下单,也防止调用方任意填写低价。
|
||||||
|
但此阶段重新拿到的是静态示例价格,并不是供应商确认的线上报价。
|
||||||
|
|
||||||
|
我们先**报价 = [重新查本次商品与数量的模拟报价](查询采购商价格(采购商标识符=`采购商标识符`, 商品=`商品`, 数量=`数量`, 有效秒数=300))**。
|
||||||
|
|
||||||
|
1. `报价` == None
|
||||||
|
我们返回*[未查到报价,禁止生成工单](_拒绝模拟工单(原因="此供应商没有可用的示例报价"))*。
|
||||||
|
|
||||||
|
报价存在后,核对输入价格与示例单价,以及交货要求;价格不一致时不允许自己改写报价。
|
||||||
|
|
||||||
|
我们先**询得单价 = [取本次询价单价](access(`报价`, "单价"))**,
|
||||||
|
再**预计交期 = [取示例预计交期](access(`报价`, "预计交付天数"))**,
|
||||||
|
同时**本单金额 = [取示例报价总额](access(`报价`, "报价总额"))**。
|
||||||
|
|
||||||
|
1. `单价` != `询得单价`
|
||||||
|
我们返回*[价格未经本次询价确认,拒绝工单](_拒绝模拟工单(原因="拟采用单价与本次示例报价不一致"))*。
|
||||||
|
|
||||||
|
1. `预计交期` > `交付要求天数`
|
||||||
|
我们返回*[预计交期不能满足要求,拒绝工单](_拒绝模拟工单(原因="示例交付周期超过可接受期限"))*。
|
||||||
|
|
||||||
|
第三道门禁必须在建立工单前调用查询余额,并使用本次输入的累计已花费金额。
|
||||||
|
发工单不是先保存成功再补看余额;条件不成立时立即返回拒绝结果。
|
||||||
|
|
||||||
|
我们先**预算 = [在拟发单时重新查询预算](查询余额(已花费=`已花费`))**。
|
||||||
|
|
||||||
|
1. `预算` == None
|
||||||
|
我们返回*[累计金额不合法,拒绝工单](_拒绝模拟工单(原因="本轮累计支出无效"))*。
|
||||||
|
|
||||||
|
我们再**剩余额度 = [读取可用于本单的余额](access(`预算`, "可用余额"))**。
|
||||||
|
|
||||||
|
1. `剩余额度` < `本单金额`
|
||||||
|
我们返回*[本单超过剩余额度,拒绝工单](_拒绝模拟工单(原因="采购金额超过 600 元总预算的剩余额度"))*。
|
||||||
|
|
||||||
|
全部检查通过后才生成可追溯的模拟编号。编号只服务本地演练,
|
||||||
|
同一秒内的多个调用可能产生相同编号,不能拿它代替生产级幂等键。
|
||||||
|
|
||||||
|
我们先**当前秒 = [读取本地模拟工单生成时间](time.now_unix())**,
|
||||||
|
再**模拟工单号 = [生成带模拟前缀的工单号]("MOCK-WO-" + str(`当前秒`) + "-" + `采购商标识符` + "-" + str(`数量`))**。
|
||||||
|
同时**预计已占用 = [计算此笔模拟工单对应的累计占用](`已花费` + `本单金额`)**,
|
||||||
|
该数值只用于展示,不会写入持久账本。
|
||||||
|
|
||||||
|
只有显式要求演练延迟时才挂起。这种等待不会触发真实发送或获取真实回执。
|
||||||
|
|
||||||
|
1. `休息秒数` > 0
|
||||||
|
我们先**等待毫秒 = [将模拟等待秒数换算为毫秒](`休息秒数` * 1000)**,
|
||||||
|
再**[模拟等待回执窗口](time.sleep_ms(ms=`等待毫秒`))**。
|
||||||
|
|
||||||
|
`工单` =
|
||||||
|
|
||||||
|
| 工单号 | 采购商标识符 | 商品 | 数量 | 单价 | 工单金额 | 采购文字 | 已花费 | 本单后预计已占用 | 模拟交期天数 | 报价来源 | 状态 |
|
||||||
|
|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||||
|
| `模拟工单号` | `采购商标识符` | `商品` | `数量` | `询得单价` | `本单金额` | `采购文字` | `已花费` | `预计已占用` | `预计交期` | 示例目录(未接实时接口) | 本地模拟,未发送 |
|
||||||
|
|
||||||
|
这一记录给智能体下一步检查模拟回执使用;它没有持久保存到任何订单系统,
|
||||||
|
也没有自动修改预算余额。把`工单`作为 value,连同成功标记一起返回。
|
||||||
|
|
||||||
|
`成功回执` =
|
||||||
|
|
||||||
|
| ok | value | error |
|
||||||
|
|---|---|---|
|
||||||
|
| True | `工单` | None |
|
||||||
|
|
||||||
|
我们返回*[模拟校验通过,但真实发单尚未接通](`成功回执`)*。
|
||||||
|
|
||||||
|
## 检查工单
|
||||||
|
|
||||||
|
| 参数 | 类型 | 默认 | 说明 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 工单号 | text | 必填 | 待演练的工单编号;本地没有可核验的持久工单仓库 |
|
||||||
|
| 模拟回复 | text | "不清楚" | 可选:有货 / 缺货 / 不清楚;默认采取保守处置 |
|
||||||
|
|
||||||
|
| 返回 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| result | map | 工单号、回执、下一步、理由、来源;任何结果均不等于真实下单完成 |
|
||||||
|
|
||||||
|
读取调用方提供的`工单号`和`模拟回复`="不清楚",生成一份仅供开发的回执解释。
|
||||||
|
本工具没有向供应商查询工单状态,也不核对该编号是否真实存在。
|
||||||
|
真实环境必须改为用工单系统查回执、核对供应商身份,再按订单状态机处理。
|
||||||
|
|
||||||
|
有货并不代表已经付款或下单。即使示例回执说“有货”,
|
||||||
|
当前可以做的也只是标记“模拟可推进”;在真实交易接口接通前必须停止。
|
||||||
|
|
||||||
|
1. `模拟回复` == "有货"
|
||||||
|
`结论` =
|
||||||
|
|
||||||
|
| 工单号 | 回执 | 下一步 | 理由 | 数据来源 |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| `工单号` | 有货 | 待真实下单接口接通 | 模拟有货;不得视作已采购或已付款 | 模拟回复 |
|
||||||
|
|
||||||
|
我们返回*[保留模拟有货的回执结果](`结论`)*。
|
||||||
|
|
||||||
|
如果模拟回复表示缺货,就停止当前候选,重新筛选其他正常供应商并比价。
|
||||||
|
更换采购商工具目前也未接通,所以不能把“准备更换”写成“更换成功”。
|
||||||
|
|
||||||
|
1. `模拟回复` == "缺货"
|
||||||
|
`结论` =
|
||||||
|
|
||||||
|
| 工单号 | 回执 | 下一步 | 理由 | 数据来源 |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| `工单号` | 缺货 | 更换采购商(待接通) | 模拟缺货,应返回供应商选择和报价阶段 | 模拟回复 |
|
||||||
|
|
||||||
|
我们返回*[建议重新筛选采购商](`结论`)*。
|
||||||
|
|
||||||
|
对于不清楚或不属于约定值的回复,采取更保守的处置:不自动采购,
|
||||||
|
只生成建议协商的下一步,避免把未定义状态解释为成功。
|
||||||
|
|
||||||
|
`结论` =
|
||||||
|
|
||||||
|
| 工单号 | 回执 | 下一步 | 理由 | 数据来源 |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| `工单号` | 不清楚 | 讲价或人工核实(待接通) | 回执没有提供足以真实下单的证据 | 模拟回复 |
|
||||||
|
|
||||||
|
我们返回*[回执不明确,停止自动确认](`结论`)*。
|
||||||
|
|
||||||
|
## 讲价
|
||||||
|
|
||||||
|
| 参数 | 类型 | 默认 | 说明 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 工单号 | text | 必填 | 需要发起议价请求的模拟工单号 |
|
||||||
|
| 目标单价 | number | 必填 | 期望价格;必须为正数,不代表采购商已经接受 |
|
||||||
|
| 理由 | text | "报价高于同期均价" | 给供应商看的议价依据,未来接通通道时使用 |
|
||||||
|
|
||||||
|
| 返回 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| result | any | 示例议价请求 map;目标单价不合法时为 None |
|
||||||
|
|
||||||
|
针对`工单号`提出`目标单价`,使用`理由`="报价高于同期均价"解释期望。
|
||||||
|
议价通道当前尚未接通,这里刻意保留一条可执行的示例请求,
|
||||||
|
方便开发者以后替换成真实消息投递和回执解析。
|
||||||
|
|
||||||
|
不能把期望价改写成询得单价,也不能认为发出模拟请求就获得了供应商同意。
|
||||||
|
真实成交价必须依赖新的、可验证的报价凭证,再重新执行预算校验。
|
||||||
|
|
||||||
|
1. `目标单价` <= 0
|
||||||
|
我们返回*[目标价格必须大于零](None)*。
|
||||||
|
|
||||||
|
`示例议价请求` =
|
||||||
|
|
||||||
|
| 工单号 | 目标单价 | 理由 | 状态 | 通道 |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| `工单号` | `目标单价` | `理由` | 未接通(仅保留模拟请求) | 示例议价通道 |
|
||||||
|
|
||||||
|
我们返回*[保留议价意图,等待接通真实通道](`示例议价请求`)*。
|
||||||
|
|
||||||
|
## 更换采购商
|
||||||
|
|
||||||
|
| 参数 | 类型 | 默认 | 说明 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 原采购商标识符 | text | 必填 | 已经不再适合本单的供应商标识 |
|
||||||
|
| 商品 | text | "深沟球轴承" | 要继续寻找供应商的采购品名 |
|
||||||
|
| 原因 | text | "原供应商缺货" | 记录更换的业务原因 |
|
||||||
|
|
||||||
|
| 返回 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| result | map | 原供应商、商品、原因、状态与建议动作;不代表真正更换成功 |
|
||||||
|
|
||||||
|
对于`原采购商标识符`、`商品`="深沟球轴承"和`原因`="原供应商缺货",
|
||||||
|
先保留更换意图,下一步应回到正常供应商名录并重新询价。
|
||||||
|
目前没有接入供应商切换系统,不能直接把固定的候选名单解释成已经选定的下一家。
|
||||||
|
|
||||||
|
后续接通真实通道时,应使用同一份供应商准入规则,排除当前被放弃的供应商,
|
||||||
|
重新比较报价、交期、预算,并重新生成工单;绝不能直接复用上一家供应商的报价。
|
||||||
|
|
||||||
|
`示例更换请求` =
|
||||||
|
|
||||||
|
| 原采购商标识符 | 商品 | 原因 | 状态 | 建议动作 |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| `原采购商标识符` | `商品` | `原因` | 未接通(仅保留模拟请求) | 重新查询正常供应商并逐家询价 |
|
||||||
|
|
||||||
|
我们返回*[供应商切换通道未接通,保存模拟更换请求](`示例更换请求`)*。
|
||||||
|
|
||||||
|
## _拒绝模拟工单
|
||||||
|
|
||||||
|
| 参数 | 类型 | 默认 | 说明 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 原因 | text | 必填 | 预算、供应商、报价、交期或输入不合格的具体原因 |
|
||||||
|
|
||||||
|
| 返回 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| result | map | 统一的失败记录,ok=False、value=None、error=失败原因 |
|
||||||
|
|
||||||
|
内部辅助函数使用`原因`说明模拟工单没有通过哪一项门禁。
|
||||||
|
所有拒绝出口都必须返回同样形态的结构化结果,便于智能体在读取 `ok` 之后决定是否继续。
|
||||||
|
这里不抛异常、不发送工单,也不通过一个虚假的工单号掩盖失败。
|
||||||
|
|
||||||
|
`失败回执` =
|
||||||
|
|
||||||
|
| ok | value | error |
|
||||||
|
|---|---|---|
|
||||||
|
| False | None | `原因` |
|
||||||
|
|
||||||
|
我们返回*[用于拒绝发单的统一失败回执](`失败回执`)*。
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
# 采购智能体:验收与真实接口接入说明
|
||||||
|
|
||||||
|
## 工程放置方式
|
||||||
|
|
||||||
|
建议把 `index.mq.md` 放入 Marqdo 仓库的 `examples/procurement/`,或可以解析 `lib/table.mq.md` 和 `lib/time.mq.md` 的现有项目中。`import` 中沿用仓库根目录提供的公开标准库。下面命令假设从 `index.mq.md` 所在目录执行。
|
||||||
|
|
||||||
|
此文件目前是**采购业务 SKILL + 本地模拟工具集合**,不是可执行的真实采购交易系统。它仍需要负责决策的 Agent 调度各工具,并保存独立调用日志。
|
||||||
|
|
||||||
|
## 建议执行的验收用例(待运行)
|
||||||
|
|
||||||
|
| 场景 | 命令 | 预期 |
|
||||||
|
|---|---|---|
|
||||||
|
| 正常供应商 | `marqdo call index.mq.md 查询采购商 "采购商状态='正常'" --json` | 只返回 SUP_HD、SUP_JN、SUP_YH |
|
||||||
|
| 黑名单询价 | `marqdo call index.mq.md 查询采购商价格 "采购商标识符='SUP_YY'" 数量=8 --json` | 返回 None |
|
||||||
|
| 暂停供应商询价 | `marqdo call index.mq.md 查询采购商价格 "采购商标识符='SUP_BL'" 数量=8 --json` | 返回 None |
|
||||||
|
| 正常报价 | `marqdo call index.mq.md 查询采购商价格 "采购商标识符='SUP_JN'" 数量=8 --json` | 示例单价 36、总额 288、交期 7 天、可真实下单 False |
|
||||||
|
| 零数量询价 | `marqdo call index.mq.md 查询采购商价格 "采购商标识符='SUP_JN'" 数量=0 --json` | 返回 None |
|
||||||
|
| 正常预算 | `marqdo call index.mq.md 查询余额 已花费=120 --json` | 可用余额 480 |
|
||||||
|
| 用尽预算 | `marqdo call index.mq.md 查询余额 已花费=600 --json` | 余额 0、不能下单 |
|
||||||
|
| 非法预算 | `marqdo call index.mq.md 查询余额 已花费=-1 --json` | 返回 None |
|
||||||
|
| 模拟工单 | `marqdo call index.mq.md 向采购商发工单 "采购商标识符='SUP_JN'" 数量=8 单价=36 已花费=120 --effects time.read,process.control --json` | ok=True、状态为本地模拟未发送、模拟本单后预计占用 408 |
|
||||||
|
| 超预算 | `marqdo call index.mq.md 向采购商发工单 "采购商标识符='SUP_JN'" 数量=8 单价=36 已花费=350 --effects time.read,process.control --json` | ok=False,不生成工单 |
|
||||||
|
| 伪低价 | `marqdo call index.mq.md 向采购商发工单 "采购商标识符='SUP_JN'" 数量=8 单价=35 已花费=0 --effects time.read,process.control --json` | ok=False,不允许自行篡改示例报价 |
|
||||||
|
| 交期不足 | `marqdo call index.mq.md 向采购商发工单 "采购商标识符='SUP_JN'" 数量=8 单价=36 已花费=0 交付要求天数=5 --effects time.read,process.control --json` | ok=False,因为样例交期 7 天 |
|
||||||
|
| 更快供应商 | `marqdo call index.mq.md 向采购商发工单 "采购商标识符='SUP_YH'" 数量=8 单价=39 已花费=0 交付要求天数=5 --effects time.read,process.control --json` | ok=True,仅模拟 |
|
||||||
|
| 无效供应商 | `marqdo call index.mq.md 向采购商发工单 "采购商标识符='SUP_YY'" 数量=8 单价=20 已花费=0 --effects time.read,process.control --json` | ok=False |
|
||||||
|
| 缺货回执 | `marqdo call index.mq.md 检查工单 "工单号='MOCK-WO-test'" "模拟回复='缺货'" --json` | 下一步为更换采购商(未接通) |
|
||||||
|
| 不明确回执 | `marqdo call index.mq.md 检查工单 "工单号='MOCK-WO-test'" --json` | 不认定下单成功,转人工或议价 |
|
||||||
|
| 议价占位 | `marqdo call index.mq.md 讲价 "工单号='MOCK-WO-test'" 目标单价=34 --json` | 返回“未接通”的示例议价请求 |
|
||||||
|
| 切换占位 | `marqdo call index.mq.md 更换采购商 "原采购商标识符='SUP_JN'" --json` | 返回“未接通”的示例切换请求 |
|
||||||
|
|
||||||
|
建议随后执行 `marqdo check index.mq.md --narrative-ratio`,并在仓库的 Tree、Bytecode 两种执行后端跑以上场景。上表是**验收设计和预期结果**,不代表这些命令已经在本环境执行。
|
||||||
|
|
||||||
|
## 真实系统接入路线
|
||||||
|
|
||||||
|
1. **供应商主数据**:替换 `查询采购商` 中的示例名录,保持相同字段,并加入供应商状态更新时间与可靠的准入校验。
|
||||||
|
2. **报价**:替换 `查询采购商价格` 的静态样例源,增加供应商确认的报价编号、有效期、税运费与币种信息;只有真实服务确认后才允许真实下单。
|
||||||
|
3. **预算账本**:把 `已花费` 的调用方输入升级为权威持久账本读数,并在工单提交前做原子预算预占、幂等和失败释放,防止并发超预算。
|
||||||
|
4. **真实工单**:真实发送必须以服务端校验的报价、准入、预算预占凭证为依据;保存工单号、状态迁移、外部调用结果和完整审计轨迹。
|
||||||
|
5. **真实回执与议价**:把 `模拟回复` 替换为工单服务查询结果;议价后重新获取报价,不能擅自修改原单价格;切换后重新比价。
|
||||||
|
6. **Agent 层**:由调用者保存每一步的入参、原始结果、选择理由及关联编号。当前函数调用为无持久状态的模拟,尚不能担保跨进程审计或执行重放。
|
||||||
|
|
||||||
|
## 重要限制
|
||||||
|
|
||||||
|
- 本次改写参考了公开仓库源码与规范,但运行环境未提供 `marqdo` 可执行文件,因此没有实际完成 `marqdo check` 或函数调用测试。
|
||||||
|
- 表格金额使用示例整数元;生产环境应使用整数分或经过审计的十进制金额库,避免浮点误差。
|
||||||
|
- 当前“发工单”返回 `ok=True` 只表示本地演练的门禁通过,不表示真实订单提交成功。
|
||||||
|
- 模拟工单号含秒级时间戳,不保证跨调用唯一,也不能充当生产幂等键。
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
---
|
||||||
|
markup: occlusion
|
||||||
|
title: 描述与细节
|
||||||
|
---
|
||||||
|
|
||||||
|
这份文档把意图留在句子中,把细节放在侧注里。阅读和展开详情都不会运行示例中的函数,只有主动调用才会计算。
|
||||||
|
|
||||||
|
可以先看 [函数与参数](计算费用(单价=12, 数量=2)),再看 [嵌套调用](计算费用(单价=abs(-12), 数量=2)),了解每个输入来自哪里。
|
||||||
|
|
||||||
|
引用 [列表内容]([1, 2, 3]) 和 [记录内容]({"名称": "茶", "单价": 12}) 时,侧注会按内容的结构排列;[补充说明]("数量以实际购买件数为准。") 则直接呈现文字。
|
||||||
|
|
||||||
|
[待实现的步骤]() 会明确提示待补充,避免把缺失逻辑当成已经完成的工作。
|
||||||
|
|
||||||
|
通过 [跳到函数定义](#fn-16) 可以在当前文档中定位,通过 [查看阅读示例](view-reading.mq.md) 可以打开同目录文档;[访问项目仓库](https://github.com/cflmy/marqdo) 保留正常的网页跳转。
|
||||||
|
|
||||||
|
## 计算费用
|
||||||
|
|
||||||
|
| 参数 | 类型 | 默认值 | 含义 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| 单价 | number | 0 | 每件商品的价格 |
|
||||||
|
| 数量 | number | 1 | 本次购买的件数 |
|
||||||
|
|
||||||
|
| 返回值 | 类型 | 含义 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 费用 | number | 单价与数量的乘积 |
|
||||||
|
|
||||||
|
调用方提供 `单价`=0 和 `数量`=1 后,可以直接按件数计算。这一示例只处理简单乘法,未包含税费、折扣或金额舍入规则,实际项目应根据业务补齐这些约定。
|
||||||
|
|
||||||
|
在确认输入符合业务要求之后,返回 *[按件数计算](单价 * 数量)*,调用方便得到了本次购买的总费用。
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Reproducible marketing captures from the actual Marqdo 2.7.1 Linux CLI.
|
||||||
|
|
||||||
|
All procurement outputs are simulation-only. The GIF is a curated display of
|
||||||
|
the real function-call JSON responses, not a filmed human typing session.
|
||||||
|
The screenshot is taken with a real headless browser from marqdo view output.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
from PIL import Image, ImageDraw, ImageFont
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
OUT = ROOT / "assets" / "marketing"
|
||||||
|
SRC = "examples/procurement/index.mq.md"
|
||||||
|
|
||||||
|
def invoke(cli, fn, args=(), effects=None):
|
||||||
|
cmd = [str(cli), "call", SRC, fn, *args]
|
||||||
|
if effects:
|
||||||
|
cmd += ["--effects", effects]
|
||||||
|
cmd.append("--json")
|
||||||
|
p = subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True, timeout=45)
|
||||||
|
if p.returncode != 0:
|
||||||
|
raise RuntimeError("Command failed:\n" + " ".join(cmd) + "\n" + p.stdout + "\n" + p.stderr)
|
||||||
|
try:
|
||||||
|
result = json.loads(p.stdout)
|
||||||
|
except json.JSONDecodeError as exc:
|
||||||
|
raise RuntimeError(f"Non-JSON CLI response {p.stdout!r}") from exc
|
||||||
|
if not result.get("ok"):
|
||||||
|
raise RuntimeError("Marqdo call rejected: " + p.stdout)
|
||||||
|
print("VERIFIED", fn, json.dumps(result, ensure_ascii=False))
|
||||||
|
return result["result"]
|
||||||
|
|
||||||
|
def font(size, bold=False):
|
||||||
|
for name in (
|
||||||
|
"/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc" if bold else "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
|
||||||
|
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf" if bold else "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
return ImageFont.truetype(name, size)
|
||||||
|
except OSError:
|
||||||
|
continue
|
||||||
|
return ImageFont.load_default()
|
||||||
|
|
||||||
|
def frame(index, headline, invocation, details, emphasis=None, danger=False):
|
||||||
|
W, H = 1200, 660
|
||||||
|
img = Image.new("RGB", (W,H), (14,22,37))
|
||||||
|
d = ImageDraw.Draw(img)
|
||||||
|
gold = (238,201,145); muted = (159,178,204)
|
||||||
|
d.rounded_rectangle((24,22,1175,635), radius=25, fill=(22,32,51), outline=(59,77,101), width=2)
|
||||||
|
d.text((53,49), "Marqdo", font=font(30,True), fill=gold)
|
||||||
|
d.text((231,57), "EXECUTABLE SKILLS / PROCUREMENT",font=font(19),fill=muted)
|
||||||
|
d.rounded_rectangle((976,44,1138,82), radius=16, fill=(39,54,75))
|
||||||
|
d.text((1000,54),"v2.7.1",font=font(18),fill=(216,227,239))
|
||||||
|
d.text((53,139),headline,font=font(32,True),fill=(245,244,239))
|
||||||
|
d.text((54,188),"CALL",font=font(16,True),fill=gold)
|
||||||
|
d.rounded_rectangle((49,208,1150,293),radius=11,fill=(12,19,33))
|
||||||
|
for i,line in enumerate(invocation):
|
||||||
|
d.text((66,223+i*34),line,font=font(19),fill=(194,221,240))
|
||||||
|
d.text((54,336),"ACTUAL CLI RESULT / DOMAIN FIELDS",font=font(16,True),fill=gold)
|
||||||
|
d.rounded_rectangle((49,352,1150,536),radius=11,fill=(16,26,43))
|
||||||
|
for i,line in enumerate(details[:5]):
|
||||||
|
d.text((69,371+i*33),line,font=font(20),fill=(219,233,241))
|
||||||
|
if emphasis:
|
||||||
|
accent=(245,153,159) if danger else (155,231,185)
|
||||||
|
d.rounded_rectangle((52,554,1149,609),radius=10,fill=(68,38,48) if danger else (30,67,57))
|
||||||
|
d.text((71,569),emphasis,font=font(22,True),fill=accent)
|
||||||
|
for i in range(5):
|
||||||
|
x=79+i*219
|
||||||
|
d.rounded_rectangle((x,621,x+204,628),radius=3,fill=gold if i<=index else (69,81,99))
|
||||||
|
d.text((855,641),f"FRAME {index+1} / 5 · SIMULATED ONLY",font=font(13),fill=muted)
|
||||||
|
return img
|
||||||
|
|
||||||
|
def make_gif(cli):
|
||||||
|
suppliers=invoke(cli,"查询采购商",["采购商状态='正常'"])
|
||||||
|
quote=invoke(cli,"查询采购商价格",["采购商标识符='SUP_JN'","数量=8","有效秒数=300"])
|
||||||
|
balance=invoke(cli,"查询余额",["已花费=120"])
|
||||||
|
orderargs=["采购商标识符='SUP_JN'","数量=8","单价=36","交付要求天数=7"]
|
||||||
|
good=invoke(cli,"向采购商发工单",orderargs+["已花费=120"],effects="time.read,process.control")
|
||||||
|
bad=invoke(cli,"向采购商发工单",orderargs+["已花费=360"],effects="time.read,process.control")
|
||||||
|
assert isinstance(suppliers,list) and any(x.get("标识符")=="SUP_JN" for x in suppliers), suppliers
|
||||||
|
assert quote["单价"]==36 and quote["报价总额"]==288,quote
|
||||||
|
assert balance["可用余额"]==480,balance
|
||||||
|
assert good["ok"] is True and good["value"]["工单金额"]==288 and good["value"]["状态"]=="本地模拟,未发送",good
|
||||||
|
assert bad["ok"] is False and "采购金额超过" in bad["error"],bad
|
||||||
|
|
||||||
|
frames=[
|
||||||
|
frame(0,"01 / Supplier approval",
|
||||||
|
["$ marqdo call ... 查询采购商", " 采购商状态='正常'"],
|
||||||
|
[f"result: {len(suppliers)} approved suppliers", "SUP_JN / 江南配件 / 正常", "Paused and blacklisted suppliers excluded."],
|
||||||
|
"✓ SUP_JN passes supplier status"),
|
||||||
|
frame(1,"02 / Quote lookup",
|
||||||
|
["$ marqdo call ... 查询采购商价格", " 采购商标识符='SUP_JN' 数量=8 有效秒数=300"],
|
||||||
|
[f"单价: ¥{quote['单价']}",f"数量: {quote['数量']}",f"报价总额: ¥{quote['报价总额']}","报价来源: 示例目录(未接实时接口)"],
|
||||||
|
"✓ ¥36 × 8 = ¥288 — example quote"),
|
||||||
|
frame(2,"03 / Budget check",
|
||||||
|
["$ marqdo call ... 查询余额 已花费=120"],
|
||||||
|
[f"最高预算: ¥{balance['最高预算']}",f"已花费: ¥{balance['已花费']}",f"可用余额: ¥{balance['可用余额']}","还能下单: "+str(balance["还能下单"])],
|
||||||
|
"✓ ¥480 ≥ ¥288 — budget check passes"),
|
||||||
|
frame(3,"04 / Callable simulated order",
|
||||||
|
["$ marqdo call ... 向采购商发工单", " SUP_JN 数量=8 单价=36 已花费=120"],
|
||||||
|
[f"result.ok: {str(good['ok']).lower()}", f"工单金额: ¥{good['value']['工单金额']}",f"状态: {good['value']['状态']}","No ERP message, payment or purchase was made."],
|
||||||
|
"✓ SIMULATED ORDER ONLY — NOT SENT"),
|
||||||
|
frame(4,"05 / Over-budget request denied",
|
||||||
|
["$ marqdo call ... 向采购商发工单", " SUP_JN 数量=8 单价=36 已花费=360"],
|
||||||
|
[f"result.ok: {str(bad['ok']).lower()}","最高预算: ¥600","剩余额度: ¥240","工单金额: ¥288", "错误: "+bad["error"]],
|
||||||
|
"× WORK ORDER REFUSED AT RUNTIME",danger=True)
|
||||||
|
]
|
||||||
|
OUT.mkdir(parents=True,exist_ok=True)
|
||||||
|
name=OUT/"procurement-cli.gif"
|
||||||
|
frames[0].save(name,save_all=True,append_images=frames[1:],duration=[1600,1600,1600,1900,2300],loop=0,optimize=True)
|
||||||
|
assert name.stat().st_size>10000, name
|
||||||
|
print("GIF_WRITTEN",name,name.stat().st_size)
|
||||||
|
|
||||||
|
def make_screenshot(cli):
|
||||||
|
from selenium import webdriver
|
||||||
|
from selenium.webdriver.common.by import By
|
||||||
|
from selenium.webdriver.chrome.options import Options
|
||||||
|
import time
|
||||||
|
import tempfile
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
dest=Path(td)/"view"
|
||||||
|
cmd=[str(cli),"view","output","examples/procurement","--out",str(dest),"--no-exec"]
|
||||||
|
p=subprocess.run(cmd,cwd=ROOT,text=True,capture_output=True,timeout=90)
|
||||||
|
if p.returncode:
|
||||||
|
raise RuntimeError("View output error:\n"+p.stdout+"\n"+p.stderr)
|
||||||
|
pages=sorted(dest.rglob("*.html"),key=lambda p:len(p.parts))
|
||||||
|
print("VIEW_PAGES",[str(p.relative_to(dest)) for p in pages[:40]])
|
||||||
|
if not pages:
|
||||||
|
raise RuntimeError("No HTML pages emitted by Marqdo View")
|
||||||
|
chosen=next((p for p in pages if "向采购商发工单" in p.read_text(encoding="utf-8",errors="replace")),pages[0])
|
||||||
|
opts=Options()
|
||||||
|
for arg in ["--headless=new","--no-sandbox","--disable-dev-shm-usage","--disable-gpu","--window-size=1500,1000"]:
|
||||||
|
opts.add_argument(arg)
|
||||||
|
driver=webdriver.Chrome(options=opts)
|
||||||
|
try:
|
||||||
|
driver.set_window_size(1500,1000)
|
||||||
|
driver.get(chosen.as_uri())
|
||||||
|
time.sleep(2)
|
||||||
|
headings=driver.find_elements(By.CSS_SELECTOR,"h1,h2,h3,h4")
|
||||||
|
matches=[el for el in headings if "向采购商发工单" in el.text]
|
||||||
|
print("VIEW_HEADINGS",[(el.tag_name,el.text[:65]) for el in headings[:25]])
|
||||||
|
if not matches:
|
||||||
|
raise RuntimeError("Couldn't find procurement function heading in exported View")
|
||||||
|
target=matches[0]
|
||||||
|
driver.execute_script("arguments[0].scrollIntoView({block:'start'}); window.scrollBy(0,-115);",target)
|
||||||
|
time.sleep(1)
|
||||||
|
shot=OUT/"procurement-view.png"
|
||||||
|
driver.save_screenshot(str(shot))
|
||||||
|
assert shot.stat().st_size>20000,shot
|
||||||
|
print("VIEW_SCREENSHOT_WRITTEN",shot,shot.stat().st_size)
|
||||||
|
finally:
|
||||||
|
driver.quit()
|
||||||
|
|
||||||
|
if __name__=="__main__":
|
||||||
|
a=argparse.ArgumentParser()
|
||||||
|
a.add_argument("--cli",required=True)
|
||||||
|
args=a.parse_args()
|
||||||
|
make_gif(Path(args.cli).resolve())
|
||||||
|
make_screenshot(Path(args.cli).resolve())
|
||||||
@@ -115,11 +115,13 @@ rm -rf "$PKG_ROOT"
|
|||||||
mkdir -p "$PKG_ROOT" "$BUILD_AREA" "$RUST_CACHE"
|
mkdir -p "$PKG_ROOT" "$BUILD_AREA" "$RUST_CACHE"
|
||||||
|
|
||||||
REUSE_ORIG=0
|
REUSE_ORIG=0
|
||||||
|
ORIG_PUBLISHED=0
|
||||||
ORIG_SRC=""
|
ORIG_SRC=""
|
||||||
if [ "$FORCE_ORIG" != "1" ]; then
|
if [ "$FORCE_ORIG" != "1" ]; then
|
||||||
# Prefer the bytes already accepted by Launchpad (rewriting .orig is rejected).
|
# Prefer the bytes already accepted by Launchpad (rewriting .orig is rejected).
|
||||||
if download_published_orig "$RUST_CACHE/$ORIG_NAME"; then
|
if download_published_orig "$RUST_CACHE/$ORIG_NAME"; then
|
||||||
ORIG_SRC="$RUST_CACHE/$ORIG_NAME"
|
ORIG_SRC="$RUST_CACHE/$ORIG_NAME"
|
||||||
|
ORIG_PUBLISHED=1
|
||||||
elif ORIG_SRC="$(resolve_existing_orig)"; then
|
elif ORIG_SRC="$(resolve_existing_orig)"; then
|
||||||
echo "warning: could not fetch PPA ${ORIG_NAME}; using local ${ORIG_SRC}" >&2
|
echo "warning: could not fetch PPA ${ORIG_NAME}; using local ${ORIG_SRC}" >&2
|
||||||
echo "warning: if its sha256 differs from the archive, Launchpad will reject the upload" >&2
|
echo "warning: if its sha256 differs from the archive, Launchpad will reject the upload" >&2
|
||||||
@@ -223,8 +225,9 @@ ln -sfn "$BUILD_AREA/$ORIG_NAME" "$(dirname "$PKG_ROOT")/$ORIG_NAME"
|
|||||||
ls -lh "$BUILD_AREA/$ORIG_NAME"
|
ls -lh "$BUILD_AREA/$ORIG_NAME"
|
||||||
|
|
||||||
cd "$PKG_ROOT"
|
cd "$PKG_ROOT"
|
||||||
# -sd: debian-only upload (reuse published orig). -sa: include orig (new upstream).
|
# Local cache reuse does not prove Launchpad already has the orig archive.
|
||||||
if [ "$REUSE_ORIG" -eq 1 ]; then
|
# Include its unchanged bytes until the published download succeeds.
|
||||||
|
if [ "$ORIG_PUBLISHED" -eq 1 ]; then
|
||||||
DEBUILD_ORIG_FLAG="-sd"
|
DEBUILD_ORIG_FLAG="-sd"
|
||||||
echo "==> debuild -S ${DEBUILD_ORIG_FLAG} (key ${GPG_KEY}; not re-uploading .orig)"
|
echo "==> debuild -S ${DEBUILD_ORIG_FLAG} (key ${GPG_KEY}; not re-uploading .orig)"
|
||||||
else
|
else
|
||||||
|
|||||||
+47
-3
@@ -124,9 +124,53 @@ import:
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn fetch_mq_load_returns_fetch_effect() {
|
fn fetch_mq_load_returns_fetch_effect() {
|
||||||
let src = std::fs::read_to_string("examples/browser-hello/fetch.mq.md")
|
// A protocol regression must not depend on a retired public example.
|
||||||
.expect("fetch.mq.md");
|
let src = r###"---
|
||||||
let (mut sess, wire) = BrowserSession::boot(&src).expect("boot");
|
markup: occlusion
|
||||||
|
title: browser fetch (C4)
|
||||||
|
description: fetch/after effects via lib/browser — no json glue
|
||||||
|
import:
|
||||||
|
browser: lib/browser.mq.md
|
||||||
|
---
|
||||||
|
|
||||||
|
# main
|
||||||
|
|
||||||
|
`wire` =
|
||||||
|
|
||||||
|
| @ | 选择器 | 事件 | 调用 |
|
||||||
|
|---|--------|------|------|
|
||||||
|
| 1 | "#load" | click | load |
|
||||||
|
| 2 | "#ping" | click | ping |
|
||||||
|
|
||||||
|
*`wire`*
|
||||||
|
|
||||||
|
## load
|
||||||
|
**`msg` = > browser.set_text sel="#status" text="loading…"**
|
||||||
|
**`req` = > browser.fetch url="https://httpbin.org/uuid" then="on_uuid"**
|
||||||
|
*> browser.merge a=msg b=req*
|
||||||
|
|
||||||
|
## on_uuid
|
||||||
|
+ `ok`
|
||||||
|
+ `status`
|
||||||
|
+ `body`=""
|
||||||
|
+ `error`=""
|
||||||
|
|
||||||
|
1. ok
|
||||||
|
*> browser.set_text sel="#status" text=body*
|
||||||
|
2. *
|
||||||
|
*> browser.set_text sel="#status" text="fetch failed"*
|
||||||
|
|
||||||
|
## ping
|
||||||
|
**`msg` = > browser.set_text sel="#status" text="wait 600ms…"**
|
||||||
|
**`t` = > browser.after ms=600 then="on_ping"**
|
||||||
|
*> browser.merge a=msg b=t*
|
||||||
|
|
||||||
|
## on_ping
|
||||||
|
+ `ok`=True
|
||||||
|
|
||||||
|
*> browser.set_text sel="#status" text="pong"*
|
||||||
|
"###;
|
||||||
|
let (mut sess, wire) = BrowserSession::boot(src).expect("boot");
|
||||||
assert!(matches!(wire, Value::List(_)));
|
assert!(matches!(wire, Value::List(_)));
|
||||||
let v = sess.call("load", "{}").expect("load");
|
let v = sess.call("load", "{}").expect("load");
|
||||||
let j = value_as_json(&v).unwrap();
|
let j = value_as_json(&v).unwrap();
|
||||||
|
|||||||
+95
-206
@@ -55,22 +55,23 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot
|
|||||||
let body_start = skip_frontmatter_end(&lines).unwrap_or(1);
|
let body_start = skip_frontmatter_end(&lines).unwrap_or(1);
|
||||||
let mut para: Vec<(u32, String)> = Vec::new();
|
let mut para: Vec<(u32, String)> = Vec::new();
|
||||||
let flush_para = |para: &mut Vec<(u32, String)>, out: &mut String| {
|
let flush_para = |para: &mut Vec<(u32, String)>, out: &mut String| {
|
||||||
if para.is_empty() {
|
if para.is_empty() { return; }
|
||||||
return;
|
|
||||||
}
|
|
||||||
let first_line = para[0].0;
|
let first_line = para[0].0;
|
||||||
let text = para
|
let source_anchors = para.iter().skip(1).map(|(line,_)|
|
||||||
.iter()
|
format!(r#"<span class="source-line-anchor" id="stmt-{line}" aria-hidden="true"></span>"#)).collect::<String>();
|
||||||
.map(|(_, t)| t.as_str())
|
let mut replacements = Vec::new();
|
||||||
.collect::<Vec<_>>()
|
let mut notes = String::new();
|
||||||
.join(" ");
|
let text = para.iter().map(|(line, text)| {
|
||||||
let source_anchors=para.iter().skip(1).map(|(line,_)|format!(r#"<span class="source-line-anchor" id="stmt-{line}" aria-hidden="true"></span>"#)).collect::<String>();
|
let fragment = super::logic::narrative(*line, text, 0);
|
||||||
|
replacements.extend(fragment.replacements);
|
||||||
|
notes.push_str(&fragment.notes);
|
||||||
|
fragment.markdown
|
||||||
|
}).collect::<Vec<_>>().join(" ");
|
||||||
para.clear();
|
para.clear();
|
||||||
let md = comment_markdown_to_html(&text);
|
let md = super::logic::replace(comment_markdown_to_html(&text), &replacements);
|
||||||
|
let band = render_document_band(&[], ¬es);
|
||||||
out.push_str(&format!(
|
out.push_str(&format!(
|
||||||
r#"<div class="doc-block" data-line="{line}" id="stmt-{line}">{source_anchors}<div class="doc-prose">{md}</div></div>"#,
|
r#"<div class="doc-block" data-line="{first_line}" id="stmt-{first_line}">{source_anchors}<div class="doc-prose">{md}</div>{band}</div>"#
|
||||||
line = first_line,
|
|
||||||
md = md
|
|
||||||
));
|
));
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -218,7 +219,7 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot
|
|||||||
}
|
}
|
||||||
flush_para(&mut para, &mut out);
|
flush_para(&mut para, &mut out);
|
||||||
out.push_str("</div>");
|
out.push_str("</div>");
|
||||||
out
|
super::logic::link_definitions(out, module)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy)]
|
||||||
@@ -305,60 +306,39 @@ fn render_table_block(
|
|||||||
line = first_line
|
line = first_line
|
||||||
);
|
);
|
||||||
let mut header_done = false;
|
let mut header_done = false;
|
||||||
for (idx, (_ln, row)) in rows.iter().enumerate() {
|
let mut notes = String::new();
|
||||||
if looks_like_table_sep(row) {
|
for (idx, (line, row)) in rows.iter().enumerate() {
|
||||||
continue;
|
if looks_like_table_sep(row) { continue; }
|
||||||
}
|
let cells: Vec<&str> = row.trim().trim_matches('|').split('|').map(str::trim).collect();
|
||||||
let cells: Vec<&str> = row
|
let rendered: Vec<String> = cells.iter().map(|cell| {
|
||||||
.trim()
|
let base = cell.as_ptr() as usize - row.as_ptr() as usize;
|
||||||
.trim_matches('|')
|
notes.push_str(&super::logic::narrative(*line, cell, base).notes);
|
||||||
.split('|')
|
render_narrative_inline(*line, cell, base)
|
||||||
.map(|c| c.trim())
|
}).collect();
|
||||||
.collect();
|
|
||||||
if !header_done {
|
if !header_done {
|
||||||
html.push_str("<thead><tr>");
|
html.push_str("<thead><tr>");
|
||||||
for c in &cells {
|
for cell in &rendered { html.push_str(&format!("<th>{cell}</th>")); }
|
||||||
html.push_str(&format!("<th>{}</th>", escape(c)));
|
|
||||||
}
|
|
||||||
html.push_str("</tr></thead><tbody>");
|
html.push_str("</tr></thead><tbody>");
|
||||||
header_done = true;
|
header_done = true;
|
||||||
// If next is sep, skip handled above; if only one data row treated as header+body empty ok
|
if idx + 1 < rows.len() && looks_like_table_sep(&rows[idx + 1].1) { continue; }
|
||||||
if idx + 1 < rows.len() && looks_like_table_sep(&rows[idx + 1].1) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
// Single-row table without sep: also emit as body
|
|
||||||
if rows.len() == 1 {
|
if rows.len() == 1 {
|
||||||
html.push_str("<tr>");
|
html.push_str("<tr>");
|
||||||
for c in &cells {
|
for cell in &cells { html.push_str(&format!("<td>{}</td>", escape(cell))); }
|
||||||
html.push_str(&format!("<td>{}</td>", escape(c)));
|
|
||||||
}
|
|
||||||
html.push_str("</tr>");
|
html.push_str("</tr>");
|
||||||
}
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
html.push_str("<tr>");
|
html.push_str("<tr>");
|
||||||
for c in &cells {
|
for cell in &rendered { html.push_str(&format!("<td>{cell}</td>")); }
|
||||||
html.push_str(&format!("<td>{}</td>", escape(c)));
|
|
||||||
}
|
|
||||||
html.push_str("</tr>");
|
html.push_str("</tr>");
|
||||||
}
|
}
|
||||||
if header_done {
|
if header_done { html.push_str("</tbody>"); }
|
||||||
html.push_str("</tbody>");
|
|
||||||
}
|
|
||||||
html.push_str("</table>");
|
html.push_str("</table>");
|
||||||
// Annots on first table line (bind of collection).
|
// The table is already a readable collection; retain only non-call results.
|
||||||
if let Some(list) = by_line.get(&first_line) {
|
let owned: Vec<ViewAnnot> = by_line.get(&first_line).into_iter().flatten()
|
||||||
// A table is already its own readable value; a call chip would collapse
|
.filter(|a| a.kind != crate::view::annot::AnnotKind::Call)
|
||||||
// the whole collection into an ellipsis. Keep only non-call chips.
|
.map(|a| (**a).clone()).collect();
|
||||||
let owned: Vec<ViewAnnot> = list
|
html.push_str(&render_document_band(&owned, ¬es));
|
||||||
.iter()
|
|
||||||
.filter(|a| a.kind != crate::view::annot::AnnotKind::Call)
|
|
||||||
.map(|a| (*a).clone())
|
|
||||||
.collect();
|
|
||||||
if !owned.is_empty() {
|
|
||||||
html.push_str(&render_annot_band(&owned, MAX_VISIBLE_ANNOTS));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if let Some(body) = writebacks.get(&first_line) {
|
if let Some(body) = writebacks.get(&first_line) {
|
||||||
html.push_str(&crate::view::render::render_output_card(first_line, body));
|
html.push_str(&crate::view::render::render_output_card(first_line, body));
|
||||||
}
|
}
|
||||||
@@ -526,11 +506,7 @@ fn render_list_block(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let notes = if occluded_lines.contains(&lines[i].line_no) {
|
let notes = render_logic_notes(lines[i].line_no, head, &scan_prose_line(head), occluded_lines.contains(&lines[i].line_no));
|
||||||
render_logic_notes(lines[i].line_no, head, &[])
|
|
||||||
} else {
|
|
||||||
String::new()
|
|
||||||
};
|
|
||||||
html.push_str(&render_document_band(&head_annots, ¬es));
|
html.push_str(&render_document_band(&head_annots, ¬es));
|
||||||
// Body: following lines with greater indent until next sibling.
|
// Body: following lines with greater indent until next sibling.
|
||||||
i += 1;
|
i += 1;
|
||||||
@@ -622,7 +598,7 @@ fn render_surface_line(
|
|||||||
if head.trim() == "*" {
|
if head.trim() == "*" {
|
||||||
return r#"<span class="mq-else">else</span>"#.into();
|
return r#"<span class="mq-else">else</span>"#.into();
|
||||||
}
|
}
|
||||||
format!(r#"<span class="doc-cond">{}</span>"#, escape(head))
|
format!(r#"<span class="doc-cond">{}</span>"#, render_narrative_inline(line_no, head, 0))
|
||||||
} else {
|
} else {
|
||||||
let annots = by_line.get(&line_no).map(|v| v.as_slice()).unwrap_or(&[]);
|
let annots = by_line.get(&line_no).map(|v| v.as_slice()).unwrap_or(&[]);
|
||||||
render_prose_with_marks(line_no, head, &bits, annots, false)
|
render_prose_with_marks(line_no, head, &bits, annots, false)
|
||||||
@@ -741,156 +717,57 @@ fn parse_args_brief(brief: &str) -> HashMap<String, String> {
|
|||||||
|
|
||||||
/// Display-only source spans. The AST decides whether this line contains an occlusion.
|
/// Display-only source spans. The AST decides whether this line contains an occlusion.
|
||||||
/// Scan only executable fragments, preserving quoted links as literal data.
|
/// Scan only executable fragments, preserving quoted links as literal data.
|
||||||
struct OcclusionSpan<'a> { start: usize, end: usize, label: &'a str, payload: &'a str }
|
fn occlusion_spans(text: &str) -> Vec<super::logic::Span<'_>> {
|
||||||
fn occlusion_spans(text: &str) -> Vec<OcclusionSpan<'_>> {
|
super::logic::spans(text, true)
|
||||||
let bytes = text.as_bytes();
|
|
||||||
let mut out = Vec::new();
|
|
||||||
let mut i = 0;
|
|
||||||
while i < bytes.len() {
|
|
||||||
if matches!(bytes[i], b'"' | b'\'' | b'`') {
|
|
||||||
let quote = bytes[i];
|
|
||||||
i += 1;
|
|
||||||
while i < bytes.len() {
|
|
||||||
if bytes[i] == b'\\' {
|
|
||||||
i += 2;
|
|
||||||
} else if bytes[i] == quote {
|
|
||||||
i += 1;
|
|
||||||
break;
|
|
||||||
} else {
|
|
||||||
i += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if bytes[i] == b'\\' {
|
|
||||||
i += 2;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if bytes[i] != b'[' || bytes.get(i + 1) == Some(&b'^') {
|
|
||||||
i += 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let start = i;
|
|
||||||
let mut j = i + 1;
|
|
||||||
let mut depth = 1;
|
|
||||||
while j < bytes.len() {
|
|
||||||
match bytes[j] {
|
|
||||||
b'\\' => {
|
|
||||||
j += 2;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
b'[' => depth += 1,
|
|
||||||
b']' => {
|
|
||||||
depth -= 1;
|
|
||||||
if depth == 0 {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
j += 1;
|
|
||||||
}
|
|
||||||
if depth != 0 || bytes.get(j + 1) != Some(&b'(') {
|
|
||||||
i += 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let label_end = j;
|
|
||||||
j += 2;
|
|
||||||
let payload_start = j;
|
|
||||||
depth = 1;
|
|
||||||
while j < bytes.len() {
|
|
||||||
match bytes[j] {
|
|
||||||
b'"' | b'\'' | b'`' => {
|
|
||||||
let quote = bytes[j];
|
|
||||||
j += 1;
|
|
||||||
while j < bytes.len() {
|
|
||||||
if bytes[j] == b'\\' {
|
|
||||||
j += 2;
|
|
||||||
} else if bytes[j] == quote {
|
|
||||||
j += 1;
|
|
||||||
break;
|
|
||||||
} else {
|
|
||||||
j += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
b'(' => depth += 1,
|
|
||||||
b')' => {
|
|
||||||
depth -= 1;
|
|
||||||
if depth == 0 {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
j += 1;
|
|
||||||
}
|
|
||||||
if depth == 0 {
|
|
||||||
out.push(OcclusionSpan {
|
|
||||||
start,
|
|
||||||
end: j + 1,
|
|
||||||
label: &text[start + 1..label_end],
|
|
||||||
payload: text[payload_start..j].trim(),
|
|
||||||
});
|
|
||||||
i = j + 1;
|
|
||||||
} else {
|
|
||||||
i += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
out
|
|
||||||
}
|
|
||||||
fn logic_id(line: u32, at: usize) -> String {
|
|
||||||
format!("logic-{line}-{at}")
|
|
||||||
}
|
}
|
||||||
fn render_occlusion_text(line: u32, text: &str, base: usize) -> String {
|
fn render_occlusion_text(line: u32, text: &str, base: usize) -> String {
|
||||||
let mut html = String::new();
|
let mut html = String::new();
|
||||||
let mut cursor = 0;
|
let mut cursor = 0;
|
||||||
for span in occlusion_spans(text) {
|
for span in occlusion_spans(text) {
|
||||||
html.push_str(&escape(&text[cursor..span.start]));
|
html.push_str(&escape(&text[cursor..span.start]));
|
||||||
let id = logic_id(line, base + span.start);
|
html.push_str(&super::logic::source(line, &span, base));
|
||||||
let label = if span.label.is_empty() {
|
|
||||||
"未命名动作"
|
|
||||||
} else {
|
|
||||||
span.label
|
|
||||||
};
|
|
||||||
html.push_str(&format!(r#"<button type="button" class="occl-label" id="{id}-source" data-logic-id="{id}" aria-controls="{id}-note" title="查看实际逻辑(阅读不会执行)">{}</button>"#,escape(label)));
|
|
||||||
if span.payload.is_empty() {
|
|
||||||
html.push_str(r#"<span class="occl-stub">待补充实际逻辑</span>"#);
|
|
||||||
}
|
|
||||||
cursor = span.end;
|
cursor = span.end;
|
||||||
}
|
}
|
||||||
html.push_str(&escape(&text[cursor..]));
|
html.push_str(&escape(&text[cursor..]));
|
||||||
html
|
html
|
||||||
}
|
}
|
||||||
fn render_logic_notes(line: u32, text: &str, bits: &[ProseBit]) -> String {
|
fn render_logic_notes(line: u32, text: &str, bits: &[ProseBit], occluded: bool) -> String {
|
||||||
let mut notes = String::new();
|
let mut notes = String::new();
|
||||||
let fragments: Vec<(usize, usize, &str)> =
|
if occluded && bits.iter().all(|bit| matches!(bit, ProseBit::Decl { .. })) {
|
||||||
if bits.iter().all(|bit| matches!(bit, ProseBit::Decl { .. })) {
|
for span in occlusion_spans(text) {
|
||||||
vec![(0, text.len(), text)]
|
notes.push_str(&super::logic::note(line, &span, 0, true));
|
||||||
} else {
|
|
||||||
bits.iter()
|
|
||||||
.filter_map(|bit| match bit {
|
|
||||||
ProseBit::BoldCode { inner, .. } | ProseBit::ItalicReturn { inner, .. } => {
|
|
||||||
Some((bit_at(bit), prose_bit_end(text, bit), inner.as_str()))
|
|
||||||
}
|
|
||||||
_ => None,
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
};
|
|
||||||
for (start, end, fragment) in fragments {
|
|
||||||
for span in occlusion_spans(fragment) {
|
|
||||||
let id = logic_id(line, start + span.start);
|
|
||||||
let payload = if span.payload.is_empty() {
|
|
||||||
"待补充实际逻辑;当前空遮蔽返回 None。"
|
|
||||||
} else {
|
|
||||||
span.payload
|
|
||||||
};
|
|
||||||
notes.push_str(&format!(r#"<details class="annot-chip annot-implementation" id="{id}-note" data-annot-id="{id}" data-annot-kind="implementation" data-anchor-line="{line}" data-anchor-byte-start="{start}" data-anchor-byte-end="{end}"><summary class="annot-label">实际逻辑 · {label}</summary><code class="annot-value occl-code">{payload}</code><small class="logic-hint">源码说明 · 不是运行结果</small></details>"#,label=escape(span.label),payload=escape(payload)));
|
|
||||||
}
|
}
|
||||||
|
return notes;
|
||||||
|
}
|
||||||
|
let mut cursor = 0;
|
||||||
|
for bit in bits {
|
||||||
|
let start = bit_at(bit);
|
||||||
|
let end = prose_bit_end(text, bit);
|
||||||
|
if start > cursor {
|
||||||
|
notes.push_str(&super::logic::narrative(line, &text[cursor..start], cursor).notes);
|
||||||
|
}
|
||||||
|
if occluded {
|
||||||
|
if let ProseBit::BoldCode { inner, .. } | ProseBit::ItalicReturn { inner, .. } = bit {
|
||||||
|
for span in occlusion_spans(inner) {
|
||||||
|
notes.push_str(&super::logic::note(line, &span, inner_offset(text, bit), true));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cursor = end.max(cursor);
|
||||||
|
}
|
||||||
|
if cursor < text.len() {
|
||||||
|
notes.push_str(&super::logic::narrative(line, &text[cursor..], cursor).notes);
|
||||||
}
|
}
|
||||||
notes
|
notes
|
||||||
}
|
}
|
||||||
|
fn inner_offset(text: &str, bit: &ProseBit) -> usize {
|
||||||
|
let start = bit_at(bit);
|
||||||
|
match bit {
|
||||||
|
ProseBit::BoldCode { inner, .. } | ProseBit::ItalicReturn { inner, .. } =>
|
||||||
|
start + text[start..prose_bit_end(text, bit)].find(inner).unwrap_or(0),
|
||||||
|
_ => start,
|
||||||
|
}
|
||||||
|
}
|
||||||
fn render_document_band(annots: &[ViewAnnot], notes: &str) -> String {
|
fn render_document_band(annots: &[ViewAnnot], notes: &str) -> String {
|
||||||
let band = render_annot_band(annots, MAX_VISIBLE_ANNOTS);
|
let band = render_annot_band(annots, MAX_VISIBLE_ANNOTS);
|
||||||
if notes.is_empty() {
|
if notes.is_empty() {
|
||||||
@@ -1000,8 +877,8 @@ fn render_line_block(
|
|||||||
.map(|a| (*a).clone())
|
.map(|a| (*a).clone())
|
||||||
.collect()
|
.collect()
|
||||||
};
|
};
|
||||||
let notes = if special.is_none() && occluded_lines.contains(&line_no) {
|
let notes = if special.is_none() {
|
||||||
render_logic_notes(line_no, text, bits)
|
render_logic_notes(line_no, text, bits, occluded_lines.contains(&line_no))
|
||||||
} else {
|
} else {
|
||||||
String::new()
|
String::new()
|
||||||
};
|
};
|
||||||
@@ -1066,15 +943,16 @@ fn render_narrative_fence(lines: &[ClassifiedLine], start: usize) -> (String, us
|
|||||||
|
|
||||||
/// Preserve ordinary Markdown links/emphasis outside executable marks. Raw HTML
|
/// Preserve ordinary Markdown links/emphasis outside executable marks. Raw HTML
|
||||||
/// stays literal here, as it did in mixed executable prose before this renderer.
|
/// stays literal here, as it did in mixed executable prose before this renderer.
|
||||||
fn render_narrative_inline(text: &str) -> String {
|
fn render_narrative_inline(line: u32, text: &str, base: usize) -> String {
|
||||||
let inner = text.trim();
|
let inner = text.trim();
|
||||||
if inner.is_empty() {
|
if inner.is_empty() {
|
||||||
return escape(text);
|
return escape(text);
|
||||||
}
|
}
|
||||||
let start = text.find(inner).unwrap();
|
let start = text.find(inner).unwrap();
|
||||||
let end = start + inner.len();
|
let end = start + inner.len();
|
||||||
let parser = pulldown_cmark::Parser::new(inner).map(|event| match event {
|
let fragment = super::logic::narrative(line, inner, base + start);
|
||||||
pulldown_cmark::Event::Html(html) => pulldown_cmark::Event::Text(html),
|
let parser = pulldown_cmark::Parser::new(&fragment.markdown).map(|event| match event {
|
||||||
|
pulldown_cmark::Event::Html(html) | pulldown_cmark::Event::InlineHtml(html) => pulldown_cmark::Event::Text(html),
|
||||||
other => other,
|
other => other,
|
||||||
});
|
});
|
||||||
let mut html = String::new();
|
let mut html = String::new();
|
||||||
@@ -1085,7 +963,7 @@ fn render_narrative_inline(text: &str) -> String {
|
|||||||
else {
|
else {
|
||||||
return escape(text);
|
return escape(text);
|
||||||
};
|
};
|
||||||
format!("{}{}{}", escape(&text[..start]), body, escape(&text[end..]))
|
format!("{}{}{}", escape(&text[..start]), super::logic::replace(body.to_string(), &fragment.replacements), escape(&text[end..]))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Render prose with markers stripped; show surface inner text only.
|
/// Render prose with markers stripped; show surface inner text only.
|
||||||
@@ -1102,7 +980,7 @@ fn render_prose_with_marks(
|
|||||||
let start = bit_at(bit);
|
let start = bit_at(bit);
|
||||||
let end = prose_bit_end(text, bit);
|
let end = prose_bit_end(text, bit);
|
||||||
if start > cursor {
|
if start > cursor {
|
||||||
html.push_str(&render_narrative_inline(&text[cursor..start]));
|
html.push_str(&render_narrative_inline(line_no, &text[cursor..start], cursor));
|
||||||
}
|
}
|
||||||
if start < end && end <= text.len() {
|
if start < end && end <= text.len() {
|
||||||
let (cls, display) = bit_display(bit);
|
let (cls, display) = bit_display(bit);
|
||||||
@@ -1117,13 +995,13 @@ fn render_prose_with_marks(
|
|||||||
start = start,
|
start = start,
|
||||||
end = end,
|
end = end,
|
||||||
aid = escape(annot_id),
|
aid = escape(annot_id),
|
||||||
inner = if occluded && !matches!(bit,ProseBit::Decl{..}) {render_occlusion_text(line_no,&display,start)}else{escape(&display)},
|
inner = if occluded && !matches!(bit,ProseBit::Decl{..}) {render_occlusion_text(line_no,&display,inner_offset(text, bit))}else{escape(&display)},
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
cursor = end.max(cursor);
|
cursor = end.max(cursor);
|
||||||
}
|
}
|
||||||
if cursor < text.len() {
|
if cursor < text.len() {
|
||||||
html.push_str(&render_narrative_inline(&text[cursor..]));
|
html.push_str(&render_narrative_inline(line_no, &text[cursor..], cursor));
|
||||||
}
|
}
|
||||||
html
|
html
|
||||||
}
|
}
|
||||||
@@ -1480,7 +1358,7 @@ mod tests {
|
|||||||
let module = crate::parse::parse_source(src).unwrap();
|
let module = crate::parse::parse_source(src).unwrap();
|
||||||
let html = render_module_document(&module, src, &[]);
|
let html = render_module_document(&module, src, &[]);
|
||||||
assert!(
|
assert!(
|
||||||
html.contains("<a href=\"https://github.com/cflmy/marqdo\">仓库</a>"),
|
html.contains("href=\"https://github.com/cflmy/marqdo\"") && html.contains(">仓库</a>") && html.contains("data-logic-kind=\"link\""),
|
||||||
"{html}"
|
"{html}"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1708,7 +1586,7 @@ fn render_syntax_guide() -> String {
|
|||||||
"hr"=>"分隔内容,不能把分隔线当作函数返回。", "writeback"=>"程序写回的结果,区别于作者原始正文。",
|
"hr"=>"分隔内容,不能把分隔线当作函数返回。", "writeback"=>"程序写回的结果,区别于作者原始正文。",
|
||||||
"ident"=>"叙述中的参数或变量;默认值跟在名称之后。", "bold-code"=>"执行语句:赋值、调用或计算;不是打印,也不是返回。",
|
"ident"=>"叙述中的参数或变量;默认值跟在名称之后。", "bold-code"=>"执行语句:赋值、调用或计算;不是打印,也不是返回。",
|
||||||
"italic-return"=>"返回表达式;句中以返回、Return 等明确引出。", "empty-return"=>"显式返回空值或结束当前函数。",
|
"italic-return"=>"返回表达式;句中以返回、Return 等明确引出。", "empty-return"=>"显式返回空值或结束当前函数。",
|
||||||
"link-index"=>"默认模式是 [动作](实现) 遮蔽,正文只显示动作;空括号表示待补充实际逻辑。classic 模式才解释为旧链接取元。",
|
"link-index"=>"正文显示描述,侧注按函数与参数、可跳转链接、结构化内容展示括号内的细节;空括号表示待补充实际逻辑。阅读不会执行调用。classic 模式保留旧链接取元。",
|
||||||
"bracket-call"=>"兼容的带修饰调用;不能把任意普通链接当作执行授权。", "footnote-index"=>"兼容的脚注取元;当前库优先用 access 读取集合。",
|
"bracket-call"=>"兼容的带修饰调用;不能把任意普通链接当作执行授权。", "footnote-index"=>"兼容的脚注取元;当前库优先用 access 读取集合。",
|
||||||
"soft-emphasis"=>"普通强调仍属于文字;界面按真实解析结果区分强调、语句与返回。", _=>"按源码中的真实结构阅读。"
|
"soft-emphasis"=>"普通强调仍属于文字;界面按真实解析结果区分强调、语句与返回。", _=>"按源码中的真实结构阅读。"
|
||||||
};
|
};
|
||||||
@@ -1764,6 +1642,15 @@ mod readable_occlusion_tests {
|
|||||||
assert!(html.contains("当前空遮蔽返回 None"));
|
assert!(html.contains("当前空遮蔽返回 None"));
|
||||||
}
|
}
|
||||||
#[test]
|
#[test]
|
||||||
|
fn table_links_and_prose_content_are_readable_with_exact_source_notes() {
|
||||||
|
let html = render("# main\n\n| 内容 | 说明 |\n| --- | --- |\n| [指南](guide.mq.md) | [解释](plain explanatory text with **emphasis**) |\n\n*None*\n");
|
||||||
|
assert!(html.contains(">指南</a>"));
|
||||||
|
assert!(html.contains("<strong>emphasis</strong>"));
|
||||||
|
assert_eq!(html.matches("class=\"annot-chip annot-implementation\"").count(), 2);
|
||||||
|
assert_eq!(html.matches("data-logic-kind=\"link\"").count(), 1);
|
||||||
|
assert_eq!(html.matches("data-logic-kind=\"content\"").count(), 1);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
fn navigation_and_quoted_links_are_not_executable_occlusions() {
|
fn navigation_and_quoted_links_are_not_executable_occlusions() {
|
||||||
let html=render("# main\n\n参阅 [普通链接](https://example.com/guide)。\n\n得到**literal = \"[数据链接](should_stay_text)\"**,以及**value = [真实动作](5)**,参阅 [混合链接](https://example.com/mixed)。\n");
|
let html=render("# main\n\n参阅 [普通链接](https://example.com/guide)。\n\n得到**literal = \"[数据链接](should_stay_text)\"**,以及**value = [真实动作](5)**,参阅 [混合链接](https://example.com/mixed)。\n");
|
||||||
assert!(html.contains("href=\"https://example.com/guide\""));
|
assert!(html.contains("href=\"https://example.com/guide\""));
|
||||||
@@ -1771,9 +1658,11 @@ mod readable_occlusion_tests {
|
|||||||
assert_eq!(
|
assert_eq!(
|
||||||
html.matches("class=\"annot-chip annot-implementation\"")
|
html.matches("class=\"annot-chip annot-implementation\"")
|
||||||
.count(),
|
.count(),
|
||||||
1
|
3
|
||||||
);
|
);
|
||||||
assert!(html.contains("[数据链接](should_stay_text)"));
|
assert!(html.contains("[数据链接](should_stay_text)"));
|
||||||
|
assert_eq!(html.matches("data-logic-kind=\"link\"").count(), 2);
|
||||||
|
assert_eq!(html.matches("文档引用 · 阅读不会执行").count(), 2);
|
||||||
let classic = render("---\nmarkup: classic\n---\n# main\n\n**value = [key](`record`)**\n");
|
let classic = render("---\nmarkup: classic\n---\n# main\n\n**value = [key](`record`)**\n");
|
||||||
assert!(!classic.contains("class=\"annot-chip annot-implementation\""));
|
assert!(!classic.contains("class=\"annot-chip annot-implementation\""));
|
||||||
}
|
}
|
||||||
|
|||||||
+99
-2
@@ -4012,6 +4012,102 @@ body.notebook-page .wb-source-text { color: var(--nb-text); }
|
|||||||
</script>"#
|
</script>"#
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Resolve links to documents in this View tree; retain the authored target so
|
||||||
|
/// live responses and static exports can share the same read model.
|
||||||
|
pub(crate) fn document_links(source: &str, files: &[PathBuf], rel: &str, links: &LinkMode) -> String {
|
||||||
|
fn attribute<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
|
||||||
|
let start = tag.find(&format!(" {name}=\""))? + name.len() + 3;
|
||||||
|
tag[start..].split('"').next()
|
||||||
|
}
|
||||||
|
fn decode(value: &str) -> String {
|
||||||
|
value.replace(""", "\"").replace("'", "'")
|
||||||
|
.replace("<", "<").replace(">", ">").replace("&", "&")
|
||||||
|
}
|
||||||
|
let mut out = String::new();
|
||||||
|
let mut rest = source;
|
||||||
|
while let Some(start) = rest.find("<a ") {
|
||||||
|
out.push_str(&rest[..start]);
|
||||||
|
rest = &rest[start..];
|
||||||
|
let Some(end) = rest.find('>') else { break };
|
||||||
|
let tag = &rest[..=end];
|
||||||
|
let mut replacement = None;
|
||||||
|
if let Some(original) = attribute(tag, "data-document-href") {
|
||||||
|
let target = decode(original);
|
||||||
|
let split = target.find(['?', '#']).unwrap_or(target.len());
|
||||||
|
let path = &target[..split];
|
||||||
|
if path.ends_with(".mq.md") && !path.contains(':') && !path.starts_with("//") {
|
||||||
|
let path = percent_decode_document_path(path);
|
||||||
|
let joined = if path.starts_with('/') { PathBuf::from(path.trim_start_matches('/')) }
|
||||||
|
else { Path::new(rel).parent().unwrap_or(Path::new("")).join(path) };
|
||||||
|
let mut parts = Vec::new();
|
||||||
|
let mut valid = true;
|
||||||
|
for component in joined.components() {
|
||||||
|
match component {
|
||||||
|
Component::Normal(part) => parts.push(part.to_string_lossy().into_owned()),
|
||||||
|
Component::ParentDir => { if parts.pop().is_none() { valid = false; break; } }
|
||||||
|
Component::CurDir => {}
|
||||||
|
_ => { valid = false; break; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let resolved = parts.join("/");
|
||||||
|
if valid && files.iter().any(|file| file.to_string_lossy().replace('\\', "/") == resolved) {
|
||||||
|
if let Some(current) = attribute(tag, "href") {
|
||||||
|
let suffix = &target[split..];
|
||||||
|
let suffix = if matches!(links, LinkMode::Live) && suffix.starts_with('?') {
|
||||||
|
format!("&{}", &suffix[1..])
|
||||||
|
} else { suffix.to_string() };
|
||||||
|
let href = format!("{}{suffix}", href_file(links, &resolved));
|
||||||
|
replacement = Some(tag.replacen(&format!(" href=\"{current}\""), &format!(" href=\"{}\"", escape(&href)), 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push_str(replacement.as_deref().unwrap_or(tag));
|
||||||
|
rest = &rest[end+1..];
|
||||||
|
}
|
||||||
|
out.push_str(rest);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod document_link_tests {
|
||||||
|
use super::*;
|
||||||
|
#[test]
|
||||||
|
fn document_links_round_trip_between_live_and_offline_views() {
|
||||||
|
let files = vec![PathBuf::from("docs/entry.mq.md"), PathBuf::from("read me.mq.md")];
|
||||||
|
let tag = r#"<a href="../read%20me.mq.md?stdin=a&b=c#fn-2" data-document-href="../read%20me.mq.md?stdin=a&b=c#fn-2">打开</a>"#;
|
||||||
|
let live = document_links(tag, &files, "docs/entry.mq.md", &LinkMode::Live);
|
||||||
|
assert!(live.contains("href=\"/file?path=read%20me.mq.md&stdin=a&b=c#fn-2\""), "{live}");
|
||||||
|
let offline = document_links(&live, &files, "docs/entry.mq.md", &LinkMode::Static {from: Some("docs/entry.mq.md".into())});
|
||||||
|
assert!(offline.contains("href=\"../read me.mq.md.html?stdin=a&b=c#fn-2\""), "{offline}");
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn unknown_paths_external_urls_and_encoded_unicode_stay_intact() {
|
||||||
|
let files = vec![PathBuf::from("next.mq.md")];
|
||||||
|
for target in ["../../next.mq.md", "https://example.com/next.mq.md", "missing.mq.md", "%中.mq.md"] {
|
||||||
|
let tag = format!("<a href=\"{target}\" data-document-href=\"{target}\">目标</a>");
|
||||||
|
assert_eq!(document_links(&tag, &files, "entry.mq.md", &LinkMode::Live), tag);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn percent_decode_document_path(value: &str) -> String {
|
||||||
|
let bytes = value.as_bytes();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut i = 0;
|
||||||
|
while i < bytes.len() {
|
||||||
|
if bytes[i] == b'%' && i+2 < bytes.len() {
|
||||||
|
let hex = |b: u8| (b as char).to_digit(16).map(|v| v as u8);
|
||||||
|
if let (Some(a), Some(b)) = (hex(bytes[i+1]), hex(bytes[i+2])) {
|
||||||
|
out.push(a*16+b); i += 3; continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push(bytes[i]); i += 1;
|
||||||
|
}
|
||||||
|
String::from_utf8(out).unwrap_or_else(|_| value.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkMode) -> String {
|
pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkMode) -> String {
|
||||||
let nav = nav_html(files, Some(rel), links);
|
let nav = nav_html(files, Some(rel), links);
|
||||||
let (status, status_label, out_text) = if vm.awaiting_input {
|
let (status, status_label, out_text) = if vm.awaiting_input {
|
||||||
@@ -4124,10 +4220,11 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM
|
|||||||
} else {
|
} else {
|
||||||
vm.outline_html.clone()
|
vm.outline_html.clone()
|
||||||
};
|
};
|
||||||
|
let structure_html = document_links(&vm.structure_html, files, rel, links);
|
||||||
let structure_block = if outline_block.is_empty() {
|
let structure_block = if outline_block.is_empty() {
|
||||||
format!(
|
format!(
|
||||||
r#"<div class="structure" id="structure">{structure}</div>"#,
|
r#"<div class="structure" id="structure">{structure}</div>"#,
|
||||||
structure = vm.structure_html
|
structure = structure_html
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
format!(
|
format!(
|
||||||
@@ -4135,7 +4232,7 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM
|
|||||||
<div class="structure" id="structure">{structure}</div>
|
<div class="structure" id="structure">{structure}</div>
|
||||||
{outline}
|
{outline}
|
||||||
</div>"#,
|
</div>"#,
|
||||||
structure = vm.structure_html,
|
structure = structure_html,
|
||||||
outline = outline_block,
|
outline = outline_block,
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,338 @@
|
|||||||
|
//! Read-only presentation of link-shaped descriptions. No evaluation or fetching.
|
||||||
|
use crate::ast::{Arg, CallExpr, Expr, Literal, Module};
|
||||||
|
use crate::view::{html::escape, render::expr_display};
|
||||||
|
use pulldown_cmark::{html, Event, Options, Parser, Tag};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
pub(crate) struct Span<'a> {
|
||||||
|
pub start: usize,
|
||||||
|
pub end: usize,
|
||||||
|
pub label: &'a str,
|
||||||
|
pub payload: &'a str,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Preserve quoted source data in executable spans and inline code in narration.
|
||||||
|
pub(crate) fn spans(text: &str, code: bool) -> Vec<Span<'_>> {
|
||||||
|
let bytes = text.as_bytes();
|
||||||
|
let mut found = Vec::new();
|
||||||
|
let mut i = 0;
|
||||||
|
while i < bytes.len() {
|
||||||
|
if bytes[i] == b'\\' { i = (i + 2).min(bytes.len()); continue; }
|
||||||
|
if bytes[i] == b'\x60' || code && matches!(bytes[i], b'"' | b'\'') {
|
||||||
|
let quote = bytes[i];
|
||||||
|
let run = if quote == b'\x60' { bytes[i..].iter().take_while(|b| **b == quote).count() } else { 1 };
|
||||||
|
i += run;
|
||||||
|
while i < bytes.len() {
|
||||||
|
if bytes[i] == b'\\' { i = (i + 2).min(bytes.len()); }
|
||||||
|
else if bytes[i..].starts_with(&vec![quote; run]) { i += run; break; }
|
||||||
|
else { i += 1; }
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if bytes[i] != b'[' || bytes.get(i + 1) == Some(&b'^')
|
||||||
|
|| i > 0 && bytes[i - 1] == b'!' {
|
||||||
|
i += 1; continue;
|
||||||
|
}
|
||||||
|
let start = i;
|
||||||
|
let mut j = i + 1;
|
||||||
|
let mut depth = 1;
|
||||||
|
while j < bytes.len() {
|
||||||
|
match bytes[j] {
|
||||||
|
b'\\' => { j += 2; continue; }
|
||||||
|
b'[' => depth += 1,
|
||||||
|
b']' => { depth -= 1; if depth == 0 { break; } }
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
j += 1;
|
||||||
|
}
|
||||||
|
if depth != 0 || bytes.get(j + 1) != Some(&b'(') { i += 1; continue; }
|
||||||
|
let label_end = j;
|
||||||
|
j += 2;
|
||||||
|
let payload_start = j;
|
||||||
|
depth = 1;
|
||||||
|
while j < bytes.len() {
|
||||||
|
match bytes[j] {
|
||||||
|
b'\\' => { j += 2; continue; }
|
||||||
|
b'"' | b'\'' | b'\x60' if code || j == payload_start
|
||||||
|
|| bytes.get(j.wrapping_sub(1)).is_some_and(|b| b" (=,[{:\t".contains(b)) => {
|
||||||
|
let quote = bytes[j]; j += 1;
|
||||||
|
while j < bytes.len() {
|
||||||
|
if bytes[j] == b'\\' { j += 2; }
|
||||||
|
else if bytes[j] == quote { j += 1; break; }
|
||||||
|
else { j += 1; }
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
b'(' => depth += 1,
|
||||||
|
b')' => { depth -= 1; if depth == 0 { break; } }
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
j += 1;
|
||||||
|
}
|
||||||
|
if depth == 0 {
|
||||||
|
found.push(Span { start, end: j + 1, label: &text[start + 1..label_end], payload: text[payload_start..j].trim() });
|
||||||
|
i = j + 1;
|
||||||
|
} else { i += 1; }
|
||||||
|
}
|
||||||
|
found
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn id(line: u32, at: usize) -> String { format!("logic-{line}-{at}") }
|
||||||
|
|
||||||
|
fn markdown(text: &str) -> String {
|
||||||
|
let parser = Parser::new_ext(text, Options::ENABLE_STRIKETHROUGH).map(|event| match event {
|
||||||
|
Event::Html(value) | Event::InlineHtml(value) => Event::Text(value),
|
||||||
|
Event::Start(Tag::Image { .. }) => Event::Html("<span class=\"logic-image-label\">".into()),
|
||||||
|
Event::End(pulldown_cmark::TagEnd::Image) => Event::Html("</span>".into()),
|
||||||
|
Event::Start(Tag::Link { dest_url, .. }) => Event::Html(format!("<span title=\"{}\">", escape(&dest_url)).into()),
|
||||||
|
Event::End(pulldown_cmark::TagEnd::Link) => Event::Html("</span>".into()),
|
||||||
|
other => other,
|
||||||
|
});
|
||||||
|
let mut rendered = String::new();
|
||||||
|
html::push_html(&mut rendered, parser);
|
||||||
|
rendered
|
||||||
|
}
|
||||||
|
fn label_html(label: &str) -> String {
|
||||||
|
let label = if label.is_empty() { "未命名内容" } else { label };
|
||||||
|
let value = markdown(label);
|
||||||
|
value.strip_prefix("<p>").and_then(|v| v.strip_suffix("</p>\n")).unwrap_or(&value).to_string()
|
||||||
|
}
|
||||||
|
fn safe_href(target: &str) -> bool {
|
||||||
|
let normalized: String = target.chars().filter(|c| !c.is_ascii_whitespace() && !c.is_control()).collect();
|
||||||
|
let lower = normalized.to_ascii_lowercase();
|
||||||
|
!lower.starts_with("javascript:") && !lower.starts_with("vbscript:")
|
||||||
|
&& !lower.starts_with("data:") && !lower.starts_with("file:")
|
||||||
|
}
|
||||||
|
fn destination(payload: &str) -> Option<String> {
|
||||||
|
let candidate = format!("[target]({payload})");
|
||||||
|
let target = Parser::new(&candidate).find_map(|event| match event {
|
||||||
|
Event::Start(Tag::Link { dest_url, .. }) => Some(dest_url.into_string()),
|
||||||
|
_ => None,
|
||||||
|
}).unwrap_or_else(|| payload.trim_matches(['<', '>']).to_string());
|
||||||
|
let scheme = target.split_once(':').is_some_and(|(scheme, _)|
|
||||||
|
scheme.starts_with(|c: char| c.is_ascii_alphabetic())
|
||||||
|
&& scheme.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')));
|
||||||
|
let relative_path = target.contains('/') && !target.contains(['(', ')'])
|
||||||
|
&& !target.chars().any(char::is_whitespace)
|
||||||
|
&& target.starts_with(|c: char| c.is_alphabetic());
|
||||||
|
let looks_like_link = scheme || relative_path || target.starts_with('#') || target.starts_with('/')
|
||||||
|
|| target.starts_with("./") || target.starts_with("../")
|
||||||
|
|| target.starts_with("mailto:") || target.starts_with("tel:")
|
||||||
|
|| target.to_ascii_lowercase().starts_with("javascript:")
|
||||||
|
|| target.to_ascii_lowercase().starts_with("data:")
|
||||||
|
|| target.to_ascii_lowercase().starts_with("vbscript:")
|
||||||
|
|| [".mq.md", ".md", ".html", ".pdf", ".txt", ".json", ".svg", ".png"]
|
||||||
|
.iter().any(|ext| target.split(['?', '#']).next().unwrap_or("").ends_with(ext));
|
||||||
|
looks_like_link.then_some(target)
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Payload { kind: &'static str, heading: &'static str, body: String, href: Option<String> }
|
||||||
|
fn payload(text: &str) -> Payload {
|
||||||
|
if text.trim().is_empty() {
|
||||||
|
return Payload { kind:"empty", heading:"待补充", body:"<p class=\"logic-empty\">待补充实际逻辑</p>".into(), href:None };
|
||||||
|
}
|
||||||
|
let expression = crate::parse::expr::parse_expr_prefer_var(text).ok();
|
||||||
|
if let Some(target) = destination(text).filter(|_| !matches!(expression, Some(Expr::List(_) | Expr::Map(_) | Expr::Literal(_)))) {
|
||||||
|
let body = if safe_href(&target) {
|
||||||
|
let external = target.starts_with("https://") || target.starts_with("http://") || target.starts_with("//");
|
||||||
|
let attributes = if external { " target=\"_blank\" rel=\"noopener noreferrer\"" } else { "" };
|
||||||
|
format!("<a class=\"logic-link-target\" href=\"{}\" data-document-href=\"{}\"{attributes}><span class=\"logic-link-address\">{}</span><span class=\"logic-link-open\">打开链接 ↗</span></a>", escape(&target), escape(&target), escape(&target))
|
||||||
|
} else {
|
||||||
|
format!("<p class=\"logic-link-address\">{}</p><p class=\"logic-hint\">此目标仅作为文字显示,不启用跳转。</p>", escape(&target))
|
||||||
|
};
|
||||||
|
return Payload { kind:"link", heading:"跳转链接", body, href:safe_href(&target).then_some(target) };
|
||||||
|
}
|
||||||
|
if text.starts_with(['[', '{']) {
|
||||||
|
if let Ok(value) = serde_json::from_str::<serde_json::Value>(text) {
|
||||||
|
return Payload { kind:"value", heading:"内容与值", body:json_html(&value, 0), href:None };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(expression) = expression {
|
||||||
|
let (kind, heading) = match expression {
|
||||||
|
Expr::Call(_) => ("call", "函数调用"),
|
||||||
|
Expr::List(_) | Expr::Map(_) | Expr::Literal(_) => ("value", "内容与值"),
|
||||||
|
Expr::Var(_) => ("reference", "引用"),
|
||||||
|
_ => ("expression", "表达式"),
|
||||||
|
};
|
||||||
|
return Payload { kind, heading, body:expression_html(&expression, 0), href:None };
|
||||||
|
}
|
||||||
|
Payload { kind:"content", heading:"内容说明", body:format!("<div class=\"logic-content\">{}</div>", markdown(text)), href:None }
|
||||||
|
}
|
||||||
|
/// JSON is document content here, never passed to the evaluator as an expression.
|
||||||
|
fn json_html(value: &serde_json::Value, depth: usize) -> String {
|
||||||
|
if depth > 5 { return format!("<code class=\"logic-expression\">{}</code>", escape(&value.to_string())); }
|
||||||
|
match value {
|
||||||
|
serde_json::Value::Array(values) => {
|
||||||
|
if values.is_empty() { return "<span class=\"logic-empty-value\">空列表</span>".into(); }
|
||||||
|
format!("<ol class=\"logic-values\">{}</ol>", values.iter()
|
||||||
|
.map(|v| format!("<li>{}</li>", json_html(v, depth + 1))).collect::<String>())
|
||||||
|
}
|
||||||
|
serde_json::Value::Object(values) => {
|
||||||
|
if values.is_empty() { return "<span class=\"logic-empty-value\">空记录</span>".into(); }
|
||||||
|
format!("<dl class=\"logic-arguments\">{}</dl>", values.iter()
|
||||||
|
.map(|(key, v)| format!("<div class=\"logic-argument\"><dt>{}</dt><dd>{}</dd></div>", escape(key), json_html(v, depth + 1))).collect::<String>())
|
||||||
|
}
|
||||||
|
serde_json::Value::String(value) => format!("<span class=\"logic-string\">{}</span>", escape(value)),
|
||||||
|
_ => format!("<code class=\"logic-expression\">{}</code>", escape(&value.to_string())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn call_name(call: &CallExpr) -> String {
|
||||||
|
if let Some(receiver) = &call.receiver { format!("{receiver}.{}", call.callee) }
|
||||||
|
else if let Some(path) = &call.path { path.join(".") }
|
||||||
|
else { call.callee.clone() }
|
||||||
|
}
|
||||||
|
fn expression_html(expression: &Expr, depth: usize) -> String {
|
||||||
|
if depth > 5 { return format!("<code class=\"logic-expression\">{}</code>", escape(&expr_display(expression))); }
|
||||||
|
match expression {
|
||||||
|
Expr::Call(call) => {
|
||||||
|
let name = call_name(call);
|
||||||
|
let mut out = format!("<div class=\"logic-call\"><code class=\"logic-call-name\" data-call-name=\"{}\">{}</code>", escape(&name), escape(&name));
|
||||||
|
if !call.pre_modifiers.is_empty() { out.push_str(&format!("<small class=\"logic-hint\">{}</small>", escape(&call.pre_modifiers.join(" ")))); }
|
||||||
|
if call.args.is_empty() { out.push_str("<p class=\"logic-no-args\">无需传入参数</p>"); }
|
||||||
|
else {
|
||||||
|
out.push_str("<dl class=\"logic-arguments\">");
|
||||||
|
for (index, argument) in call.args.iter().enumerate() {
|
||||||
|
let (name, value) = match argument {
|
||||||
|
Arg::Named { name, value } => (name.clone(), value),
|
||||||
|
Arg::Positional(value) => (format!("参数 {}", index + 1), value),
|
||||||
|
};
|
||||||
|
out.push_str(&format!("<div class=\"logic-argument\"><dt>{}</dt><dd>{}</dd></div>", escape(&name), expression_html(value, depth + 1)));
|
||||||
|
}
|
||||||
|
out.push_str("</dl>");
|
||||||
|
}
|
||||||
|
out.push_str("</div>"); out
|
||||||
|
}
|
||||||
|
Expr::Literal(Literal::Text(value)) =>
|
||||||
|
format!("<span class=\"logic-string\">{}</span>", escape(value)),
|
||||||
|
Expr::Literal(_) | Expr::Var(_) =>
|
||||||
|
format!("<code class=\"logic-expression\">{}</code>", escape(&expr_display(expression))),
|
||||||
|
Expr::List(values) => {
|
||||||
|
if values.is_empty() { return "<span class=\"logic-empty-value\">空列表</span>".into(); }
|
||||||
|
let rows = values.iter().map(|v| format!("<li>{}</li>", expression_html(v, depth + 1))).collect::<String>();
|
||||||
|
format!("<ol class=\"logic-values\">{rows}</ol>")
|
||||||
|
}
|
||||||
|
Expr::Map(values) => {
|
||||||
|
if values.is_empty() { return "<span class=\"logic-empty-value\">空记录</span>".into(); }
|
||||||
|
let rows = values.iter().map(|(key, value)| format!("<div class=\"logic-argument\"><dt>{}</dt><dd>{}</dd></div>", escape(key), expression_html(value, depth + 1))).collect::<String>();
|
||||||
|
format!("<dl class=\"logic-arguments\">{rows}</dl>")
|
||||||
|
}
|
||||||
|
Expr::Occluded { label, payload } => format!("<div class=\"logic-nested\"><span class=\"logic-nested-label\">{}</span>{}</div>", escape(label), payload.as_deref().map(|v|expression_html(v,depth+1)).unwrap_or_else(||"<span class=\"logic-empty-value\">待补充实际逻辑</span>".into())),
|
||||||
|
_ => format!("<code class=\"logic-expression\">{}</code>", escape(&expr_display(expression))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn source(line: u32, span: &Span<'_>, base: usize) -> String {
|
||||||
|
let id = id(line, base + span.start);
|
||||||
|
let item = payload(span.payload);
|
||||||
|
let attrs = format!("id=\"{id}-source\" data-logic-id=\"{id}\" data-line=\"{line}\" data-byte-start=\"{}\" data-byte-end=\"{}\" aria-describedby=\"{id}-note\"", base+span.start,base+span.end);
|
||||||
|
let label = label_html(span.label);
|
||||||
|
let mut out = if let Some(href) = item.href {
|
||||||
|
format!("<a href=\"{}\" data-document-href=\"{}\" class=\"occl-label logic-link-label mq-anchor\" {attrs}>{label}</a>", escape(&href), escape(&href))
|
||||||
|
} else {
|
||||||
|
format!("<button type=\"button\" class=\"occl-label mq-anchor\" {attrs} aria-controls=\"{id}-note\" title=\"查看{}(阅读不会执行)\">{label}</button>", item.heading)
|
||||||
|
};
|
||||||
|
if item.kind == "empty" { out.push_str("<span class=\"occl-stub\">待补充实际逻辑</span>"); }
|
||||||
|
out
|
||||||
|
}
|
||||||
|
pub(crate) fn note(line: u32, span: &Span<'_>, base: usize, executable: bool) -> String {
|
||||||
|
let id = id(line, base+span.start);
|
||||||
|
let item = payload(span.payload);
|
||||||
|
let hint = if executable { "源码说明 · 不是运行结果" } else { "文档引用 · 阅读不会执行" };
|
||||||
|
let original = if span.payload.is_empty() && executable { "待补充实际逻辑;当前空遮蔽返回 None。" } else { span.payload };
|
||||||
|
format!(r#"<details class="annot-chip annot-implementation" id="{id}-note" data-annot-id="{id}" data-annot-kind="implementation" data-logic-kind="{kind}" data-anchor-line="{line}" data-anchor-byte-start="{start}" data-anchor-byte-end="{end}"><summary class="annot-label"><span class="logic-kind">{heading}</span><span class="logic-note-label">{label}</span></summary><div class="annot-value logic-body">{body}<details class="logic-source"><summary>原始写法</summary><pre><code class="occl-code">{original}</code></pre></details></div><small class="logic-hint">{hint}</small></details>"#,
|
||||||
|
kind=item.kind, start=base+span.start, end=base+span.end, heading=item.heading,
|
||||||
|
label=label_html(span.label), body=item.body, original=escape(original))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct Narrative {
|
||||||
|
pub markdown: String,
|
||||||
|
pub replacements: Vec<(String,String)>,
|
||||||
|
pub notes: String,
|
||||||
|
}
|
||||||
|
pub(crate) fn narrative(line: u32, text: &str, base: usize) -> Narrative {
|
||||||
|
let mut result = Narrative { markdown:String::new(), replacements:Vec::new(), notes:String::new() };
|
||||||
|
let mut prefix = format!("MQVIEWLINK{line}X{base}Q");
|
||||||
|
while text.contains(&prefix) { prefix.push('Q'); }
|
||||||
|
let mut cursor = 0;
|
||||||
|
for (index, span) in spans(text, false).into_iter().enumerate() {
|
||||||
|
let token = format!("{prefix}{index}END");
|
||||||
|
result.markdown.push_str(&text[cursor..span.start]);
|
||||||
|
result.markdown.push_str(&token);
|
||||||
|
result.replacements.push((token,source(line,&span,base)));
|
||||||
|
result.notes.push_str(¬e(line,&span,base,false));
|
||||||
|
cursor=span.end;
|
||||||
|
}
|
||||||
|
result.markdown.push_str(&text[cursor..]);
|
||||||
|
result
|
||||||
|
}
|
||||||
|
pub(crate) fn replace(mut html: String, replacements: &[(String,String)]) -> String {
|
||||||
|
for (token,value) in replacements { html=html.replace(token,value); }
|
||||||
|
html
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Link only unambiguous definitions in this document.
|
||||||
|
pub(crate) fn link_definitions(mut html: String, module: &Module) -> String {
|
||||||
|
fn walk(functions: &[crate::ast::Function], prefix:&str, names:&mut HashMap<String,Vec<u32>>) {
|
||||||
|
for function in functions {
|
||||||
|
let path=if prefix.is_empty(){function.name.clone()}else{format!("{prefix}.{}",function.name)};
|
||||||
|
names.entry(path.clone()).or_default().push(function.span.line);
|
||||||
|
if !prefix.is_empty(){names.entry(function.name.clone()).or_default().push(function.span.line);}
|
||||||
|
walk(&function.children,&path,names);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut names=HashMap::new();walk(&module.functions,"",&mut names);
|
||||||
|
for (name,lines) in names {
|
||||||
|
if lines.len()!=1 {continue;}
|
||||||
|
let escaped=escape(&name);
|
||||||
|
html=html.replace(&format!("<code class=\"logic-call-name\" data-call-name=\"{escaped}\">{escaped}</code>"),
|
||||||
|
&format!("<a class=\"logic-definition\" href=\"#fn-{}\" title=\"查看本页函数定义\"><code class=\"logic-call-name\">{escaped}</code><span aria-hidden=\"true\"> ↗</span></a>",lines[0]));
|
||||||
|
}
|
||||||
|
html
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
#[test]
|
||||||
|
fn calls_and_collections_containing_urls_remain_structured_values() {
|
||||||
|
let call = payload("fetch(url=\"https://example.com/file.mq.md\", options={retry: 2})");
|
||||||
|
assert_eq!(call.kind, "call");
|
||||||
|
assert!(call.body.contains("logic-call-name") && call.body.contains("<dt>url</dt>"));
|
||||||
|
assert!(call.body.contains("<dt>options</dt>"));
|
||||||
|
assert!(!call.body.contains("logic-link-target"));
|
||||||
|
for text in ["[\"https://example.com\", 2]", "{\"url\": \"https://example.com\"}", "\"guide.mq.md\""] {
|
||||||
|
assert_eq!(payload(text).kind, "value", "{text}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn balanced_scanning_preserves_inline_code_quotes_and_byte_anchors() {
|
||||||
|
let code = "\"[data](untouched)\" [操作](f(value=\")\", nested=g(2))) [空]()";
|
||||||
|
let found = spans(code, true);
|
||||||
|
assert_eq!(found.len(), 2);
|
||||||
|
assert_eq!(found[0].payload, "f(value=\")\", nested=g(2))");
|
||||||
|
assert_eq!(&code[found[0].start..found[0].end], "[操作](f(value=\")\", nested=g(2)))");
|
||||||
|
let narrative = "don't hide [链接](https://example.com/a(b)) or `[代码](opaque)`";
|
||||||
|
let found = spans(narrative, false);
|
||||||
|
assert_eq!(found.len(), 1);
|
||||||
|
assert_eq!(found[0].label, "链接");
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn unsafe_targets_and_html_are_displayed_without_navigation_or_execution() {
|
||||||
|
for text in ["javascript:alert(1)", "data:text/html,<svg/onload=alert(1)>", "vbscript:evil"] {
|
||||||
|
let item = payload(text);
|
||||||
|
assert_eq!(item.kind, "link");
|
||||||
|
assert!(item.href.is_none());
|
||||||
|
assert!(!item.body.contains("<a "));
|
||||||
|
}
|
||||||
|
let item = payload("<script>alert(1)</script> beautiful prose");
|
||||||
|
assert!(!item.body.contains("<script>"));
|
||||||
|
assert!(item.body.contains("<script>"));
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn markdown_link_titles_and_nested_parentheses_keep_the_destination() {
|
||||||
|
for (text, target) in [("https://example.com/a(b)", "https://example.com/a(b)"),
|
||||||
|
("<guide.mq.md> \"说明\"", "guide.mq.md"), ("#fn-7", "#fn-7")] {
|
||||||
|
assert_eq!(payload(text).href.as_deref(), Some(target));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-1
@@ -6,6 +6,7 @@ mod debug_api;
|
|||||||
mod debug_page;
|
mod debug_page;
|
||||||
mod document;
|
mod document;
|
||||||
mod html;
|
mod html;
|
||||||
|
mod logic;
|
||||||
mod knowledge_present;
|
mod knowledge_present;
|
||||||
mod knowledge_reading;
|
mod knowledge_reading;
|
||||||
mod notebook_api;
|
mod notebook_api;
|
||||||
@@ -591,7 +592,7 @@ pub(crate) fn build_file_view_with_exec(
|
|||||||
Ok(FileViewModel {
|
Ok(FileViewModel {
|
||||||
rel_path: rel.to_string(),
|
rel_path: rel.to_string(),
|
||||||
source,
|
source,
|
||||||
structure_html: structure,
|
structure_html: html::document_links(&structure, &root.files, rel, &LinkMode::Live),
|
||||||
outline_html: outline,
|
outline_html: outline,
|
||||||
stdout,
|
stdout,
|
||||||
stderr,
|
stderr,
|
||||||
|
|||||||
@@ -212,3 +212,57 @@ body.reader-page .is-margin-note.annot-implementation > summary { font:15px/1.5
|
|||||||
.reader-dialog .knowledge-table-wrap table { width:100%; border-collapse:collapse; font:12px/1.7 var(--sans); }
|
.reader-dialog .knowledge-table-wrap table { width:100%; border-collapse:collapse; font:12px/1.7 var(--sans); }
|
||||||
.reader-dialog .knowledge-table-wrap th,.reader-dialog .knowledge-table-wrap td { text-align:left; padding:8px 10px; border-bottom:1px solid var(--line); vertical-align:top; overflow-wrap:anywhere; }
|
.reader-dialog .knowledge-table-wrap th,.reader-dialog .knowledge-table-wrap td { text-align:left; padding:8px 10px; border-bottom:1px solid var(--line); vertical-align:top; overflow-wrap:anywhere; }
|
||||||
.reader-run-summary { color:var(--olive); }.reader-dialog > details { margin:16px 0; }
|
.reader-run-summary { color:var(--olive); }.reader-dialog > details { margin:16px 0; }
|
||||||
|
|
||||||
|
|
||||||
|
/* Expanded details need reading room; collapsed neighbours keep their own height. */
|
||||||
|
body.reader-page .annot-chips:has(> .annot-implementation) { align-items:flex-start; }
|
||||||
|
body.reader-page .annot-implementation[open]:not(.is-margin-note) { flex-basis:100%; width:100%; }
|
||||||
|
body.reader-page .annot-implementation > summary { list-style:none; }
|
||||||
|
body.reader-page .annot-implementation > summary::-webkit-details-marker { display:none; }
|
||||||
|
body.reader-page .annot-implementation > summary::before { content:'›'; float:right; margin-left:12px; color:var(--gold); }
|
||||||
|
body.reader-page .annot-implementation[open] > summary::before { content:'⌄'; }
|
||||||
|
.logic-body pre { white-space:pre-wrap; overflow-wrap:anywhere; font:12px/1.7 var(--mono); margin:8px 0; }
|
||||||
|
@media(max-width:600px) {
|
||||||
|
body.reader-page .annot-chips:has(> .annot-implementation) { flex-direction:column; align-items:stretch; }
|
||||||
|
body.reader-page .annot-chips > .annot-implementation { width:100%; max-width:none; flex:none; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Describe the intent in the sentence; read typed details beside it. */
|
||||||
|
body.reader-page a.occl-label { color:var(--olive); border-bottom:1px dotted var(--gold); text-decoration:none; padding:0 1px; }
|
||||||
|
body.reader-page a.occl-label:hover { background:var(--fill); }
|
||||||
|
.occl-label:focus-visible,.logic-definition:focus-visible,.logic-link-target:focus-visible { outline:2px solid var(--gold); outline-offset:4px; }
|
||||||
|
.logic-kind { display:block; font:10px/1.5 var(--sans); letter-spacing:.06em; color:var(--muted); }
|
||||||
|
.logic-note-label { font:15px/1.6 var(--serif); }
|
||||||
|
.logic-body { min-width:0; text-align:left; font:12px/1.7 var(--sans); color:var(--ink); overflow-wrap:anywhere; }
|
||||||
|
body.reader-page .annot-implementation .logic-body { display:block; white-space:normal; padding:8px 0 0; max-height:none; }
|
||||||
|
body.reader-page .annot-implementation.is-margin-note .logic-body { max-height:320px; overflow:auto; scrollbar-width:thin; }
|
||||||
|
.logic-call { border-left:2px solid var(--gold); padding:2px 0 2px 10px; }
|
||||||
|
.logic-call-name { color:var(--olive); font:600 12px/1.6 var(--mono); white-space:normal; overflow-wrap:anywhere; }
|
||||||
|
.logic-definition { color:var(--olive); text-decoration:none; border-bottom:1px dotted var(--gold); }
|
||||||
|
.logic-arguments { margin:8px 0 0; padding:0; }
|
||||||
|
.logic-argument { display:grid; grid-template-columns:minmax(45px,.7fr) minmax(0,1.3fr); gap:4px 8px; padding:5px 0; border-top:1px solid var(--line); }
|
||||||
|
.logic-argument dt { color:var(--muted); overflow-wrap:anywhere; font:11px/1.65 var(--mono); }
|
||||||
|
.logic-argument dd { margin:0; min-width:0; }
|
||||||
|
.logic-argument .logic-argument { display:block; }
|
||||||
|
.logic-string { white-space:pre-wrap; }
|
||||||
|
.logic-expression { white-space:pre-wrap; font:12px/1.7 var(--mono); color:var(--ink); }
|
||||||
|
.logic-values { padding-left:19px; margin:4px 0; }
|
||||||
|
.logic-values > li { margin:3px 0; padding-left:2px; }
|
||||||
|
.logic-no-args,.logic-empty-value { font-size:11px; color:var(--muted); }
|
||||||
|
.logic-body p { margin:5px 0; }
|
||||||
|
.logic-body .logic-link-target { display:block; border:1px solid var(--line); border-radius:7px; padding:9px 10px; color:var(--olive); text-decoration:none; background:var(--fill); }
|
||||||
|
.logic-link-address { display:block; font:11px/1.7 var(--mono); overflow-wrap:anywhere; }
|
||||||
|
.logic-link-open { display:block; margin-top:5px; font:11px/1.6 var(--sans); }
|
||||||
|
.logic-body .logic-source { margin-top:10px; border-top:1px solid var(--line); padding-top:6px; color:var(--muted); }
|
||||||
|
.logic-source > summary { cursor:pointer; font:10px/1.7 var(--sans); }
|
||||||
|
.logic-source pre { margin:5px 0 0; white-space:pre-wrap; overflow-wrap:anywhere; }
|
||||||
|
.logic-nested-label { color:var(--olive); }
|
||||||
|
.logic-content > :first-child { margin-top:0; }
|
||||||
|
.reader-dialog .logic-body { font-size:14px; }
|
||||||
|
.reader-dialog .logic-call-name { font-size:15px; }
|
||||||
|
.reader-dialog .logic-argument { grid-template-columns:minmax(70px,.6fr) minmax(0,1.4fr); padding:9px 0; }
|
||||||
|
.reader-dialog .logic-body .occl-code { white-space:pre-wrap; overflow-wrap:anywhere; font:12px/1.7 var(--mono); }
|
||||||
|
@media(max-width:600px) {
|
||||||
|
.logic-note-label { font-size:14px; }
|
||||||
|
.reader-dialog .logic-argument { grid-template-columns:minmax(55px,.6fr) minmax(0,1.4fr); }
|
||||||
|
}
|
||||||
+68
-7
@@ -2,6 +2,28 @@
|
|||||||
(function () {
|
(function () {
|
||||||
'use strict';
|
'use strict';
|
||||||
var dialog, content, returnNodes = [], pending = false, toastTimer;
|
var dialog, content, returnNodes = [], pending = false, toastTimer;
|
||||||
|
// User choices belong to the document, not to one temporary layout or DOM.
|
||||||
|
var disclosureChoices = new Map(), layoutToggles = new WeakMap();
|
||||||
|
function disclosureKey(node) {
|
||||||
|
var note=node.closest('.annot-implementation');
|
||||||
|
if(!note || !note.dataset.annotId) return null;
|
||||||
|
return note.dataset.annotId+(node===note ? '' : ':source');
|
||||||
|
}
|
||||||
|
function setDisclosure(node, open) {
|
||||||
|
if(node.open===open) return;
|
||||||
|
layoutToggles.set(node,open);
|
||||||
|
node.open=open;
|
||||||
|
}
|
||||||
|
function implementationOpen(note, margin) {
|
||||||
|
var key=disclosureKey(note);
|
||||||
|
return disclosureChoices.has(key) ? disclosureChoices.get(key) : margin;
|
||||||
|
}
|
||||||
|
function restoreDisclosures(root) {
|
||||||
|
root.querySelectorAll('.annot-implementation, .annot-implementation .logic-source').forEach(function(node){
|
||||||
|
var key=disclosureKey(node);
|
||||||
|
if(disclosureChoices.has(key)) setDisclosure(node,disclosureChoices.get(key));
|
||||||
|
});
|
||||||
|
}
|
||||||
function toast(message) {
|
function toast(message) {
|
||||||
var el = document.querySelector('.reader-toast');
|
var el = document.querySelector('.reader-toast');
|
||||||
el.textContent = message; el.hidden = false;
|
el.textContent = message; el.hidden = false;
|
||||||
@@ -142,7 +164,7 @@
|
|||||||
var anchors = Array.from(owner.querySelectorAll('.mq-anchor')).filter(function (el) {
|
var anchors = Array.from(owner.querySelectorAll('.mq-anchor')).filter(function (el) {
|
||||||
return el.closest('.doc-block, .doc-list-item') === owner;
|
return el.closest('.doc-block, .doc-list-item') === owner;
|
||||||
});
|
});
|
||||||
var exact = anchors.find(function (el) { return id && el.dataset.annotId === id; });
|
var exact = anchors.find(function (el) { return id && (el.dataset.logicId === id || el.dataset.annotId === id); });
|
||||||
if (exact) return exact;
|
if (exact) return exact;
|
||||||
var onLine = anchors.filter(function (el) { return line && el.dataset.line === line; });
|
var onLine = anchors.filter(function (el) { return line && el.dataset.line === line; });
|
||||||
if (chip.hasAttribute('data-anchor-byte-start')) {
|
if (chip.hasAttribute('data-anchor-byte-start')) {
|
||||||
@@ -191,7 +213,7 @@
|
|||||||
band.classList.remove('is-keyed');
|
band.classList.remove('is-keyed');
|
||||||
band.querySelectorAll('.annot-chip').forEach(function (chip) {
|
band.querySelectorAll('.annot-chip').forEach(function (chip) {
|
||||||
chip.classList.remove('is-margin-note');
|
chip.classList.remove('is-margin-note');
|
||||||
if(chip.classList.contains('annot-implementation')) chip.open=false;
|
if(chip.classList.contains('annot-implementation')) setDisclosure(chip,implementationOpen(chip,false));
|
||||||
['left', 'top', 'width'].forEach(function (key) { chip.style.removeProperty(key); });
|
['left', 'top', 'width'].forEach(function (key) { chip.style.removeProperty(key); });
|
||||||
delete chip.dataset.readerAnchor; delete chip.dataset.readerSide;
|
delete chip.dataset.readerAnchor; delete chip.dataset.readerSide;
|
||||||
});
|
});
|
||||||
@@ -401,7 +423,7 @@
|
|||||||
var fragments = anchorFragments(item.anchor);
|
var fragments = anchorFragments(item.anchor);
|
||||||
var width = Math.max(140, Math.min(190, Math.min.apply(Math, space) * .58));
|
var width = Math.max(140, Math.min(190, Math.min.apply(Math, space) * .58));
|
||||||
item.chip.classList.add('is-margin-note'); item.chip.style.width = width + 'px';
|
item.chip.classList.add('is-margin-note'); item.chip.style.width = width + 'px';
|
||||||
if(item.chip.classList.contains('annot-implementation')) item.chip.open=true;
|
if(item.chip.classList.contains('annot-implementation')) setDisclosure(item.chip,implementationOpen(item.chip,true));
|
||||||
var height = item.chip.offsetHeight, stagger = [-58, 44, -34, 68][index % 4];
|
var height = item.chip.offsetHeight, stagger = [-58, 44, -34, 68][index % 4];
|
||||||
var choices = nextY.map(function (y, side) {
|
var choices = nextY.map(function (y, side) {
|
||||||
var fragment = side === 0 ? fragments[0] : fragments[fragments.length - 1];
|
var fragment = side === 0 ? fragments[0] : fragments[fragments.length - 1];
|
||||||
@@ -446,7 +468,15 @@
|
|||||||
var choices = [];
|
var choices = [];
|
||||||
if (structure && data.structure_html) {
|
if (structure && data.structure_html) {
|
||||||
structure.querySelectorAll('.call-picker,.loop-picker').forEach(function (el, i) { choices.push({index:i,value:el.value}); });
|
structure.querySelectorAll('.call-picker,.loop-picker').forEach(function (el, i) { choices.push({index:i,value:el.value}); });
|
||||||
|
var destinations = new Map();
|
||||||
|
structure.querySelectorAll('a[data-document-href]').forEach(function (link) {
|
||||||
|
destinations.set(link.dataset.documentHref, link.getAttribute('href'));
|
||||||
|
});
|
||||||
structure.innerHTML = data.structure_html;
|
structure.innerHTML = data.structure_html;
|
||||||
|
restoreDisclosures(structure);
|
||||||
|
structure.querySelectorAll('a[data-document-href]').forEach(function (link) {
|
||||||
|
if(destinations.has(link.dataset.documentHref)) link.setAttribute('href', destinations.get(link.dataset.documentHref));
|
||||||
|
});
|
||||||
if (window.marqdoInitDocument) window.marqdoInitDocument();
|
if (window.marqdoInitDocument) window.marqdoInitDocument();
|
||||||
var pickers = structure.querySelectorAll('.call-picker,.loop-picker');
|
var pickers = structure.querySelectorAll('.call-picker,.loop-picker');
|
||||||
choices.forEach(function (choice) {
|
choices.forEach(function (choice) {
|
||||||
@@ -461,14 +491,33 @@
|
|||||||
function init() {
|
function init() {
|
||||||
dialog = document.getElementById('reader-dialog'); content = document.getElementById('reader-dialog-content');
|
dialog = document.getElementById('reader-dialog'); content = document.getElementById('reader-dialog-content');
|
||||||
dialog.addEventListener('close', function () { restorePanels(); refreshAnnotations(); });
|
dialog.addEventListener('close', function () { restorePanels(); refreshAnnotations(); });
|
||||||
|
// Capture native summary activation before other handlers can stop bubbling.
|
||||||
|
// Keyboard activation also produces a click; never cancel the native toggle.
|
||||||
|
document.addEventListener('click', function(ev) {
|
||||||
|
var summary=ev.target.closest('.annot-implementation > summary, .annot-implementation .logic-source > summary');
|
||||||
|
if(!summary || summary.closest('#reader-dialog')) return;
|
||||||
|
var node=summary.parentElement, key=disclosureKey(node);
|
||||||
|
if(key) disclosureChoices.set(key,!node.open);
|
||||||
|
refreshAnnotations();
|
||||||
|
}, true);
|
||||||
document.addEventListener('click', function (ev) {
|
document.addEventListener('click', function (ev) {
|
||||||
var logic=ev.target.closest('[data-logic-id]');
|
var definition=ev.target.closest('.logic-definition');
|
||||||
|
if(definition && dialog.open) dialog.close();
|
||||||
|
var logic=ev.target.closest('button[data-logic-id]');
|
||||||
if(logic) {
|
if(logic) {
|
||||||
ev.preventDefault();
|
ev.preventDefault();
|
||||||
var note=document.getElementById(logic.dataset.logicId+'-note');
|
var note=document.getElementById(logic.dataset.logicId+'-note');
|
||||||
openDialog('实际逻辑 · '+logic.textContent,'logic');
|
var kind=note && note.querySelector('.logic-kind');
|
||||||
var hint=document.createElement('p');hint.className='knowledge-hint';hint.textContent='这里展示源码实现,阅读不会执行;运行结果另有标注。';content.appendChild(hint);
|
openDialog((kind ? kind.textContent : '内容详情')+' · '+logic.textContent,'logic');
|
||||||
var code=document.createElement('pre');code.textContent=note ? note.querySelector('.annot-value').textContent : '此片段的逻辑详情暂不可用。';content.appendChild(code);return;
|
var hint=document.createElement('p');hint.className='knowledge-hint';hint.textContent='这里展示源码与说明,阅读不会执行;运行结果另有标注。';content.appendChild(hint);
|
||||||
|
var body=note && note.querySelector('.logic-body');
|
||||||
|
if(body) {
|
||||||
|
var copy=body.cloneNode(true);copy.classList.remove('annot-value');
|
||||||
|
content.appendChild(copy);
|
||||||
|
} else {
|
||||||
|
var fallback=document.createElement('p');fallback.textContent='此片段的详情暂不可用。';content.appendChild(fallback);
|
||||||
|
}
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
var knowledge=ev.target.closest('.knowledge-explain, [data-knowledge-link]');
|
var knowledge=ev.target.closest('.knowledge-explain, [data-knowledge-link]');
|
||||||
if(knowledge) {
|
if(knowledge) {
|
||||||
@@ -483,6 +532,18 @@
|
|||||||
if (ev.target.closest('.reader-brand')) { ev.preventDefault(); window.scrollTo({top:0,behavior:'auto'}); }
|
if (ev.target.closest('.reader-brand')) { ev.preventDefault(); window.scrollTo({top:0,behavior:'auto'}); }
|
||||||
if (dialog.open && ev.target.closest('.outline-panel a')) { dialog.close(); }
|
if (dialog.open && ev.target.closest('.outline-panel a')) { dialog.close(); }
|
||||||
});
|
});
|
||||||
|
document.addEventListener('toggle', function(ev) {
|
||||||
|
var node=ev.target;
|
||||||
|
if(!node.matches('.annot-implementation, .annot-implementation .logic-source') || node.closest('#reader-dialog')) return;
|
||||||
|
var expected=layoutToggles.get(node);
|
||||||
|
layoutToggles.delete(node);
|
||||||
|
// Layout writes can coalesce into one native toggle event. They must not
|
||||||
|
// become user choices or schedule another reset/measure cycle.
|
||||||
|
if(expected===node.open) return;
|
||||||
|
var key=disclosureKey(node);
|
||||||
|
if(key) disclosureChoices.set(key,node.open);
|
||||||
|
refreshAnnotations();
|
||||||
|
}, true);
|
||||||
function focusNote(ev, focus) {
|
function focusNote(ev, focus) {
|
||||||
var trigger=ev.target.closest('.annot-chip,[data-logic-id]');
|
var trigger=ev.target.closest('.annot-chip,[data-logic-id]');
|
||||||
if(!trigger || ev.relatedTarget && trigger.contains(ev.relatedTarget)) return;
|
if(!trigger || ev.relatedTarget && trigger.contains(ev.relatedTarget)) return;
|
||||||
|
|||||||
+1
-1
@@ -1761,7 +1761,7 @@ mod tests {
|
|||||||
let module = crate::parse::parse_source(src).unwrap();
|
let module = crate::parse::parse_source(src).unwrap();
|
||||||
let html = render_module_structure(&module, src);
|
let html = render_module_structure(&module, src);
|
||||||
assert!(
|
assert!(
|
||||||
html.contains("<a href=\"https://github.com/cflmy/marqdo\">仓库</a>"),
|
html.contains("href=\"https://github.com/cflmy/marqdo\"") && html.contains(">仓库</a>"),
|
||||||
"{html}"
|
"{html}"
|
||||||
);
|
);
|
||||||
assert!(html.contains("<code>code</code>"), "{html}");
|
assert!(html.contains("<code>code</code>"), "{html}");
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
// Reproduce user activation followed by real layout/observer and live DOM updates.
|
||||||
|
const assert=require('node:assert/strict');
|
||||||
|
const {chromium}=require(process.env.MARQDO_PLAYWRIGHT_MODULE||'playwright');
|
||||||
|
let browser;
|
||||||
|
(async()=>{
|
||||||
|
browser=await chromium.launch({headless:true,args:['--no-sandbox']});
|
||||||
|
const page=await browser.newPage({viewport:{width:1100,height:1000}});
|
||||||
|
const errors=[];page.on('pageerror',e=>errors.push(e.message));
|
||||||
|
await page.route('https://**/*',r=>r.abort());
|
||||||
|
await page.goto(process.argv[2]);
|
||||||
|
await page.waitForTimeout(300);
|
||||||
|
for(const width of [1100,390,1440]){
|
||||||
|
await page.setViewportSize({width,height:1000});await page.waitForTimeout(200);
|
||||||
|
const note=page.locator('.annot-implementation:not(.is-margin-note)').first();
|
||||||
|
assert(await note.count(),'actual inline fallback at '+width);
|
||||||
|
const id=await note.getAttribute('data-annot-id');
|
||||||
|
const summary=note.locator(':scope > summary');
|
||||||
|
if(await note.evaluate(n=>n.open))await summary.click();
|
||||||
|
await summary.click();await page.waitForTimeout(300);
|
||||||
|
assert(await note.evaluate(n=>n.open),'click remains open after observer layout at '+width);
|
||||||
|
await page.evaluate(()=>{for(let i=0;i<5;i++)window.MarqdoReader.refreshAnnotations();});
|
||||||
|
await page.setViewportSize({width:width+15,height:980});await page.waitForTimeout(200);
|
||||||
|
assert(await note.evaluate(n=>n.open),'open choice survives resize at '+width);
|
||||||
|
const raw=note.locator('.logic-source');
|
||||||
|
if(await raw.count()){
|
||||||
|
if(!await raw.evaluate(n=>n.open))await raw.locator(':scope > summary').click();
|
||||||
|
await page.waitForTimeout(200);
|
||||||
|
assert(await note.evaluate(n=>n.open)&&await raw.evaluate(n=>n.open),'nested source stays readable');
|
||||||
|
}
|
||||||
|
await page.evaluate(()=>{
|
||||||
|
const structure=document.getElementById('structure');
|
||||||
|
const template=structure.cloneNode(true);
|
||||||
|
template.querySelectorAll('.annot-implementation,.logic-source').forEach(n=>n.open=false);
|
||||||
|
window.MarqdoReader.applyExecution({ok:true,page_token:window.MARQDO_VIEW_PAGE_TOKEN,structure_html:template.innerHTML});
|
||||||
|
});
|
||||||
|
await page.waitForTimeout(250);
|
||||||
|
const refreshed=page.locator('[data-annot-id="'+id+'"].annot-implementation');
|
||||||
|
assert(await refreshed.evaluate(n=>n.open),'live replacement preserves open choice');
|
||||||
|
if(await raw.count())assert(await refreshed.locator('.logic-source').evaluate(n=>n.open),'live replacement preserves raw source');
|
||||||
|
await refreshed.locator(':scope > summary').focus();await page.keyboard.press('Enter');
|
||||||
|
await page.waitForTimeout(250);assert.equal(await refreshed.evaluate(n=>n.open),false,'keyboard close persists');
|
||||||
|
await refreshed.locator(':scope > summary').focus();await page.keyboard.press('Space');
|
||||||
|
await page.waitForTimeout(250);assert(await refreshed.evaluate(n=>n.open),'keyboard open persists');
|
||||||
|
await refreshed.locator(':scope > summary').click();await page.waitForTimeout(150);
|
||||||
|
await page.evaluate(()=>window.MarqdoReader.refreshAnnotations());await page.waitForTimeout(150);
|
||||||
|
assert.equal(await refreshed.evaluate(n=>n.open),false,'explicit close persists');
|
||||||
|
}
|
||||||
|
assert.deepEqual(errors,[]);await browser.close();
|
||||||
|
console.log('disclosures: click, keyboard, nested source, repeated layout, resize and live replacement passed');
|
||||||
|
})().catch(async e=>{console.error(e);if(browser)await browser.close();process.exitCode=1;});
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
// Read typed details in the actual static/live reader without executing payloads.
|
||||||
|
const assert=require('node:assert/strict');
|
||||||
|
const {chromium}=require(process.env.MARQDO_PLAYWRIGHT_MODULE||'playwright');
|
||||||
|
let browser;
|
||||||
|
(async()=>{
|
||||||
|
browser=await chromium.launch({headless:true,args:['--no-sandbox']});
|
||||||
|
const context=await browser.newContext({viewport:{width:1440,height:1000}});
|
||||||
|
await context.route('https://**/*',r=>r.request().isNavigationRequest() ? r.fulfill({contentType:'text/html',body:'<h1>navigation reached</h1>'}) : r.abort());
|
||||||
|
const page=await context.newPage(),errors=[];
|
||||||
|
page.on('pageerror',e=>errors.push(e.message));
|
||||||
|
await page.goto(process.argv[2]);await page.waitForTimeout(250);
|
||||||
|
const label=text=>page.locator('#structure .occl-label').getByText(text,{exact:true});
|
||||||
|
const ids=await page.locator('#structure .occl-label').evaluateAll(ns=>ns.map(n=>n.dataset.logicId));
|
||||||
|
assert(ids.length>=10);assert.equal(new Set(ids).size,ids.length);
|
||||||
|
for(const id of ids)assert.equal(await page.locator('#'+id+'-note').count(),1,'one detail per description');
|
||||||
|
const callId=await label('函数与参数').getAttribute('data-logic-id');
|
||||||
|
const callNote=page.locator('#'+callId+'-note');
|
||||||
|
assert.equal(await callNote.getAttribute('data-logic-kind'),'call');
|
||||||
|
assert.deepEqual(await callNote.locator('.logic-arguments dt').allTextContents(),['单价','数量']);
|
||||||
|
const definition=await callNote.locator('.logic-definition').getAttribute('href');
|
||||||
|
await label('函数与参数').click();
|
||||||
|
assert(await page.locator('#reader-dialog').evaluate(n=>n.open));
|
||||||
|
assert(await page.locator('#reader-dialog .logic-arguments').isVisible());
|
||||||
|
assert.equal(await page.locator('#reader-dialog .logic-call-name').first().textContent(),'计算费用');
|
||||||
|
await page.locator('#reader-dialog .logic-source > summary').click();
|
||||||
|
assert((await page.locator('#reader-dialog pre').innerText()).includes('计算费用(单价=12, 数量=2)'));
|
||||||
|
await page.locator('#reader-dialog .logic-definition').click();
|
||||||
|
assert.equal(await page.locator('#reader-dialog').evaluate(n=>n.open),false);
|
||||||
|
assert.equal(new URL(page.url()).hash,definition);
|
||||||
|
const nestedId=await label('嵌套调用').getAttribute('data-logic-id');
|
||||||
|
assert.equal(await page.locator('#'+nestedId+'-note .logic-call-name').count(),2);
|
||||||
|
const listId=await label('列表内容').getAttribute('data-logic-id');
|
||||||
|
assert.deepEqual(await page.locator('#'+listId+'-note .logic-values li').allTextContents(),['1','2','3']);
|
||||||
|
const recordId=await label('记录内容').getAttribute('data-logic-id');
|
||||||
|
assert((await page.locator('#'+recordId+'-note .logic-body').textContent()).includes('茶'));
|
||||||
|
assert.equal(await page.locator('#structure .occl-stub').count(),1);
|
||||||
|
const repository=label('访问项目仓库');
|
||||||
|
assert.equal(await repository.evaluate(n=>n.tagName),'A');
|
||||||
|
const repoNote=page.locator('#'+await repository.getAttribute('data-logic-id')+'-note');
|
||||||
|
if(!await repoNote.evaluate(n=>n.open))await repoNote.locator(':scope > summary').click();
|
||||||
|
const popupPromise=context.waitForEvent('page');await repoNote.locator('.logic-link-target').click();
|
||||||
|
const popup=await popupPromise;await popup.waitForLoadState();
|
||||||
|
assert.equal(popup.url(),'https://github.com/cflmy/marqdo');await popup.close();
|
||||||
|
await label('跳到函数定义').click();assert.equal(new URL(page.url()).hash,definition);
|
||||||
|
await label('查看阅读示例').click();await page.waitForLoadState();
|
||||||
|
assert(page.url().includes('view-reading.mq.md'));
|
||||||
|
assert(await page.locator('#structure').getByText('购买两件商品',{exact:true}).count());
|
||||||
|
await page.goto(process.argv[2]);await page.waitForTimeout(200);
|
||||||
|
for(const width of [1920,1440,1100,1000,800,390]){
|
||||||
|
await page.setViewportSize({width,height:1000});await page.waitForTimeout(150);
|
||||||
|
assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1),'overflow '+width);
|
||||||
|
assert.deepEqual(await page.locator('.is-margin-note').evaluateAll(nodes=>{
|
||||||
|
const issues=[],rects=nodes.map(n=>n.getBoundingClientRect());
|
||||||
|
nodes.forEach((n,i)=>{
|
||||||
|
const r=rects[i];if(r.left<0||r.right>innerWidth)issues.push('offscreen');
|
||||||
|
const source=document.querySelector('[data-reader-source-anchor="'+n.dataset.readerAnchor+'"]');
|
||||||
|
if(!source||source.dataset.logicId!==n.dataset.annotId)issues.push('wrong source');
|
||||||
|
for(let j=i+1;j<rects.length;j++){const b=rects[j];if(r.left<b.right&&b.left<r.right&&r.top<b.bottom&&b.top<r.bottom)issues.push('overlap');}
|
||||||
|
});
|
||||||
|
if(innerWidth>=1440&&!nodes.length)issues.push('missing wide notes');
|
||||||
|
if(innerWidth<=1000&&nodes.length)issues.push('mobile margin');
|
||||||
|
return issues;
|
||||||
|
}),[],'precise and readable notes '+width);
|
||||||
|
}
|
||||||
|
const mobileNote=page.locator('#'+callId+'-note');
|
||||||
|
await mobileNote.locator(':scope > summary').click();
|
||||||
|
assert(await mobileNote.locator('.logic-body').isVisible());
|
||||||
|
await page.setViewportSize({width:430,height:1000});await page.waitForTimeout(150);
|
||||||
|
assert(await mobileNote.evaluate(n=>n.open),'manual disclosure survives layout');
|
||||||
|
if(process.env.MARQDO_SCREENSHOT_DIR){
|
||||||
|
await page.screenshot({path:process.env.MARQDO_SCREENSHOT_DIR+'/details-mobile.png',fullPage:true});
|
||||||
|
await page.setViewportSize({width:1440,height:1000});await page.waitForTimeout(200);
|
||||||
|
await page.locator('#structure .doc-prose').first().scrollIntoViewIfNeeded();
|
||||||
|
await page.screenshot({path:process.env.MARQDO_SCREENSHOT_DIR+'/details-desktop.png'});
|
||||||
|
await label('函数与参数').click();
|
||||||
|
await page.screenshot({path:process.env.MARQDO_SCREENSHOT_DIR+'/details-call.png'});
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
}
|
||||||
|
const plainContext=await browser.newContext({javaScriptEnabled:false,viewport:{width:390,height:900}});
|
||||||
|
const plain=await plainContext.newPage();await plain.goto(process.argv[2]);
|
||||||
|
const note=plain.locator('#'+callId+'-note');await note.locator(':scope > summary').click();
|
||||||
|
assert(await note.locator('.logic-arguments').isVisible());
|
||||||
|
await note.locator('.logic-source > summary').click();assert((await note.locator('pre').innerText()).includes('计算费用'));
|
||||||
|
await plain.locator('#structure a.occl-label').getByText('查看阅读示例',{exact:true}).click();await plain.waitForLoadState();
|
||||||
|
assert(plain.url().includes('view-reading.mq.md'));await plainContext.close();
|
||||||
|
assert.deepEqual(errors,[]);await browser.close();
|
||||||
|
console.log('typed details: calls, values, real links, precise notes, responsive and no-JS passed');
|
||||||
|
})().catch(async e=>{console.error(e);if(browser)await browser.close();process.exitCode=1;});
|
||||||
@@ -64,7 +64,7 @@ let browser;
|
|||||||
// Read-only no-script fallback still exposes native details and real source text.
|
// Read-only no-script fallback still exposes native details and real source text.
|
||||||
const context=await browser.newContext({javaScriptEnabled:false,viewport:{width:390,height:900}});
|
const context=await browser.newContext({javaScriptEnabled:false,viewport:{width:390,height:900}});
|
||||||
const plain=await context.newPage();await plain.goto(process.argv[2]);
|
const plain=await context.newPage();await plain.goto(process.argv[2]);
|
||||||
const note=plain.locator('.annot-implementation').first();await note.locator('summary').click();
|
const note=plain.locator('.annot-implementation').first();await note.locator(':scope > summary').click();
|
||||||
assert(await note.locator('.annot-value').isVisible());
|
assert(await note.locator('.annot-value').isVisible());
|
||||||
assert.equal(await plain.locator('.occl-stub').count(),1);
|
assert.equal(await plain.locator('.occl-stub').count(),1);
|
||||||
await context.close();
|
await context.close();
|
||||||
|
|||||||
@@ -153,3 +153,20 @@ fn automatic_reader_marks_callable_modules_without_executing_tools_or_hiding_pro
|
|||||||
assert!(html.contains(">fail</span>"), "a real entry failure was hidden");
|
assert!(html.contains(">fail</span>"), "a real entry failure was hidden");
|
||||||
assert!(!html.contains(">module</span>"));
|
assert!(!html.contains(">module</span>"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn typed_details_keep_calls_links_and_content_readable_without_executing() {
|
||||||
|
let temp = Scratch::new();
|
||||||
|
let source = temp.0.join("details.mq.md");
|
||||||
|
fs::write(&source, include_str!("../examples/view-details.mq.md")).unwrap();
|
||||||
|
fs::write(temp.0.join("view-reading.mq.md"), "## next\n\nReturn *1*.\n").unwrap();
|
||||||
|
export(&temp.0, &temp.0.join("out"));
|
||||||
|
let html = fs::read_to_string(temp.0.join("out/pages/details.mq.md.html")).unwrap();
|
||||||
|
for fragment in ["data-logic-kind=\"call\"", "<dt>单价</dt>", "<dt>数量</dt>",
|
||||||
|
"class=\"logic-definition\"", "class=\"logic-values\"", "<dt>名称</dt>",
|
||||||
|
"data-logic-kind=\"empty\"", "待补充实际逻辑",
|
||||||
|
"href=\"view-reading.mq.md.html\"", "href=\"https://github.com/cflmy/marqdo\""] {
|
||||||
|
assert!(html.contains(fragment), "missing typed reading detail: {fragment}");
|
||||||
|
}
|
||||||
|
assert!(!html.contains("class=\"annot-chip annot-bind"), "reading acquired runtime results");
|
||||||
|
}
|
||||||
Reference in new issue
Block a user