From ec4b3c6a8b3849c785be7692587b743535061b67 Mon Sep 17 00:00:00 2001 From: Rim Zabarov Date: Tue, 17 Nov 2026 16:23:55 +0300 Subject: [PATCH] Rebase an inline example's assets to its published folder; document D22 illustrations A shared example admitted inline into the page has no of its own, so "assets/photo.svg" resolved against the page address and returned 404. Before the markup joins the page, references to the example's own assets in attribute values (plain URL, srcset, url() in a style, a path inside a JSON attribute) now point at /_docara/examples//. Text and paths to files the example does not have stay as written; the source tab still shows what the author wrote. The example component page explains this and adds the documentation illustration rule (SIMAI rule D22): flat SVG from the pinned SIMAI Framework palette, sets, shapes, names, alt text and generate.mjs sync. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 15 ++++ docs/site/content/ru/components/example.md | 35 ++++++++ .../component-catalog/source-metadata.json | 4 +- .../InlineExampleAssetRebaser.php | 86 +++++++++++++++++++ src/PortableSite/PortableMarkdownRenderer.php | 9 +- src/PortableSite/ProjectExampleRepository.php | 5 +- tests/Unit/InlineExampleAssetRebaserTest.php | 44 ++++++++++ tests/Unit/ProjectExampleRepositoryTest.php | 39 +++++++++ 8 files changed, 233 insertions(+), 4 deletions(-) create mode 100644 src/PortableSite/InlineExampleAssetRebaser.php create mode 100644 tests/Unit/InlineExampleAssetRebaserTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index f6a9c73d..7e7bfddc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,12 +8,27 @@ All notable changes to Docara are recorded here. The format follows ### Fixed +- Inline examples: a shared example admitted inline into the page now loads + its own files. Paths to the example's `assets/` in attribute values (a + plain URL, a `srcset` list, `url()` in a style, a path inside a JSON + attribute) are rewritten to the example's published folder, as the frame's + `` already did; before, they resolved against the page address + and returned 404. Text and paths to files the example does not have stay as + written. - Link previews: pages state the share image's type, width, height and alt text (`og:image:type`, `og:image:width`, `og:image:height`, `og:image:alt`), so messengers and social networks draw the card at once. The docs recommend PNG or JPEG for `branding.share_image`, since some services do not show WebP, and the documentation site uses PNG. +### Documentation + +- The example component page describes how inline examples reach their + `assets/`, and the documentation illustration rule (SIMAI rule D22): flat + SVG from the pinned SIMAI Framework palette, five sets of eight and a + colour study, six shapes, names, alt text, and the `generate.mjs sync` + workflow. + ## [3.16.0] - 2026-11-16 ### Added diff --git a/docs/site/content/ru/components/example.md b/docs/site/content/ru/components/example.md index 6abca07f..221d1108 100644 --- a/docs/site/content/ru/components/example.md +++ b/docs/site/content/ru/components/example.md @@ -206,6 +206,41 @@ Docara показывает только существующие вкладки точечная сборка остановится, чтобы не оставить другие страницы со старой версией. +Файлы из `assets/` указывайте относительным путём: `assets/photo.svg`. В +рамке такой путь ведёт в опубликованную папку примера. Во встроенном +примере Docara сама переписывает пути к его файлам в атрибутах — в том числе +внутри JSON-значения Smart-атрибута — на адрес этой папки, поэтому +`preview=sandbox` ради картинок не нужен. Текст и пути к файлам, которых нет +в `assets/` примера, остаются как написаны. + +### Картинки в примерах + +Картинки в примерах и на страницах документации SIMAI — плоские SVG, +нарисованные одним скриптом из статической палитры закреплённой пары +SIMAI Framework (`--sf-<оттенок>-<тон>` из `distr/core/css/core.css`). +Фотографии, стоки, внешние сервисы картинок и подобранные вручную цвета не +используются. Один файл подходит и для светлой, и для тёмной темы. + +- **Наборы.** Пять наборов по восемь картинок: места, товары, люди без черт + лица, документы и экраны, обложки. Отдельно — один цветовой этюд для + примеров с фильтрами, размытием и стеклом. +- **Формы.** 1:1, 4:3, 3:4, 3:2, 2:3 и 16:9; главное — в средней трети + кадра; длинная сторона — 1200 px. +- **Имена.** `<набор>--<форма>.svg`, например `place-03-16x9.svg`. + Вариант с номером и формой в углу (`place-03-16x9-label.svg`) — только + там, где пример показывает порядок, форму или обрезку: галерея, слайдер, + поле изображения. +- **Подписи.** `alt` — короткое предложение из манифеста на языке страницы. + У декоративных обложек `alt` пустой, у аватара — имя человека. + +Скрипт, картинки и `manifest.json` лежат в `assets/illustrations/` сайта. +Docara публикует только папку самого примера, поэтому +`node assets/illustrations/generate.mjs sync` копирует нужные картинки в +`assets/` каждого примера, а `sync --check` входит в проверки сайта: +он падает, если копия отличается, больше не используется или в примере +есть растровая картинка. После каждого обновления закреплённой пары +Framework картинки перерисовываются: `generate.mjs` без аргументов. + ### Пример целой страницы Шапку, меню, области макета и настройки раздела видно только на целой diff --git a/resources/component-catalog/source-metadata.json b/resources/component-catalog/source-metadata.json index aa98209c..1d47f96c 100644 --- a/resources/component-catalog/source-metadata.json +++ b/resources/component-catalog/source-metadata.json @@ -126,7 +126,7 @@ }, { "source_ref": "docs/site/content/ru/components/example.md", - "source_sha256": "bc337e961733bc284db80ee7476698b3a38120c2dc408bfbd38d82268cfbe1ed", + "source_sha256": "89602c89598a4c323be8a1d66296d7b655afbe2ad8ee6fb66204bab4e5ed2599", "release": "3.16.0", "source_url": "https://github.com/simai/docara/blob/v3.16.0/docs/site/content/ru/components/example.md", "history_url": "https://github.com/simai/docara/commits/v3.16.0/docs/site/content/ru/components/example.md", @@ -573,5 +573,5 @@ "history_exact": false } ], - "content_sha256": "532ab62b4b8e19b2fc9e12fd79f87ed5ca722572dbc481fee655f3ddb9946ad9" + "content_sha256": "0a21bb574c60d6f3c5b279c424b09ec98a677570e87bfc28add497ab7c2a480f" } diff --git a/src/PortableSite/InlineExampleAssetRebaser.php b/src/PortableSite/InlineExampleAssetRebaser.php new file mode 100644 index 00000000..3247b384 --- /dev/null +++ b/src/PortableSite/InlineExampleAssetRebaser.php @@ -0,0 +1,86 @@ + pointing at its published folder, so + * "assets/photo.svg" in its markup loads the example's own file. An inline + * example is part of the page and has no base of its own: the same path + * would resolve against the page address and miss. Before the markup joins + * the page, every reference to one of the example's own assets in an + * attribute value is rewritten to the published folder. + * + * Only the example's known asset paths are rewritten, and only inside tag + * attribute values: a plain URL attribute (image-url="assets/a.svg"), a + * srcset list, url() in a style, or a path inside a JSON attribute + * (value='{"href":"assets/a.svg"}'). Text content, other relative URLs and + * paths that merely start with an asset's name stay as written. + */ +final class InlineExampleAssetRebaser +{ + private const TAG = '/<[A-Za-z][A-Za-z0-9-]*(?:\s+[^\s"\'>\/=]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|[^\s"\'=<>`]+))?)*\s*\/?>/'; + + private const ATTRIBUTE = '/(?\s[^\s"\'>\/=]+\s*=\s*)(?"[^"]*"|\'[^\']*\'|[^\s"\'=<>`]+)/'; + + /** + * @param list $assets Asset paths relative to the example + * folder, such as "assets/photo.svg". + * @param string $baseHref The example's published folder, ending in "/". + */ + public function rebase(string $html, array $assets, string $baseHref): string + { + $pattern = $this->assetPattern($assets); + if ($pattern === null || $baseHref === '') { + return $html; + } + $prefix = rtrim($baseHref, '/') . '/'; + + return preg_replace_callback( + self::TAG, + fn (array $tag): string => preg_replace_callback( + self::ATTRIBUTE, + fn (array $attribute): string => $attribute['name'] . (preg_replace_callback( + $pattern, + // The value is raw markup, so the prefix is HTML-escaped + // and the matched path is kept as written. + static fn (array $asset): string => htmlspecialchars($prefix, ENT_QUOTES | ENT_HTML5, 'UTF-8') . $asset['asset'], + $attribute['value'], + ) ?? $attribute['value']), + $tag[0], + ) ?? $tag[0], + $html, + ) ?? $html; + } + + /** @param list $assets */ + private function assetPattern(array $assets): ?string + { + $alternatives = []; + foreach ($assets as $asset) { + $asset = ltrim(str_replace('\\', '/', $asset), '/'); + if ($asset === '') { + continue; + } + // Markup holds the path as written or HTML-escaped, and a JSON + // attribute may escape its slashes. + foreach ([$asset, htmlspecialchars($asset, ENT_QUOTES | ENT_HTML5, 'UTF-8')] as $form) { + $alternatives[preg_quote($form, '/')] = true; + $alternatives[preg_quote(str_replace('/', '\\/', $form), '/')] = true; + } + } + if ($alternatives === []) { + return null; + } + $keys = array_keys($alternatives); + // The longest path first, so assets/a.svg never wins over assets/a.svg.gz. + usort($keys, static fn (string $left, string $right): int => strlen($right) <=> strlen($left)); + + // A reference starts the value or follows a delimiter (quote, space, + // comma, parenthesis, equals sign); "./" in front is the same path. + // It ends where the path ends: query, fragment, quote, space, comma + // or parenthesis, never inside a longer file name. + return '/(?' . implode('|', $keys) . ')(?![A-Za-z0-9_.~%\/-])/'; + } +} diff --git a/src/PortableSite/PortableMarkdownRenderer.php b/src/PortableSite/PortableMarkdownRenderer.php index 278bcf0c..0b0799f5 100644 --- a/src/PortableSite/PortableMarkdownRenderer.php +++ b/src/PortableSite/PortableMarkdownRenderer.php @@ -760,6 +760,7 @@ private function renderExample( // starts in the page's theme and its own switch changes only itself. $ownTheme = $this->exampleOwnTheme($attributes); $baseHref = null; + $exampleAssets = []; if (array_key_exists('src', $attributes)) { return $this->renderPageExample($markdown, $attributes, $label, $defaultLabel, $fullscreen, $wrap, $sourceRoot, $sourceFile, $showSources, $wide); } @@ -779,6 +780,7 @@ private function renderExample( $external = $this->projectExamples->load($exampleId, $sourceFile); $sources = $external['sources']; $baseHref = $external['base_href']; + $exampleAssets = $external['assets']; } else { $sources = $this->exampleSources($markdown); } @@ -846,9 +848,14 @@ private function renderExample( ), 1); } } else { + // The page has no to the example folder, as the frame + // has, so the example's own assets/ paths point there directly. + $inlineHtml = $baseHref === null + ? $compiledPreview + : (new InlineExampleAssetRebaser)->rebase($compiledPreview, $exampleAssets, $baseHref); $preview = '
' . $this->nestInlineHeadings($compiledPreview) . '
'; + . ' class="docara-example-inline">' . $this->nestInlineHeadings($inlineHtml) . ''; // An admitted HTML example opens in the same full-screen viewer // with device widths: the hidden frame holds the same sources and // loads only when the reader opens the viewer. diff --git a/src/PortableSite/ProjectExampleRepository.php b/src/PortableSite/ProjectExampleRepository.php index 72d5cd94..ef51a0b1 100644 --- a/src/PortableSite/ProjectExampleRepository.php +++ b/src/PortableSite/ProjectExampleRepository.php @@ -40,7 +40,7 @@ public function __construct( private readonly string $baseUrl = '/', ) {} - /** @return array{sources:array,base_href:string} */ + /** @return array{sources:array,base_href:string,assets:list} */ public function load(string $id, ?string $consumer = null): array { $id = $this->assertId($id); @@ -57,6 +57,9 @@ public function load(string $id, ?string $consumer = null): array return [ 'sources' => $record['source_contents'], 'base_href' => $this->publicBase($id), + // Paths relative to the example folder ("assets/photo.svg"); an + // inline preview rebases them to base_href. + 'assets' => array_values(array_map(static fn (array $asset): string => $asset['path'], $record['assets'])), ]; } diff --git a/tests/Unit/InlineExampleAssetRebaserTest.php b/tests/Unit/InlineExampleAssetRebaserTest.php new file mode 100644 index 00000000..b88cd36e --- /dev/null +++ b/tests/Unit/InlineExampleAssetRebaserTest.php @@ -0,0 +1,44 @@ +rebase( + '' + . '
' + . '', + $assets, + $base, + ); + + self::assertSame( + '' + . '
' + . '', + $rebased, + ); + } + + #[Test] + public function text_unknown_files_absolute_and_parent_paths_stay_as_written(): void + { + $html = '

