Вбудовування та перегляд

Один тег script відображає документи-інструкції на будь-якій вебсторінці — у вашій документації, вікі, довідковому центрі чи попередньому перегляді Markdown — так, як їх відображає instruction.md: правила списком, а примітки, інструменти та приклади картками. Вигляд змінюється звичайним CSS.

Додайте його на сторінку

Вставте цей рядок у свою сторінку, будь-де. Він працює на будь-якому сайті й більше нічого не потребує.

HTML
<script src="https://instruction.md/render@1.classic.js" defer></script>

Потім напишіть документ усередині елемента <instruction-md> або вкажіть йому файл:

HTML
<script src="https://instruction.md/render@1.classic.js" defer></script>

<!-- written in the page -->
<instruction-md>
---
spec: "1"
title: Support replies
---
MUST: answer in the customer's language.
NEVER: promise a refund before checking the order.
</instruction-md>

<!-- a file on your site, or a published instruction -->
<instruction-md src="/docs/support.md"></instruction-md>
<instruction-md ref="instruction://acme/support-agent@stable"></instruction-md>

Текст можна прочитати й без скрипта: доки він не завантажиться (або якщо його заблоковано), документ показується звичайним текстом. Таким елементом може стати й наявний: дайте йому data-instruction-md, і його текст буде відображено, або data-src, щоб завантажити файл.

Версії

render@1.js і render@1.classic.js — це завжди найновіша версія 1.x: виправлення й нові елементи з’являються без жодних змін з вашого боку, і ніщо з того, що працює, не перестає працювати. Оскільки файл змінюється, завантажуйте його без атрибута integrity, як показано вище.

Щоб натомість закріпити одну точну версію, використовуйте її власну адресу, render@1.1.0.classic.js (або render@1.1.0.js), з її integrity. Файл версії ніколи не змінюється після випуску, і він завантажує власну копію Mermaid для діаграм, тож закріплена сторінка відображається однаково, доки ця версія доступна.

HTML
<script src="https://instruction.md/render@1.1.0.classic.js"
  integrity="sha384-9GGdpGQOoKznsAXHv4dOgHHulOE4pObSP5lP311Dxddc8mVc73++6McGEfOxWJXu"
  crossorigin="anonymous" defer></script>

Кожну версію, її файли та їхні значення integrity перелічено в render@1.versions.json. Браузер перевіряє integrity скрипта з іншого сайту лише тоді, коли той сайт це дозволяє (CORS); доки instruction.md не надсилає цих заголовків для цих файлів, віддавайте закріплений файл із власного сайту з тим самим атрибутом (див. Безпека).

Блоки коду у вашому Markdown

Більшість інструментів Markdown перетворює блок коду на <pre><code class="language-…">. Напишіть документ-інструкцію в блоці з позначкою instruction:

Markdown
```instruction
---
spec: "1"
title: Support replies
---
MUST: answer in the customer's language.
```

і додайте data-fences до тегу script. Кожен такий блок на сторінці буде відображено як документ.

HTML
<script src="https://instruction.md/render@1.classic.js" data-fences defer></script>

Скрипт знаходить language-instruction, language-instruction-md, lang-instruction і <pre lang="instruction">, з підсвічуванням чи без.

Живий попередній перегляд

Попередній перегляд у редакторі перемальовує свій HTML, поки ви друкуєте. З data-watch рендерер відображає кожен блок, що з’являється, щоразу. Він дивиться лише на те, що змінилося, а блок, текст якого він уже відображав, повертає таким, як був, а не малює заново, тож друкувати й далі швидко.

HTML
<script src="https://instruction.md/render@1.classic.js" data-watch data-theme="auto" defer></script>

З вашого власного коду те саме роблять instructionMd.enhance(root, options) і instructionMd.watch(root, options):

JavaScript
// draw the fences under one element, now
instructionMd.enhance(document.querySelector("#preview"), { attributes: { theme: "dark" } });

// and again whenever the preview's HTML changes; stop() ends it
const stop = instructionMd.watch(document.querySelector("#preview"));

markdown-it та інші рендерери

Якщо ви формуєте HTML самі, плагін для markdown-it (його використовують попередній перегляд у VS Code і багато генераторів сайтів) записує блоки інструкцій як елементи. Він не має залежностей і входить у пакет instruction.md.

