Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
`<base href>` 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
Expand Down
35 changes: 35 additions & 0 deletions docs/site/content/ru/components/example.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
- **Имена.** `<набор>-<nn>-<форма>.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` без аргументов.

### Пример целой страницы

Шапку, меню, области макета и настройки раздела видно только на целой
Expand Down
4 changes: 2 additions & 2 deletions resources/component-catalog/source-metadata.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -573,5 +573,5 @@
"history_exact": false
}
],
"content_sha256": "532ab62b4b8e19b2fc9e12fd79f87ed5ca722572dbc481fee655f3ddb9946ad9"
"content_sha256": "0a21bb574c60d6f3c5b279c424b09ec98a677570e87bfc28add497ab7c2a480f"
}
86 changes: 86 additions & 0 deletions src/PortableSite/InlineExampleAssetRebaser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<?php

declare(strict_types=1);

namespace Simai\Docara\PortableSite;

/**
* A framed example has <base href> 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 = '/(?<name>\s[^\s"\'>\/=]+\s*=\s*)(?<value>"[^"]*"|\'[^\']*\'|[^\s"\'=<>`]+)/';

/**
* @param list<string> $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<string> $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 '/(?<![A-Za-z0-9_.~%\/\\\\-])(?:\.\/|\.\\\\\/)?(?<asset>' . implode('|', $keys) . ')(?![A-Za-z0-9_.~%\/-])/';
}
}
9 changes: 8 additions & 1 deletion src/PortableSite/PortableMarkdownRenderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand All @@ -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);
}
Expand Down Expand Up @@ -846,9 +848,14 @@ private function renderExample(
), 1);
}
} else {
// The page has no <base> 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 = '<div data-docara-example-inline-preview="html"'
. ($exampleId === '' ? '' : ' data-docara-example-source="' . $this->escapeHtml($exampleId) . '"')
. ' class="docara-example-inline">' . $this->nestInlineHeadings($compiledPreview) . '</div>';
. ' class="docara-example-inline">' . $this->nestInlineHeadings($inlineHtml) . '</div>';
// 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.
Expand Down
5 changes: 4 additions & 1 deletion src/PortableSite/ProjectExampleRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public function __construct(
private readonly string $baseUrl = '/',
) {}

/** @return array{sources:array<string,string>,base_href:string} */
/** @return array{sources:array<string,string>,base_href:string,assets:list<string>} */
public function load(string $id, ?string $consumer = null): array
{
$id = $this->assertId($id);
Expand All @@ -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'])),
];
}

Expand Down
44 changes: 44 additions & 0 deletions tests/Unit/InlineExampleAssetRebaserTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

declare(strict_types=1);

namespace Tests\Unit;

use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use Simai\Docara\PortableSite\InlineExampleAssetRebaser;

final class InlineExampleAssetRebaserTest extends TestCase
{
#[Test]
public function every_attribute_form_of_an_own_asset_moves_to_the_example_folder(): void
{
$base = '/_docara/examples/components/gallery/';
$assets = ['assets/a.svg', 'assets/a.svg.gz', 'assets/b&c.svg'];
$rebased = (new InlineExampleAssetRebaser)->rebase(
'<img src="assets/a.svg" srcset="assets/a.svg 1x, ./assets/a.svg.gz 2x" alt="">'
. '<div style="background-image: url(assets/a.svg)" data-image=assets/a.svg></div>'
. '<sf-avatar image-url=\'assets/b&amp;c.svg?v=2#x\' data-json=\'{"href":"assets\/a.svg"}\'></sf-avatar>',
$assets,
$base,
);

self::assertSame(
'<img src="/_docara/examples/components/gallery/assets/a.svg"'
. ' srcset="/_docara/examples/components/gallery/assets/a.svg 1x, /_docara/examples/components/gallery/assets/a.svg.gz 2x" alt="">'
. '<div style="background-image: url(/_docara/examples/components/gallery/assets/a.svg)" data-image=/_docara/examples/components/gallery/assets/a.svg></div>'
. '<sf-avatar image-url=\'/_docara/examples/components/gallery/assets/b&amp;c.svg?v=2#x\' data-json=\'{"href":"/_docara/examples/components/gallery/assets\/a.svg"}\'></sf-avatar>',
$rebased,
);
}

#[Test]
public function text_unknown_files_absolute_and_parent_paths_stay_as_written(): void
{
$html = '<p data-a="https://cdn.test/assets/a.svg" data-b="/assets/a.svg" data-c="../assets/a.svg"'
. ' data-d="assets/a.svgz" data-e="myassets/a.svg" data-f="assets/other.svg">assets/a.svg</p>';

self::assertSame($html, (new InlineExampleAssetRebaser)->rebase($html, ['assets/a.svg'], '/_docara/examples/x/'));
self::assertSame($html, (new InlineExampleAssetRebaser)->rebase($html, [], '/_docara/examples/x/'));
}
}
39 changes: 39 additions & 0 deletions tests/Unit/ProjectExampleRepositoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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' => '<div data-picture="assets/place-01-4x3.svg" class="grid">'
. '<span data-value=\'{"label":"cover","href":"assets/cover 02.svg"}\'>assets/place-01-4x3.svg</span>'
. '<span data-other="assets/missing.svg" data-parent="../assets/place-01-4x3.svg" data-dot="./assets/place-01-4x3.svg"></span></div>',
'examples/components/card/assets/place-01-4x3.svg' => '<svg xmlns="http://www.w3.org/2000/svg"/>',
'examples/components/card/assets/cover 02.svg' => '<svg xmlns="http://www.w3.org/2000/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(
'<div data-docara-example-inline-preview="html" data-docara-example-source="components/card" class="docara-example-inline">'
. '<div data-picture="/docs/_docara/examples/components/card/assets/place-01-4x3.svg" class="grid">'
// A path inside a JSON attribute moves too; text content stays.
. '<span data-value=\'{"label":"cover","href":"/docs/_docara/examples/components/card/assets/cover 02.svg"}\'>assets/place-01-4x3.svg</span>'
// An unknown file and a path outside the example stay as written;
// "./assets/..." is the same file.
. '<span data-other="assets/missing.svg" data-parent="../assets/place-01-4x3.svg" data-dot="/docs/_docara/examples/components/card/assets/place-01-4x3.svg"></span></div>',
$html,
);
// The source tab shows what the author wrote, and the hidden
// full-screen frame keeps its <base href> to the same folder.
self::assertStringContainsString('<code class="language-html">&lt;div data-picture=&quot;assets/place-01-4x3.svg&quot;', $html);
self::assertStringContainsString('&lt;base href=&quot;/docs/_docara/examples/components/card/&quot;&gt;', $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
{
Expand Down
Loading