assets/a.svg

'; + + self::assertSame($html, (new InlineExampleAssetRebaser)->rebase($html, ['assets/a.svg'], '/_docara/examples/x/')); + self::assertSame($html, (new InlineExampleAssetRebaser)->rebase($html, [], '/_docara/examples/x/')); + } +} diff --git a/tests/Unit/ProjectExampleRepositoryTest.php b/tests/Unit/ProjectExampleRepositoryTest.php index a846b0ac..98a16eb4 100644 --- a/tests/Unit/ProjectExampleRepositoryTest.php +++ b/tests/Unit/ProjectExampleRepositoryTest.php @@ -93,6 +93,45 @@ public function an_html_only_project_example_renders_inline_inside_a_boundary_ro ], $reasons); } + #[Test] + public function an_inline_project_example_points_its_own_assets_at_the_published_folder(): void + { + $this->createSource([ + 'content/ru/page.md' => '# Page', + 'examples/components/card/index.html' => '
' + . 'assets/place-01-4x3.svg' + . '
', + 'examples/components/card/assets/place-01-4x3.svg' => '', + 'examples/components/card/assets/cover 02.svg' => '', + ]); + $repository = new ProjectExampleRepository($this->tmp, '/docs/'); + $renderer = new PortableMarkdownRenderer(projectExamples: $repository); + $html = $renderer->render( + ":::example {id=\"components/card\" label=\"Result\"}\n:::\n", + $this->tmp, + $this->tmpPath('content/ru/page.md'), + ); + + self::assertStringContainsString( + '
' + . '
' + // A path inside a JSON attribute moves too; text content stays. + . 'assets/place-01-4x3.svg' + // An unknown file and a path outside the example stay as written; + // "./assets/..." is the same file. + . '
', + $html, + ); + // The source tab shows what the author wrote, and the hidden + // full-screen frame keeps its to the same folder. + self::assertStringContainsString('<div data-picture="assets/place-01-4x3.svg"', $html); + self::assertStringContainsString('<base href="/docs/_docara/examples/components/card/">', $html); + self::assertSame(['inline', 'admitted_html'], [ + $repository->receipt()['previews'][0]['resolved_preview'], + $repository->receipt()['previews'][0]['reason'], + ]); + } + #[Test] public function it_rejects_inline_body_with_id_and_unsafe_project_files(): void {