JavaScript
import markdownIt from "markdown-it";
import instructionMd from "instruction.md/render/markdown-it";

const md = markdownIt().use(instructionMd, { attributes: { theme: "auto" } });
const html = md.render(readme);
// ```instruction fences are now <instruction-md> elements:
// load render@1.classic.js on the page that shows the HTML to draw them

Для статичного сайту відображайте кожен документ під час збирання, і сторінці взагалі не знадобиться скрипт:

JavaScript
import { renderToString } from "instruction.md/render/ssr";

// drawn at build time, no script on the page (declarative shadow DOM)
markdownIt().use(instructionMd, { render: (text) => renderToString(text).html });

Для HTML, який створив інший рендерер, enhanceHtml робить те саме з рядком:

JavaScript
import { enhanceHtml } from "instruction.md/render/markdown-it";

// any Markdown renderer's output: its instruction fences become <instruction-md>
const page = enhanceHtml(htmlFromYourRenderer);

Атрибути

На кожному елементі <instruction-md> (описи в довідкових таблицях цієї сторінки наведено англійською: вони формуються з власного переліку рендерера):

АтрибутЗначенняЩо він робить
srcURLLoad the document from an address (same origin, instruction.md, the registry, or allow-origins).
refinstruction://owner/name@tagLoad a published instruction from the registry.
registryURLThe registry ref reads from. Default https://instruction.md/mcp.
viewrendered | delivered | sourceThe view it opens in. Default rendered.
viewscomma listThe views the switch offers; with one, no switch is shown.
themelight | dark | autoThe colour scheme of the built-in defaults. Default auto (follows the reader's system).
chromefull | barebare drops the header, the switch and the contents, for a host with its own.
tocside | agenda | noneThe contents: a rail beside the text when there is room, above it, or none.
back-matteron | offRules at a glance, guardrails and figures at the end. Default: with the full chrome.
allow-imagesbooleanShow images. Off by default: an image is a request to its server.
allow-originscomma list or *More hosts src may load from.
max-bytesnumberThe largest document src or ref loads. Default 1 MiB.
heading-offsetnumberShift the document's headings down, when your page owns the h1.
paramsJSONValues for the document's parameters, in the delivered view.
inputsbooleanThe document's parameters as inputs above it, to try values.
baseURLThe address relative links and images resolve against.
langlanguage tagThe language of the renderer's own words (Contents, Parameters, a rule's label): fr, uk… Default: the page's own lang, else English. The document's text is never translated.

На тезі script:

АтрибутЩо він робить
data-fencesВідображає також блоки коду з інструкціями на сторінці.
data-watchВідображає їх знову щоразу, коли сторінка додає HTML (живий попередній перегляд). Передбачає data-fences.
data-theme, data-view, data-views, data-chrome, data-toc, data-back-matter, data-allow-imagesТой самий атрибут на кожному елементі, на який перетворюється блок коду.

Спробуйте

Змініть документ і вигляд. CSS під ним — це те, що треба додати на вашу сторінку, щоб отримати такий самий результат.

--- spec: "1" title: Support replies --- MUST: answer in the customer's language. SHOULD: keep a reply under 120 words. NEVER: promise a refund before checking the order. MAY: suggest the help centre when it answers the question. > [!TIP] > Edit this text, or change the colours below.
css
/* the renderer's own look: nothing to set */

Оформлення

Кожен колір, шрифт і розмір — це параметр CSS (власна властивість, custom property), назва якого починається з --imd-. Задайте його на елементі або на будь-чому довкола нього, як задаєте будь-який CSS. Усе, чого ви не задали, зберігає власний вигляд рендерера, світлий або темний.

CSS
/* on the element, or on any element around it */
.docs instruction-md {
  --imd-font: "Inter", system-ui, sans-serif;
  --imd-fg: #1c1917;
  --imd-tone-must: #7c3aed;
  --imd-radius: 12px;
}
instruction-md::part(header) { display: none; }

Кольори відповідають системі читача (світлій або темній), якщо елемент не має theme="light" чи theme="dark". Колір, який ви задали, діє в обох схемах; щоб задати його лише для темної, помістіть його в медіазапит prefers-color-scheme: dark або на instruction-md[theme="dark"].

Шрифти

ПараметрТипове значенняЩо він змінює
--imd-fontui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serifThe document's text: paragraphs, lists, cards and the chrome.
--imd-font-headingvar(--imd-font)Headings and the document's title. Defaults to --imd-font.
--imd-font-monoui-monospace, SFMono-Regular, Menlo, Consolas, monospaceCode, parameters, keyboard keys and other monospaced text.
--imd-font-size15pxThe base text size; headings and small print scale from it in em/rem steps.
--imd-line-height1.5The base line height (prose reads at 1.75 on its own).

Кольори

ПараметрТипове значенняЩо він змінює
--imd-fg#09090b · dark #fafafaThe text colour.
--imd-bg#ffffff · dark #09090bThe element's background. Set it to transparent to sit on your page's own.
--imd-surface#f4f4f5 · dark #18181bA quiet fill: the view toggle, figures, asides, step numbers.
--imd-raised#ffffff · dark #09090bWhat sits on a card (badges, chips, cards themselves) and the ground a tone is tinted into.
--imd-muted#6b6b74 · dark #a1a1aaSecondary text: captions, labels, list markers, counts.
--imd-border#e4e4e7 · dark #27272aEvery hairline: cards, tables, the rule list, dividers.
--imd-link#09090b · dark #fafafaLinks in the text.
--imd-code-bg#f4f4f5 · dark #27272aThe background of code blocks and inline code.
--imd-object#09090b · dark #fafafaThe icon colour of declared things: tools, MCP servers, skills, agents.
--imd-chip-bg#f4f4f5 · dark #27272aThe background of a parameter chip, like ${customer}.
--imd-chip-fg#09090b · dark #fafafaThe text of a parameter chip.

Тони (кольори, якими відображається правило або примітка)

ПараметрТипове значенняЩо він змінює
--imd-tone-must#2563eb · dark #60a5faMUST and ALWAYS rules.
--imd-tone-should#2563eb · dark #60a5faSHOULD rules.
--imd-tone-may#15803d · dark #4ade80MAY rules, good examples and passing marks.
--imd-tone-never#b91c1c · dark #f87171NEVER and MUST NOT rules, bad examples, errors.
--imd-tone-guardrail#b91c1c · dark #f87171Guardrail alerts.
--imd-tone-note#2563eb · dark #60a5faNote and info alerts.
--imd-tone-tip#15803d · dark #4ade80Tip alerts.
--imd-tone-important#7c3aed · dark #a78bfaImportant alerts.
--imd-tone-warning#b45309 · dark #fbbf24Warning alerts, SHOULD NOT rules, highlights and items needing attention.
--imd-tone-caution#b45309 · dark #fbbf24Caution alerts.

Форма і простір

ПараметрТипове значенняЩо він змінює
--imd-radius8pxThe corner radius of cards, code blocks, tables and figures.
--imd-radius-sm6pxThe corner radius of small controls: badges, buttons, inputs, tiles.
--imd-space1remThe padding around the document.
--imd-max-width72chThe widest the text column grows (a contents rail is added beside it when there is room).

Частини

Щоб змінити більше, ніж кольори, оформіть частину зображення через ::part(), наприклад instruction-md::part(callout) { … }. Частини:

ЧастинаЩо це
allowAn agent's or tool's list of allowed items (the chips under Allow).
asideA :::aside block.
attrsThe key/value facts of a declaration (a tool's server, a schedule's time…).
back-matterThe end of the document: every rule at a glance, the guardrails, the figures.
badgeA badge in the header: signature, version, revoked.
blockedThe note under a tool or server blocked in the workspace.
blocked-markThe Blocked badge on a declaration.
bodyThe body of the document, a rule, an alert or a group.
calloutA rule, an alert, an example or an output shape.
captionA media block's caption.
cardA :::card block.
casesA test's or evaluation's list of cases.
codeA code block (its head, its code and its caption).
columnOne column of :::columns.
columnsA :::columns block.
componentA component the host doesn't have, drawn with its fallback.
conditionA rule's condition badge (if …).
copyThe copy source button in the source view.
definitionThe definition text of a script, data or configuration block.
definitionsA definition list.
deliveredThe delivered view: the text an agent receives.
denyAn agent's or tool's list of denied items.
detailsA :::details disclosure.
embedAn embedded resource (![[…]]).
errorThe message shown when the document could not be loaded.
extensionA block from an extension, drawn with its fallback.
fieldOne input of a form preview.
figureA figure: a drawing, a Mermaid diagram, a workflow graph, media.
footnoteOne footnote.
footnote-refA footnote's number in the text.
footnotesThe footnotes at the end.
formA form preview (nothing is submitted).
formatAn output's format badge.
glossaryA glossary.
gridA :::grid block.
groupA policy, an instruction or another group of rules.
headerThe header: title, version and signature.
html-frameThe sandboxed frame an html fence is drawn in.
image-placeholderWhere an image stands when images are not allowed.
includeAn include, as a card.
inputOne input of the parameter inputs (the inputs attribute).
inputsThe parameter inputs above the document.
integrationThe Integration or Not approved mark on a declaration.
labelThe label of a rule, alert, example or form field (MUST, Note, Do…).
mathMath, inline or displayed.
mediaAn image, video or audio block.
media-placeholderWhere media stands when it isn't loaded.
metaThe header's line of badges.
objectA declared tool, MCP server, skill, agent or person, as a card.
occurrenceA schedule's when, in words.
panelA context panel.
paramA parameter, inline or as its declaration card.
patchAn inheritance patch: replace, extend or remove.
proseA run of Markdown prose.
railsAn agent's list of rails.
reasonA rule's Because line.
refAn output's schema link.
referenceA typed reference in the text, drawn as a pill.
refusalsThe line that counts the document's errors.
rootThe element's outer box.
schemaAn output's schema line.
sectionA :::section block.
skillsAn agent's list of skills.
sourceThe source view.
stepOne step of :::steps.
stepsA :::steps block.
tabOne tab's panel.
tableA data block drawn as a table.
tabsA :::tabs block (and an html fence's Rendered and Code).
targetAn include's source address.
technicalA script, data, configuration, schedule, workflow, test or evaluation, as a card.
titleThe document's title.
tocThe contents, as an agenda above the text.
toc-sideThe On this page rail beside the text.
toggleThe rendered / delivered / source switch.
toolsAn agent's list of tools.
unapprovedThe note under a declaration outside the approved integrations.
unknownA block of a kind the specification doesn't have, kept as written.

Теми

З рендерером постачаються три готові варіанти вигляду: paper (теплий, із засічками), github-like і terminal (темний, моноширинний). Кожен — це коротка таблиця стилів із цих параметрів: виберіть його в полі «Почати з» вище, щоб побачити, і скопіюйте його CSS. В npm це instruction.md/render/themes/paper.css і подібні.

Безпека

  • Документ не може нічого запустити. Його Markdown відображається без сирого HTML, небезпечні посилання відкидаються, форми ніколи не надсилаються, а малюнки й діаграми зводяться до фігур і тексту.
  • Зображення вимкнено, доки ви не додасте allow-images: зображення — це запит до чийогось сервера.
  • Він завантажує лише те, що ви дозволили. src читає з вашого власного сайту, з instruction.md і реєстру або з хостів, які ви назвали в allow-origins, і щонайбільше 1 МіБ.
  • Він працює із суворою Content-Security-Policy. Він не компілює коду під час виконання, а його стилі — це сконструйовані таблиці стилів усередині елемента, тож script-src https://instruction.md — усе, що йому потрібно. Діаграми завантажують Mermaid з того самого місця, коли котрась із них потрапляє в поле зору.
  • Закріпіть копію, якщо хочете. Щоб віддавати точний файл самостійно, завантажте версію, render@1.1.0.classic.js (і vendor/mermaid@11.17.2/mermaid.min.js поруч із нею, для діаграм), та її геш, render@1.1.0.classic.js.sri, для атрибута integrity. Файли версії ніколи не змінюються, тож геш залишається правильним.

Сторінка, яка вже завантажує модулі з instruction.md, може натомість використати модульну збірку, що експортує ті самі функції:

HTML
<script type="module" src="https://instruction.md/render@1.js"></script>