From 7c6dc9ed9f32dbfab28007537ec36805df029c06 Mon Sep 17 00:00:00 2001 From: WilliamShakesGibson <343627761+WilliamShakesGibson@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:57:53 -0600 Subject: [PATCH] feat: place attached images inline in commit bodies Adds !(N)[alt] references so attached images appear among the words that introduce them, with a 1-based insertion button in the composer, escaped alt text, and code-aware parsing on both sides of the API. Feed previews carry short images inline, clip the first that cannot fit behind a 50% eased scrim colored from the theme background, and expand it in place from one keyboard-focusable control. Cropped images keep their alt for assistive technology but hide the visible caption until expanded. Segments are derived from the current body and loaded attachment metadata: missing metadata yields no feed preview rather than a stale cached one, folded previews measure only their prose, and scheduled drafts keep unresolved tokens as plain text. Replies and link-topic rows omit only the images their preview already shows. --- KNOWLEDGE_BASE.md | 4 +- .../Api/CommitTranslationController.php | 6 + .../Controllers/CommitPreviewController.php | 6 +- .../CommitTranslationController.php | 12 + app/Http/Resources/CommitResource.php | 5 + .../Resources/ScheduledCommitResource.php | 2 +- app/Models/Commit.php | 21 +- app/Services/CommitBodies.php | 58 +++- app/Services/CommitTranslations.php | 8 +- app/Services/FeedBodies.php | 227 +++++++++++++++ app/Services/ImageReferences.php | 223 +++++++++++++++ resources/css/app.css | 33 +++ resources/js/components/commit-body-image.tsx | 214 +++++++++++++++ resources/js/components/commit-body.tsx | 130 ++++++++- resources/js/components/commit-card.tsx | 52 +++- resources/js/components/commit-composer.tsx | 8 + .../js/components/commit-image-picker.tsx | 26 +- resources/js/components/commit-images.tsx | 223 +++++++++++---- resources/js/components/commit-thread.tsx | 30 +- .../js/components/commit-translation.tsx | 35 ++- resources/js/components/composer-preview.tsx | 15 +- .../js/components/link-topic-commits.tsx | 24 +- resources/js/components/linkified-text.tsx | 11 + resources/js/hooks/use-image-insertion.ts | 65 +++++ resources/js/lib/code.ts | 53 +++- resources/js/lib/image-references.ts | 95 +++++++ resources/js/pages/notification/index.tsx | 5 +- resources/js/types/commit.ts | 10 + resources/js/types/notification.ts | 5 +- .../Controllers/Api/CommitControllerTest.php | 2 + .../Controllers/Api/LogControllerTest.php | 1 + .../Api/NotificationControllerTest.php | 2 + .../Api/ScheduledCommitControllerTest.php | 14 + tests/Unit/BodyBlocks.test.ts | 77 ++++++ tests/Unit/CommitBodyImages.test.tsx | 204 ++++++++++++++ tests/Unit/CommitImages.test.tsx | 133 ++++++++- tests/Unit/CommitTranslationSegments.test.tsx | 54 ++++ tests/Unit/DraftImagePreview.test.tsx | 208 +++++++++++--- tests/Unit/FoldedCommitBody.test.tsx | 137 +++++++++- tests/Unit/ImageReferences.test.tsx | 101 +++++++ tests/Unit/Models/CommitTest.php | 1 + tests/Unit/NotificationInbox.test.tsx | 2 + tests/Unit/QuoteReply.test.tsx | 2 + tests/Unit/Services/CommitBodiesTest.php | 258 +++++++++++++++++- tests/Unit/Services/ImageReferencesTest.php | 131 +++++++++ tsconfig.json | 8 +- 46 files changed, 2775 insertions(+), 166 deletions(-) create mode 100644 app/Services/FeedBodies.php create mode 100644 app/Services/ImageReferences.php create mode 100644 resources/js/components/commit-body-image.tsx create mode 100644 resources/js/hooks/use-image-insertion.ts create mode 100644 resources/js/lib/image-references.ts create mode 100644 tests/Unit/BodyBlocks.test.ts create mode 100644 tests/Unit/CommitBodyImages.test.tsx create mode 100644 tests/Unit/CommitTranslationSegments.test.tsx create mode 100644 tests/Unit/ImageReferences.test.tsx create mode 100644 tests/Unit/Services/ImageReferencesTest.php diff --git a/KNOWLEDGE_BASE.md b/KNOWLEDGE_BASE.md index 4cf327f296..ad700ad1c5 100644 --- a/KNOWLEDGE_BASE.md +++ b/KNOWLEDGE_BASE.md @@ -293,7 +293,9 @@ Sources: [stash hook](resources/js/hooks/use-stash.ts), [image storage](resource Attach up to **three JPEG, PNG, or WebP images** to a commit or reply. Each image can be at most **10 MB** and **6,000 pixels in either dimension**. Add an image description of up to **1,000 characters** for accessibility. Add images with the picker, by pasting, or by dropping them on the composer. Every image is re-encoded to WebP, at most 1,600 pixels on its longest side, which strips metadata such as location. Images can be posted without accompanying text on the web and in the app. Images on a pending commit are visible only to its author and admins. Image attachments and a poll cannot be combined in the same commit. Open an attached photo to view it in the photo viewer, move through the commit's images, read its description, or download it. Terminal commits can attach images without descriptions, and signed API commits with them. -Sources: [image picker](resources/js/components/commit-image-picker.tsx), [image limits](app/Actions/CreateCommitImages.php), [image processing](app/Actions/CreateImageFiles.php), [attachment validation](app/Http/Requests/CreateCommitRequest.php), [photo controller](app/Http/Controllers/CommitPhotoController.php). +Place an attached image among the words by writing `!(N)[caption]` in the body, where **N** is its 1-based attachment position, from 1 to 3. The caption is optional: `!(2)[]` shows the second image with no visible caption, using a generic label for screen readers. In the web composer, choose **EMBED** on an attachment thumbnail to insert the reference at the caret. A thumbnail's stored description becomes the caption, escaped so brackets and line breaks survive in the token, and the reference is then ordinary text you can edit. Referenced images leave the row of thumbnails below the body; unreferenced images stay there. In a feed, a folded post keeps as many short images as fit where the body places them and shows the rest as small thumbnails at the foot; **Show more** unfolds the full post with every image in place. Only attached images can be shown this way: URLs and outside image imports are not supported, and a reference without a matching attachment stays as literal text, so you can write `!(1)[Woke up to Coffee]` before attaching anything and add the image later, including from a terminal commit. The older `![caption](N)` form stays literal text. References inside inline code or fenced code blocks stay code. + +Sources: [image picker](resources/js/components/commit-image-picker.tsx), [image reference parsing](app/Services/ImageReferences.php), [image limits](app/Actions/CreateCommitImages.php), [image processing](app/Actions/CreateImageFiles.php), [attachment validation](app/Http/Requests/CreateCommitRequest.php), [photo controller](app/Http/Controllers/CommitPhotoController.php). ### Links, link cards, and embedded players diff --git a/app/Http/Controllers/Api/CommitTranslationController.php b/app/Http/Controllers/Api/CommitTranslationController.php index 575c74b8aa..56aa971a4b 100644 --- a/app/Http/Controllers/Api/CommitTranslationController.php +++ b/app/Http/Controllers/Api/CommitTranslationController.php @@ -34,6 +34,12 @@ public function store(CreateApiCommitTranslationRequest $request, Commit $commit ->header('Cache-Control', 'no-store, private'); } + if ($commit->imagesAreVisibleTo($request->user())) { + $commit->loadMissing('images'); + } else { + $commit->unsetRelation('images'); + } + return response()->json(ShownGuildMentions::of(['translation' => $translations->display($commit, $request->string('language')->value(), includePending: true)], $request->user())) ->header('Cache-Control', 'no-store, private'); } diff --git a/app/Http/Controllers/CommitPreviewController.php b/app/Http/Controllers/CommitPreviewController.php index b1e2d3ea70..06368110c1 100644 --- a/app/Http/Controllers/CommitPreviewController.php +++ b/app/Http/Controllers/CommitPreviewController.php @@ -8,8 +8,8 @@ use App\Http\Resources\ShownGuildMentions; use App\Queries\MentionedOrganizationsQuery; use App\Queries\MentionedUsersQuery; -use App\Services\CodeSpans; use App\Services\EmojiShortcodes; +use App\Services\ImageReferences; use Illuminate\Http\JsonResponse; final readonly class CommitPreviewController @@ -21,7 +21,7 @@ public function store( CreateCommitPreviewRequest $request, EmojiShortcodes $emojiShortcodes, - CodeSpans $codeSpans, + ImageReferences $imageReferences, MentionedUsersQuery $mentionedUsers, MentionedOrganizationsQuery $mentionedOrganizations, ): JsonResponse { @@ -30,7 +30,7 @@ public function store( $expanded = $emojiShortcodes->replace($body); return response()->json([ - 'segments' => $codeSpans->highlight($expanded), + 'segments' => $imageReferences->highlight($expanded), 'mentions' => $mentions, 'organization_mentions' => $mentionedOrganizations->get($body, $mentions), 'guild_mentions' => ShownGuildMentions::get([$expanded], $request->user()), diff --git a/app/Http/Controllers/CommitTranslationController.php b/app/Http/Controllers/CommitTranslationController.php index 1a78f833c5..42e078326e 100644 --- a/app/Http/Controllers/CommitTranslationController.php +++ b/app/Http/Controllers/CommitTranslationController.php @@ -21,6 +21,12 @@ */ public function show(ShowCommitTranslationRequest $request, Commit $commit, CommitTranslations $translations): JsonResponse { + if ($commit->imagesAreVisibleTo($request->user())) { + $commit->loadMissing('images'); + } else { + $commit->unsetRelation('images'); + } + return response()->json(ShownGuildMentions::of(['translation' => $translations->display($commit, $request->string('language')->value(), includePending: true)], $request->user())) ->header('Cache-Control', 'no-store, private'); } @@ -40,6 +46,12 @@ public function store(CreateCommitTranslationRequest $request, Commit $commit, C ->header('Cache-Control', 'no-store, private'); } + if ($commit->imagesAreVisibleTo($request->user())) { + $commit->loadMissing('images'); + } else { + $commit->unsetRelation('images'); + } + return response()->json(ShownGuildMentions::of(['translation' => $translations->display($commit, $request->string('language')->value(), includePending: true)], $request->user())) ->header('Cache-Control', 'no-store, private'); } diff --git a/app/Http/Resources/CommitResource.php b/app/Http/Resources/CommitResource.php index 6e3f02ed28..c7b8ad1b08 100644 --- a/app/Http/Resources/CommitResource.php +++ b/app/Http/Resources/CommitResource.php @@ -11,6 +11,7 @@ use App\Models\Poll; use App\Models\User; use App\Services\CommitBodies; +use App\Services\FeedBodies; use App\Services\Mentions; use Illuminate\Database\Eloquent\Collection; use Illuminate\Http\Request; @@ -92,6 +93,10 @@ public function toArray(Request $request): array $shown = [ ...$commit, ...resolve(CommitBodies::class)->segments($this->body), + 'feed_segments' => resolve(FeedBodies::class)->segments( + $this->body, + $this->relationLoaded('images') ? $this->images->all() : null, + ), 'mentions' => resolve(Mentions::class)->positions($this->body, $this->organization_mentions ?? [], $this->mentions ?? []), 'status' => $this->status, 'is_pinned' => $this->author?->user?->pinned_commit_id === $this->id, diff --git a/app/Http/Resources/ScheduledCommitResource.php b/app/Http/Resources/ScheduledCommitResource.php index 74e2d5cd58..50ad2ae439 100644 --- a/app/Http/Resources/ScheduledCommitResource.php +++ b/app/Http/Resources/ScheduledCommitResource.php @@ -34,7 +34,7 @@ public function toArray(Request $request): array 'id' => $this->id, 'author' => $this->author === null ? null : ProfileResource::make($this->author)->resolve($request), ...($this->submitted_at === null && $this->body !== null - ? ['body' => $this->body, ...resolve(CommitBodies::class)->segments($this->body)] + ? ['body' => $this->body, ...resolve(CommitBodies::class)->plainSegments($this->body)] : ['body' => null, 'body_segments' => [], 'preview_segments' => null]), 'poll_options' => $this->poll['options'] ?? null, 'image_count' => count($this->images ?? []), diff --git a/app/Models/Commit.php b/app/Models/Commit.php index 93adc3ffd7..e72543b7d5 100644 --- a/app/Models/Commit.php +++ b/app/Models/Commit.php @@ -7,6 +7,7 @@ use App\Enums\CommitStatus; use App\Queries\CommitBuilder; use App\Services\CommitBodies; +use App\Services\FeedBodies; use App\Services\Mentions; use Carbon\CarbonInterface; use Database\Factories\CommitFactory; @@ -96,10 +97,13 @@ final class Commit extends Model public const int MAX_BODY_LENGTH = 4000; /** - * Lists show a longer body folded to its first characters and lines, the rest one click away. + * Lists show a longer body folded to its first characters and lines, the rest one click away. A short tail on the + * same line completes the preview instead of adding a “Show more” that is barely taller than the text it hides. */ public const int PREVIEW_LENGTH = 280; + public const int PREVIEW_TAIL_LENGTH = 40; + public const int PREVIEW_LINES = 8; /** @@ -110,7 +114,7 @@ final class Commit extends Model ]; /** - * @var array{body_segments: list>, preview_segments: list>|null}|null + * @var array{body_segments: list>, preview_segments: list>|null}|null */ private ?array $segments = null; @@ -168,7 +172,18 @@ public function toArray(): array $this->segments = resolve(CommitBodies::class)->segments($this->body); } - return [...parent::toArray(), ...$this->segments, 'is_checking' => $this->isBeingChecked()]; + // Feed segments depend on the images being loaded, not just the body, so they are never cached with it. + $feedSegments = resolve(FeedBodies::class)->segments( + $this->body, + $this->relationLoaded('images') ? $this->images->all() : null, + ); + + return [ + ...parent::toArray(), + ...$this->segments, + 'feed_segments' => $feedSegments, + 'is_checking' => $this->isBeingChecked(), + ]; } /** diff --git a/app/Services/CommitBodies.php b/app/Services/CommitBodies.php index 0b7284dccb..2f59a392a8 100644 --- a/app/Services/CommitBodies.php +++ b/app/Services/CommitBodies.php @@ -8,23 +8,40 @@ use Illuminate\Container\Attributes\Scoped; /** - * Scoped, like the CodeSpans it relies on, so that a page of commits shares one. + * Scoped, like the CodeSpans and ImageReferences it relies on, so that a page of commits shares one of each. */ #[Scoped] final readonly class CommitBodies { - public function __construct(private CodeSpans $codeSpans) + public function __construct(private CodeSpans $codeSpans, private ImageReferences $imageReferences) { // } /** - * The body split into prose, inline code and highlighted code blocks, for rendering, and so is its excerpt when it - * is too long to show whole in a list. + * The body split into prose, inline code, highlighted code blocks and references to attached images, plus the + * text-only excerpt a list folds a long body to. Image references do not count towards that excerpt: only the + * words a list actually shows are measured. * - * @return array{body_segments: list>, preview_segments: list>|null} + * @return array{body_segments: list>, preview_segments: list>|null} */ public function segments(string $body): array + { + $excerpt = $this->excerpt($this->imageReferences->withoutReferences($body)); + + return [ + 'body_segments' => $this->imageReferences->highlight($body), + 'preview_segments' => $excerpt === null ? null : $this->withoutImages($this->imageReferences->highlight($excerpt)), + ]; + } + + /** + * The split used before a draft has images to reference, as in scheduled commits: code is highlighted, but a + * written reference stays as its author typed it until the attachment exists. + * + * @return array{body_segments: list>, preview_segments: list>|null} + */ + public function plainSegments(string $body): array { $excerpt = $this->excerpt($body); @@ -67,6 +84,10 @@ public function excerpt(string $body): ?string if (! str_contains($body, '`')) { $excerpt = mb_rtrim($this->cutProse($body, $limit, true)); + if ($this->endsInShortTail($body, $excerpt)) { + return null; + } + return $excerpt.'…'; } @@ -99,6 +120,33 @@ public function excerpt(string $body): ?string return str_ends_with($excerpt, '```') ? $excerpt."\n…" : $excerpt.'…'; } + /** + * A cut at a word boundary that leaves only a short suffix of the final line does not save a line in the feed: the + * “Show more” it adds is taller than the text it hides, so the whole body reads better. Hard cuts inside a long + * word and anything past a line break still fold. + */ + private function endsInShortTail(string $body, string $excerpt): bool + { + if (! str_starts_with($body, $excerpt)) { + return false; + } + + $tail = mb_substr($body, mb_strlen($excerpt)); + + return preg_match('/^\s/u', $tail) === 1 + && ! str_contains($tail, "\n") + && mb_strlen($tail) <= Commit::PREVIEW_TAIL_LENGTH; + } + + /** + * @param list> $segments + * @return list> + */ + private function withoutImages(array $segments): array + { + return array_values(array_filter($segments, static fn (array $segment): bool => $segment['type'] !== 'image')); + } + /** * How many characters of the body fit in the excerpt, or null when the whole body does. */ diff --git a/app/Services/CommitTranslations.php b/app/Services/CommitTranslations.php index 3c8eb6686f..bce111cfa4 100644 --- a/app/Services/CommitTranslations.php +++ b/app/Services/CommitTranslations.php @@ -143,7 +143,13 @@ public function display(Commit $commit, ?string $language = null, bool $includeP default => Locale::getDisplayLanguage($source, 'en'), }, 'available' => $source !== $language && $source !== 'und', - 'translated' => $body === null ? null : resolve(CommitBodies::class)->segments($body), + 'translated' => $body === null ? null : [ + ...resolve(CommitBodies::class)->segments($body), + 'feed_segments' => resolve(FeedBodies::class)->segments( + $body, + $commit->relationLoaded('images') ? $commit->images->all() : null, + ), + ], ]; } } diff --git a/app/Services/FeedBodies.php b/app/Services/FeedBodies.php new file mode 100644 index 0000000000..8480136e54 --- /dev/null +++ b/app/Services/FeedBodies.php @@ -0,0 +1,227 @@ +|object>|null $images + * @return list>|null + */ + public function segments(string $body, ?array $images): ?array + { + if ($images === null) { + return null; + } + + $body = str_replace("\r\n", "\n", $body); + $text = $this->imageReferences->withoutReferences($body, $images); + $excerpt = $this->commitBodies->excerpt($text); + $references = $this->imageReferences->references($body, $images); + + if ($excerpt === null && count($references) <= 1) { + return null; + } + + [$content, $ellipsis] = $excerpt === null ? [$text, ''] : $this->splitEllipsis($excerpt); + $within = array_values(array_filter( + $references, + static fn (array $reference): bool => $reference['offset'] <= mb_strlen($content), + )); + $fitting = $this->fittingReferences($within, $images); + + if ($fitting['cutOffset'] !== null) { + $content = mb_substr($content, 0, $fitting['cutOffset']); + $ellipsis = $this->cutEllipsis($text, $fitting, $ellipsis); + } + + $shown = array_map(static fn (array $item): array => $item['reference'], $fitting['shown']); + $segments = $shown === [] + ? $this->imageReferences->highlight($content.$ellipsis) + : $this->imageReferences->highlight($this->withReferences($content, $shown, $ellipsis)); + + return $this->withFadedImage($segments, $fitting['shown']); + } + + /** + * Takes full images until their height budget runs out, then keeps a final image when two text lines of room remain. + * Anything past that boundary waits at the foot, so the preview never continues with text whose image was left out. + * + * @param list $references + * @param list|object> $images + * @return array{shown: list, cutOffset: int|null} + */ + private function fittingReferences(array $references, array $images): array + { + if ($images === []) { + return ['shown' => [], 'cutOffset' => null]; + } + + $shown = []; + $height = 0; + + foreach ($references as $reference) { + $image = $this->imageHeight($images[$reference['index'] - 1] ?? null); + + // Unknown dimensions cannot be fitted. Stop at the last image we could show: its crop or the missing image + // ends the excerpt, so prose that followed it waits at the foot too. + if ($image === null) { + return ['shown' => $shown, 'cutOffset' => $this->cutOffset($shown, $reference)]; + } + + if ($height + $image > self::FEED_IMAGE_BUDGET) { + $remaining = self::FEED_IMAGE_BUDGET - $height; + + if ($remaining >= self::FEED_IMAGE_FADE_HEIGHT) { + $shown[] = ['reference' => $reference, 'visibleHeight' => $remaining]; + } + + return ['shown' => $shown, 'cutOffset' => $this->cutOffset($shown, $reference)]; + } + + $shown[] = ['reference' => $reference, 'visibleHeight' => null]; + $height += $image; + } + + return ['shown' => $shown, 'cutOffset' => null]; + } + + /** + * The excerpt ends after the last image that fits, or before the first one that cannot. Text between images is part + * of the same excerpt, so a partial or missing image does not leave its trailing prose hanging below the feed. + * + * @param list $shown + * @param array{offset: int, index: int, alt: string|null, spaceBefore: bool, spaceAfter: bool} $stopping + */ + private function cutOffset(array $shown, array $stopping): int + { + $last = end($shown); + + return $last === false ? $stopping['offset'] : $last['reference']['offset']; + } + + /** + * A cropped image already shows that it continues. Otherwise an ellipsis marks prose left out at the image boundary; + * image references and their alt descriptions do not count as prose. + * + * @param array{shown: list, visibleHeight: int|null}>, cutOffset: int|null} $fitting + */ + private function cutEllipsis(string $text, array $fitting, string $ellipsis): string + { + if ($ellipsis !== '') { + return $ellipsis; + } + + $last = end($fitting['shown']); + + if ($last !== false && $last['visibleHeight'] !== null) { + return ''; + } + + return mb_trim(mb_substr($text, $fitting['cutOffset'])) === '' ? '' : '…'; + } + + /** + * Marks the final image as partly shown so the client can clip and fade its bottom. + * + * @param list> $segments + * @param list, visibleHeight: int|null}> $shown + * @return list> + */ + private function withFadedImage(array $segments, array $shown): array + { + $height = null; + + foreach ($shown as $item) { + if ($item['visibleHeight'] !== null) { + $height = $item['visibleHeight']; + } + } + + if ($height === null) { + return $segments; + } + + for ($index = count($segments) - 1; $index >= 0; $index--) { + if ($segments[$index]['type'] === 'image') { + $segments[$index]['visibleHeight'] = $height; + + break; + } + } + + return $segments; + } + + /** How tall an attachment renders at the feed body's usual width, or null when its size is unknown. */ + private function imageHeight(mixed $image): ?int + { + $width = data_get($image, 'width'); + $height = data_get($image, 'height'); + + if (! is_numeric($width) || ! is_numeric($height) || $width <= 0 || $height <= 0) { + return null; + } + + return (int) round(min((float) $height, self::FEED_IMAGE_WIDTH * (float) $height / (float) $width)); + } + + /** + * Puts image references back at the offsets they held in the text without references, along with the spaces that + * dropping them would have left doubled. Right to left, so earlier offsets stay valid. + * + * @param list $references + */ + private function withReferences(string $text, array $references, string $suffix = ''): string + { + foreach (array_reverse($references) as $reference) { + $token = $this->imageReferences->token($reference['index'], $reference['alt']); + $space = $reference['spaceBefore'] && $reference['spaceAfter'] ? ' ' : ''; + + $text = mb_substr($text, 0, $reference['offset']).$token.$space.mb_substr($text, $reference['offset']); + } + + return $text.$suffix; + } + + /** + * @return array{0: string, 1: string} + */ + private function splitEllipsis(string $excerpt): array + { + if (str_ends_with($excerpt, "\n…")) { + return [mb_substr($excerpt, 0, -2), "\n…"]; + } + + if (str_ends_with($excerpt, '…')) { + return [mb_substr($excerpt, 0, -1), '…']; + } + + return [$excerpt, '']; + } +} diff --git a/app/Services/ImageReferences.php b/app/Services/ImageReferences.php new file mode 100644 index 0000000000..e33fa01378 --- /dev/null +++ b/app/Services/ImageReferences.php @@ -0,0 +1,223 @@ + + */ + public function highlight(string $text): array + { + $segments = []; + + foreach ($this->codeSpans->highlight($text) as $segment) { + if ($segment['type'] !== 'text') { + $segments[] = $segment; + + continue; + } + + array_push($segments, ...$this->split($segment['text'])); + } + + return $segments; + } + + /** + * The body without the references that become images, so a preview measures only the words it shows. References + * inside code stay as they were written, as do numbers past the images a commit can carry. Pass $images to only + * remove references with a matching loaded attachment; unmatched tokens stay literal. + * + * @param list|null $images + */ + public function withoutReferences(string $text, ?array $images = null): string + { + if (! str_contains($text, '!(')) { + return $text; + } + + $plain = ''; + + foreach ($this->codeSpans->split($text) as $partIndex => $part) { + $plain .= $partIndex % 2 === 1 ? $part : $this->stripProse($part, $images)[0]; + } + + return $plain; + } + + /** + * Every reference that becomes an image, with the offset it sat at in {@see withoutReferences()}, so a feed can put + * as many as fit back among the words it previews. + * + * @param list|null $images + * @return list + */ + public function references(string $text, ?array $images = null): array + { + if (! str_contains($text, '!(')) { + return []; + } + + $references = []; + $offset = 0; + + foreach ($this->codeSpans->split($text) as $partIndex => $part) { + if ($partIndex % 2 === 1) { + $offset += mb_strlen($part); + + continue; + } + + [$plain, $found] = $this->stripProse($part, $images); + + foreach ($found as $reference) { + $references[] = [...$reference, 'offset' => $offset + $reference['offset']]; + } + + $offset += mb_strlen($plain); + } + + return $references; + } + + /** + * Splits a piece of prose into text and image reference segments. References beyond the number of images a commit + * can carry stay as text, so a draft written before its images are attached keeps what the author typed. + * + * @return list + */ + public function split(string $prose): array + { + if (preg_match_all(self::PATTERN, $prose, $matches, PREG_OFFSET_CAPTURE) === 0) { + return [['type' => 'text', 'text' => $prose]]; + } + + $segments = []; + $cursor = 0; + + foreach ($matches[0] as $index => [$token, $position]) { + $character = mb_strlen(mb_strcut($prose, 0, $position)); + + if ($character > $cursor) { + $segments[] = ['type' => 'text', 'text' => mb_substr($prose, $cursor, $character - $cursor)]; + } + + $number = (int) $matches[1][$index][0]; + + if ($number > CreateCommitImages::MAX_IMAGES) { + $segments[] = ['type' => 'text', 'text' => $token]; + } else { + $alt = mb_trim($this->unescapeAlt($matches[2][$index][0])); + $segments[] = ['type' => 'image', 'index' => $number, 'alt' => $alt === '' ? null : $alt]; + } + + $cursor = $character + mb_strlen($token); + } + + if ($cursor < mb_strlen($prose)) { + $segments[] = ['type' => 'text', 'text' => mb_substr($prose, $cursor)]; + } + + return $segments; + } + + /** + * Removes the references from one piece of prose, reporting where each sat in what is left. With $images, only + * references with a matching loaded attachment are removed. + * + * @param list|null $images + * @return array{0: string, 1: list} + */ + private function stripProse(string $prose, ?array $images = null): array + { + if (preg_match_all(self::PATTERN, $prose, $matches, PREG_OFFSET_CAPTURE) === 0) { + return [$prose, []]; + } + + $plain = ''; + $references = []; + $cursor = 0; + + foreach ($matches[0] as $matchIndex => [$token, $position]) { + $character = mb_strlen(mb_strcut($prose, 0, $position)); + $plain .= $this->joinProse($plain, mb_substr($prose, $cursor, $character - $cursor)); + $number = (int) $matches[1][$matchIndex][0]; + + if ($number > CreateCommitImages::MAX_IMAGES || ($images !== null && ! array_key_exists($number - 1, $images))) { + $plain .= $token; + } else { + $references[] = [ + 'offset' => mb_strlen($plain), + 'index' => $number, + 'alt' => (($alt = mb_trim($this->unescapeAlt($matches[2][$matchIndex][0]))) !== '' ? $alt : null), + 'spaceBefore' => $character > 0 && preg_match('/[ \t]$/u', mb_substr($prose, $character - 1, 1)) === 1, + 'spaceAfter' => preg_match('/^[ \t]/u', mb_substr($prose, $character + mb_strlen($token), 1)) === 1, + ]; + } + + $cursor = $character + mb_strlen($token); + } + + return [$plain.$this->joinProse($plain, mb_substr($prose, $cursor)), $references]; + } + + /** Reverses the escapes written by {@see token()}, leaving any other escape as the author typed it. */ + private function unescapeAlt(string $alt): string + { + return (string) preg_replace_callback( + '/\\\\(n|b|\]|\\\\)/u', + static fn (array $match): string => match ($match[1]) { + 'n' => "\n", + 'b' => '`', + ']' => ']', + '\\' => '\\', + default => $match[0], + }, + $alt, + ); + } + + /** A reference usually sits between two spaces, so dropping it would leave two where one read. */ + private function joinProse(string $plain, string $part): string + { + if ($plain !== '' && preg_match('/[ \t]$/u', $plain) === 1 && preg_match('/^[ \t]/u', $part) === 1) { + return mb_substr($part, 1); + } + + return $part; + } +} diff --git a/resources/css/app.css b/resources/css/app.css index c1291a8d2b..69cf468f4d 100644 --- a/resources/css/app.css +++ b/resources/css/app.css @@ -8,6 +8,39 @@ @custom-variant dark (&:is(.dark *)); @custom-variant in-place (&:is(:root[data-view-transition] *)); +/* One eased, theme-colored scrim for every cropped feed image: invisible at the midpoint, then steadily stronger into the feed surface. */ +.feed-image-scrim { + height: 50%; + background: linear-gradient( + to top, + var(--background) 0%, + color-mix(in oklab, var(--background) 99%, transparent) 1%, + color-mix(in oklab, var(--background) 98%, transparent) 2%, + color-mix(in oklab, var(--background) 96%, transparent) 4%, + color-mix(in oklab, var(--background) 93%, transparent) 6%, + color-mix(in oklab, var(--background) 89%, transparent) 9%, + color-mix(in oklab, var(--background) 84%, transparent) 12%, + color-mix(in oklab, var(--background) 78%, transparent) 16%, + color-mix(in oklab, var(--background) 71%, transparent) 20%, + color-mix(in oklab, var(--background) 63%, transparent) 25%, + color-mix(in oklab, var(--background) 54%, transparent) 30%, + color-mix(in oklab, var(--background) 45%, transparent) 35%, + color-mix(in oklab, var(--background) 36%, transparent) 40%, + color-mix(in oklab, var(--background) 28%, transparent) 45%, + color-mix(in oklab, var(--background) 21%, transparent) 50%, + color-mix(in oklab, var(--background) 15%, transparent) 55%, + color-mix(in oklab, var(--background) 10%, transparent) 60%, + color-mix(in oklab, var(--background) 7%, transparent) 65%, + color-mix(in oklab, var(--background) 4.5%, transparent) 70%, + color-mix(in oklab, var(--background) 2.8%, transparent) 75%, + color-mix(in oklab, var(--background) 1.6%, transparent) 80%, + color-mix(in oklab, var(--background) 0.8%, transparent) 85%, + color-mix(in oklab, var(--background) 0.3%, transparent) 90%, + color-mix(in oklab, var(--background) 0.08%, transparent) 95%, + transparent 100% + ); +} + /* Keep the fingerprint's wrapping, selection and accessible text while revealing its tiny secret. */ .certificate-hash { position: relative; diff --git a/resources/js/components/commit-body-image.tsx b/resources/js/components/commit-body-image.tsx new file mode 100644 index 0000000000..c4f5cc158f --- /dev/null +++ b/resources/js/components/commit-body-image.tsx @@ -0,0 +1,214 @@ +import { ChevronDown } from 'lucide-react'; +import { type MouseEvent, type ReactNode, useState } from 'react'; +import { + CommitImageThumbnail, + type ShownImage, +} from '@/components/commit-images'; +import { InlineText } from '@/components/linkified-text'; +import { emojify } from '@/lib/emoji'; +import { imageReference } from '@/lib/image-references'; +import { cn } from '@/lib/utils'; +import type { BodySegment } from '@/types'; + +/** Keep in sync with FeedBodies::FEED_IMAGE_WIDTH. */ +const feedImageWidth = 530; + +/** A caption is one text line plus its margin; a cropped feed gives that room back to the image. */ +const feedImageCaptionHeight = 24; + +/** An image reference placed among the words of a body, with its caption and any in-feed crop. */ +export function BodyImage({ + segment, + image, + onImageOpen, + pasteisMode, +}: { + segment: Extract; + image: ShownImage | undefined; + onImageOpen?: (index: number) => void; + pasteisMode: boolean; +}) { + const [isExpanded, setIsExpanded] = useState(false); + + if (!image) { + return ( + + {imageReference(segment.index, segment.alt)} + + ); + } + + const alt = segment.alt + ? emojify(segment.alt) + : image.description + ? emojify(image.description) + : `Attached image ${segment.index}`; + const isCropped = segment.visibleHeight !== undefined && !isExpanded; + + return ( +
+ setIsExpanded(true) : undefined} + /> + {segment.alt && !isCropped && ( +
+ +
+ )} +
+ ); +} + +function ImageFrame({ + segment, + image, + alt, + onImageOpen, + onExpand, +}: { + segment: Extract; + image: ShownImage; + alt: string; + onImageOpen?: (index: number) => void; + onExpand?: () => void; +}) { + const cropWidth = + image.width === undefined + ? undefined + : Math.min(image.width, feedImageWidth); + const naturalHeight = + image.width !== undefined && image.height !== undefined + ? Math.max( + 1, + Math.floor( + (image.height / image.width) * + Math.min(image.width, feedImageWidth), + ), + ) + : undefined; + const height = + segment.visibleHeight === undefined + ? undefined + : Math.min( + segment.visibleHeight + + (segment.alt ? feedImageCaptionHeight : 0), + naturalHeight ?? Number.POSITIVE_INFINITY, + ); + const aspectRatio = + cropWidth !== undefined && height !== undefined + ? `${cropWidth} / ${height}` + : undefined; + + const thumbnail = ( + + ); + + if (height === undefined) { + return ( + + + {thumbnail} + + + ); + } + + const label = `Expand image${segment.alt ? `: ${segment.alt}` : ''}`; + const expand = (event: MouseEvent) => { + event.preventDefault(); + event.stopPropagation(); + onExpand?.(); + }; + + return ( + + {thumbnail} + + {onExpand && ( + + )} + + ); +} + +function ImageLink({ + image, + index, + onImageOpen, + children, +}: { + image: ShownImage; + index: number; + onImageOpen?: (index: number) => void; + children: ReactNode; +}) { + if (!onImageOpen) { + return children; + } + + return ( + { + if ( + event.metaKey || + event.ctrlKey || + event.shiftKey || + event.altKey + ) { + return; + } + + event.preventDefault(); + onImageOpen(index - 1); + }} + className="relative inline-block max-w-full" + > + {children} + + ); +} diff --git a/resources/js/components/commit-body.tsx b/resources/js/components/commit-body.tsx index 9139ff6c30..18e3d885fe 100644 --- a/resources/js/components/commit-body.tsx +++ b/resources/js/components/commit-body.tsx @@ -2,6 +2,8 @@ import { usePage } from '@inertiajs/react'; import { useEffect, useRef, useState } from 'react'; import { CertificateText } from '@/components/certificate-text'; import { CodeBlock } from '@/components/code-block'; +import { BodyImage } from '@/components/commit-body-image'; +import type { ShownImage } from '@/components/commit-images'; import { LinkifiedText } from '@/components/linkified-text'; import { bodyBlocks } from '@/lib/code'; import { emojify } from '@/lib/emoji'; @@ -14,6 +16,8 @@ export function CommitBody({ mentions, organizationMentions = null, guildMentions, + images = [], + onImageOpen, className, isStatic = false, linksEveryMention = true, @@ -22,6 +26,8 @@ export function CommitBody({ mentions: Commit['mentions']; organizationMentions?: Commit['organization_mentions']; guildMentions?: GuildMentions; + images?: ShownImage[]; + onImageOpen?: (index: number) => void; className?: string; isStatic?: boolean; /** @@ -48,6 +54,8 @@ export function CommitBody({ mentions={mentions} organizationMentions={organizationMentions} guildMentions={guildMentions} + images={images} + onImageOpen={onImageOpen} isStatic={isStatic} linksEveryMention={linksEveryMention} /> @@ -59,6 +67,8 @@ export function CommitBody({ mentions={mentions} organizationMentions={organizationMentions} guildMentions={guildMentions} + images={images} + onImageOpen={onImageOpen} isStatic={isStatic} linksEveryMention={linksEveryMention} /> @@ -73,6 +83,8 @@ export function BodySegments({ mentions, organizationMentions = null, guildMentions, + images = [], + onImageOpen, isStatic = false, linksEveryMention = true, }: { @@ -80,6 +92,8 @@ export function BodySegments({ mentions: Commit['mentions']; organizationMentions?: Commit['organization_mentions']; guildMentions?: GuildMentions; + images?: ShownImage[]; + onImageOpen?: (index: number) => void; isStatic?: boolean; linksEveryMention?: boolean; }) { @@ -111,6 +125,16 @@ export function BodySegments({ ); + case 'image': + return ( + + ); case 'block': return ( void; className?: string; + canUnfold?: boolean; + onUnfoldChange?: (isUnfolded: boolean) => void; }) { const [isUnfolded, setIsUnfolded] = useState(false); const bodyRef = useRef(null); - if (previewSegments === null) { + if (!previewSegments || sameSegments(previewSegments, segments)) { return ( ); @@ -167,6 +202,7 @@ export function FoldedCommitBody({ const card = button.closest('[data-reply], [data-commit]'); setIsUnfolded(true); + onUnfoldChange?.(true); if (card?.matches('[data-commit]')) { card.focus({ preventScroll: true }); @@ -188,9 +224,11 @@ export function FoldedCommitBody({ mentions={mentions} organizationMentions={organizationMentions} guildMentions={guildMentions} + images={images} + onImageOpen={onImageOpen} className={className} /> - {!isUnfolded && ( + {!isUnfolded && canUnfold && ( + {onInsertInline && ( + + )} ); })} diff --git a/resources/js/components/commit-images.tsx b/resources/js/components/commit-images.tsx index 9bc295d3d5..30fa40b75a 100644 --- a/resources/js/components/commit-images.tsx +++ b/resources/js/components/commit-images.tsx @@ -1,4 +1,4 @@ -import type { MouseEvent } from 'react'; +import type { MouseEvent, ReactNode } from 'react'; import { useState } from 'react'; import { useScrambledHash } from '@/hooks/use-scrambled-hash'; import { commitPhotoUrl, openCommitPhoto } from '@/lib/commit-photo'; @@ -75,7 +75,7 @@ function CommitImageLoading({ hash }: { hash: string }) { ); } -function CommitImageThumbnail({ +export function CommitImageThumbnail({ image, alt, className, @@ -123,28 +123,166 @@ function CommitImageThumbnail({ /** * A commit's images open in its photo viewer. Other images, like a message's, open wherever `onOpen` shows them. */ -type CommitImagesProps = +type CommitImagesProps = { + /** 1-based attachment positions already shown inline in the body. */ + omit?: ReadonlySet; + /** + * In a folded feed, the first image keeps the post readable and the rest wait as small footnotes until it unfolds. + */ + compact?: boolean; + /** Whether compact mode keeps its first image large, or the feed already shows that image in place. */ + lead?: boolean; +} & ( | { commit: Commit; images?: never; onOpen?: never } | { commit?: never; images: ShownImage[]; onOpen?: (index: number) => void; - }; + } +); const isModifiedClick = (event: MouseEvent): boolean => event.metaKey || event.ctrlKey || event.shiftKey || event.altKey; +function CommitImageLink({ + commit, + onOpen, + image, + index, + className, + children, +}: { + commit?: Commit; + onOpen?: (index: number) => void; + image: ShownImage; + index: number; + className: string; + children: ReactNode; +}) { + if (commit) { + return ( + { + event.stopPropagation(); + + if (isModifiedClick(event)) { + return; + } + + event.preventDefault(); + openCommitPhoto(commit, index); + }} + className={className} + > + {children} + + ); + } + + if (onOpen) { + return ( + { + if (isModifiedClick(event)) { + return; + } + + event.preventDefault(); + onOpen(index); + }} + className={className} + > + {children} + + ); + } + + return
{children}
; +} + export function CommitImages({ commit, images: draftImages, onOpen, + omit, + compact = false, + lead = true, }: CommitImagesProps) { - const images = commit ? (commit.images ?? []) : draftImages; + const all = commit ? (commit.images ?? []) : (draftImages ?? []); + const images = all + .map((image, index) => ({ image, index })) + .filter(({ index }) => !omit?.has(index + 1)); if (images.length === 0) { return null; } + if (compact) { + const first = lead ? images[0] : undefined; + const footnotes = lead ? images.slice(1) : images; + + return ( +
+ {first && ( + + + + )} + {footnotes.length > 0 && ( +
+ {footnotes.map(({ image, index }) => ( + + + + ))} +
+ )} +
+ ); + } + const hasMultipleImages = images.length > 1; return ( @@ -160,64 +298,35 @@ export function CommitImages({ data-test="commit-images" data-image-grid={hasMultipleImages || undefined} > - {images.map((image, index) => { + {images.map(({ image, index }, position) => { const className = cn('relative block min-h-0 bg-muted', { - 'row-span-2': images.length === 3 && index === 0, + 'row-span-2': images.length === 3 && position === 0, }); - const thumbnail = ( - - ); - return commit ? ( - { - event.stopPropagation(); - - if (isModifiedClick(event)) { - return; - } - - event.preventDefault(); - openCommitPhoto(commit, index); - }} - className={className} - > - {thumbnail} - - ) : onOpen ? ( - { - if (isModifiedClick(event)) { - return; - } - - event.preventDefault(); - onOpen(index); - }} + commit={commit} + onOpen={onOpen} + image={image} + index={index} className={className} > - {thumbnail} - - ) : ( -
- {thumbnail} -
+ + ); })} diff --git a/resources/js/components/commit-thread.tsx b/resources/js/components/commit-thread.tsx index 49321cdd17..47a416f092 100644 --- a/resources/js/components/commit-thread.tsx +++ b/resources/js/components/commit-thread.tsx @@ -81,6 +81,7 @@ import { } from '@/hooks/use-deleted-resources'; import { useEmojiInsertion } from '@/hooks/use-emoji-insertion'; import { useImageAttachments } from '@/hooks/use-image-attachments'; +import { useImageInsertion } from '@/hooks/use-image-insertion'; import { focusCommit } from '@/hooks/use-keyboard-shortcuts'; import { useLeaving } from '@/hooks/use-leaving'; import { useLinkCard } from '@/hooks/use-link-card'; @@ -98,7 +99,9 @@ import { minBodyLength, } from '@/lib/commit'; import { changesSince, readAt } from '@/lib/commit-changes'; +import { openCommitPhoto } from '@/lib/commit-photo'; import { changeCountLocally, commitStateKey } from '@/lib/commit-state'; +import { referencedImageIndexes } from '@/lib/image-references'; import { hasModKey } from '@/lib/keyboard'; import { exactCountTitle, formatCount } from '@/lib/numbers'; import { @@ -1474,6 +1477,7 @@ function CommitReply({ const wasDeleted = useIsCommitDeleted(reply.id); const commitNotFound = useCommitNotFound(); const [isConfirming, setIsConfirming] = useState(false); + const [isBodyUnfolded, setIsBodyUnfolded] = useState(false); const request = useHttp, { deleted: DeletedFlash }>( {}, ); @@ -1663,12 +1667,27 @@ function CommitReply({ guildMentions={translation.guildMentions} mentions={reply.mentions} organizationMentions={reply.organization_mentions} - previewSegments={translation.previewSegments} + previewSegments={ + translation.feedSegments ?? + translation.previewSegments + } + images={reply.images} + onImageOpen={(index) => + openCommitPhoto(reply, index) + } + onUnfoldChange={setIsBodyUnfolded} className="text-[15px]" /> {translation.notice} - + {reply.link_preview && reply.link_preview.url !== hiddenLinkPreviewUrl && ( { const commit = @@ -2018,6 +2043,7 @@ function ReplyComposer({ descriptions={attachments.descriptions} onDescribe={attachments.describe} onRemove={attachments.remove} + onInsertInline={insertImage} /> )} diff --git a/resources/js/components/commit-translation.tsx b/resources/js/components/commit-translation.tsx index fc7b461912..319d9f24f9 100644 --- a/resources/js/components/commit-translation.tsx +++ b/resources/js/components/commit-translation.tsx @@ -7,7 +7,28 @@ import { useCommitNotFound } from '@/hooks/use-deleted-resources'; import { signIn } from '@/lib/auth'; import { changesSince, readAt } from '@/lib/commit-changes'; import { coalesce, commitChannel, listen } from '@/lib/realtime'; -import type { Commit, CommitTranslation } from '@/types'; +import type { BodySegment, Commit, CommitTranslation } from '@/types'; + +/** + * The segments actually drawn in the place a collapsed body occupies, so callers can hide only the images already + * visible there. Feed segments win, then the folded excerpt, then the whole body. + */ +export function shownCommitSegments( + commit: Commit, + translated: CommitTranslation['translated'], +): BodySegment[] { + if (translated) { + return ( + translated.feed_segments ?? + translated.preview_segments ?? + translated.body_segments + ); + } + + return ( + commit.feed_segments ?? commit.preview_segments ?? commit.body_segments + ); +} export function useCommitTranslation(commit: Commit) { const { auth, now: serverNow } = usePage().props; @@ -191,9 +212,15 @@ export function useCommitTranslation(commit: Commit) { bodyRef, bodyStyle: { minHeight: bodyHeight }, segments: translated ? translated.body_segments : commit.body_segments, - previewSegments: translated - ? translated.preview_segments - : commit.preview_segments, + previewSegments: + (translated + ? translated.preview_segments + : commit.preview_segments) ?? null, + feedSegments: + (translated ? translated.feed_segments : commit.feed_segments) ?? + null, + // What FoldedCommitBody renders, so callers can hide only the images that are already visible inline. + shownSegments: shownCommitSegments(commit, translated || null), guildMentions: translated ? generated?.translation === translation && generated.source !== commit.translation && diff --git a/resources/js/components/composer-preview.tsx b/resources/js/components/composer-preview.tsx index b8c98631a0..e764a16130 100644 --- a/resources/js/components/composer-preview.tsx +++ b/resources/js/components/composer-preview.tsx @@ -14,6 +14,7 @@ import type { PollDraft } from '@/components/poll-editor'; import { Button } from '@/components/ui/button'; import { useNow } from '@/hooks/use-now'; import { bodySegments, hasCodeBlock } from '@/lib/code'; +import { referencedImageIndexes } from '@/lib/image-references'; import { hasModKey, useKeyLabels } from '@/lib/keyboard'; import { cn } from '@/lib/utils'; import type { BodySegment } from '@/types'; @@ -300,6 +301,12 @@ export function ComposerPreviewBody({ url: string | null; className?: string; }) { + const shownImages = images.map((image, index) => ({ + id: objectUrlFor(image), + url: objectUrlFor(image), + description: descriptions[index]?.trim() || null, + })); + return (
) : ( @@ -326,11 +334,8 @@ export function ComposerPreviewBody({ )} ({ - id: objectUrlFor(image), - url: objectUrlFor(image), - description: descriptions[index]?.trim() || null, - }))} + images={shownImages} + omit={referencedImageIndexes(preview.segments)} /> {url && ( diff --git a/resources/js/components/link-topic-commits.tsx b/resources/js/components/link-topic-commits.tsx index fa186f9ca7..2fd654bb58 100644 --- a/resources/js/components/link-topic-commits.tsx +++ b/resources/js/components/link-topic-commits.tsx @@ -2,7 +2,7 @@ import { Link } from '@inertiajs/react'; import type { InertiaLinkProps } from '@inertiajs/react'; import { CornerDownRight } from 'lucide-react'; import type { CSSProperties } from 'react'; -import { useCallback, useRef } from 'react'; +import { useCallback, useRef, useState } from 'react'; import CommitController from '@/actions/App/Http/Controllers/CommitController'; import { AuthorAvatar } from '@/components/author-avatar'; import { FoldedCommitBody } from '@/components/commit-body'; @@ -31,6 +31,8 @@ import { TimestampTooltip } from '@/components/timestamp-tooltip'; import { UserPreview } from '@/components/user-preview'; import { useIsCommitDeleted } from '@/hooks/use-deleted-resources'; import { useNow } from '@/hooks/use-now'; +import { openCommitPhoto } from '@/lib/commit-photo'; +import { referencedImageIndexes } from '@/lib/image-references'; import { formatCount } from '@/lib/numbers'; import { cn, @@ -96,6 +98,7 @@ function LinkTopicCommit({ }) { const now = useNow(); const thread = useThread(commit); + const [isBodyUnfolded, setIsBodyUnfolded] = useState(false); const { bodyRef, ...translation } = useCommitTranslation(commit); const wasDeleted = useIsCommitDeleted(commit.id); const nodeRef = useGraphNode({ @@ -237,12 +240,27 @@ function LinkTopicCommit({ guildMentions={translation.guildMentions} mentions={commit.mentions} organizationMentions={commit.organization_mentions} - previewSegments={translation.previewSegments} + previewSegments={ + translation.feedSegments ?? + translation.previewSegments + } + images={commit.images} + onImageOpen={(index) => + openCommitPhoto(commit, index) + } + onUnfoldChange={setIsBodyUnfolded} className="mt-0.5 text-[15px]" />
{translation.notice} - + {commit.poll && ( {withWordmarks(text, 0, pasteisMode)}; +} + export function LinkifiedText({ text, mentions, diff --git a/resources/js/hooks/use-image-insertion.ts b/resources/js/hooks/use-image-insertion.ts new file mode 100644 index 0000000000..e736b23a79 --- /dev/null +++ b/resources/js/hooks/use-image-insertion.ts @@ -0,0 +1,65 @@ +import type { RefObject } from 'react'; +import { useLayoutEffect, useRef } from 'react'; +import { imageReference } from '@/lib/image-references'; +import { insertAtSelection } from '@/lib/text-selection'; + +type InsertImage = (index: number, alt: string | null) => void; + +/** + * Inserts a reference to an attached image where the caret was, the same way an emoji or a markdown format is inserted. + */ +export function useImageInsertion({ + body, + updateBody, + textareaRef, + maxLength, +}: { + body: string; + updateBody: (body: string) => void; + textareaRef: RefObject; + maxLength: number; +}): { insertImage: InsertImage } { + const caret = useRef(null); + + useLayoutEffect(() => { + const element = textareaRef.current; + + if (caret.current === null || element === null) { + return; + } + + element.focus(); + element.setSelectionRange(caret.current, caret.current); + caret.current = null; + }, [body, textareaRef]); + + const insertImage: InsertImage = (index, alt) => { + const element = textareaRef.current; + const inserted = insertAtSelection( + body, + element, + imageReference(index, alt), + maxLength, + ); + + if (inserted === null) { + return; + } + + if (inserted.value === body) { + caret.current = null; + + if (element !== null) { + element.focus(); + element.setSelectionRange(inserted.caret, inserted.caret); + } + + return; + } + + caret.current = inserted.caret; + updateBody(inserted.value); + }; + + return { insertImage }; +} diff --git a/resources/js/lib/code.ts b/resources/js/lib/code.ts index b819b20f4f..812320f091 100644 --- a/resources/js/lib/code.ts +++ b/resources/js/lib/code.ts @@ -1,4 +1,5 @@ import type { BodySegment } from '@/types'; +import { imageReferences } from './image-references.ts'; // Keep in sync with app/Services/CodeSpans.php: a fenced code block, from a line starting with ``` or more (and maybe // a language) to a line that is only as many backticks or more, so a block can hold a shorter fence, or inline code @@ -134,13 +135,48 @@ export function bodySegments(text: string): BodySegment[] { } }); - return segments; + return imageReferences(segments); } export function hasCodeBlock(segments: BodySegment[]): boolean { return segments.some((segment) => segment.type === 'block'); } +/** + * Images are block-level, so a newline immediately after one would add an empty line on top of the block break. + * Drop that first newline; later ones stay as the blank lines the author wrote. + */ +function withoutImageBoundaryNewlines(segments: BodySegment[]): BodySegment[] { + const flattened: BodySegment[] = []; + let afterImage = false; + + for (const segment of segments) { + if (segment.type !== 'text') { + flattened.push(segment); + afterImage = segment.type === 'image'; + + continue; + } + + for (const text of segment.text.split(/(?<=\n)/)) { + if (!afterImage) { + flattened.push({ type: 'text', text }); + + continue; + } + + afterImage = false; + const trimmed = text.replace(/^\r?\n/, ''); + + if (trimmed !== '') { + flattened.push({ type: 'text', text: trimmed }); + } + } + } + + return flattened; +} + /** * Groups quoted prose lines without interpreting markers inside code or changing the stored segments. */ @@ -151,14 +187,12 @@ export function bodyBlocks( let atLineStart = true; let quoted = false; - for (const segment of segments.flatMap((segment): BodySegment[] => - segment.type === 'text' - ? segment.text - .split(/(?<=\n)/) - .map((text) => ({ type: 'text', text })) - : [segment], - )) { - if (atLineStart || segment.type === 'block') { + for (const segment of withoutImageBoundaryNewlines(segments)) { + if ( + atLineStart || + segment.type === 'block' || + segment.type === 'image' + ) { quoted = segment.type === 'text' && segment.text.startsWith('>'); } @@ -182,6 +216,7 @@ export function bodyBlocks( atLineStart = segment.type === 'block' || + segment.type === 'image' || (segment.type === 'text' && segment.text.endsWith('\n')); } diff --git a/resources/js/lib/image-references.ts b/resources/js/lib/image-references.ts new file mode 100644 index 0000000000..d0be0977b9 --- /dev/null +++ b/resources/js/lib/image-references.ts @@ -0,0 +1,95 @@ +import type { BodySegment } from '@/types'; +import { maxImages } from './read-picked-images.ts'; + +// Keep in sync with app/Services/ImageReferences.php. Alt text escapes backslashes, brackets and line breaks. +const pattern = /!\(([1-9][0-9]*)\)\[((?:\\.|[^\\\]\r\n])*)\]/g; + +function escapeAlt(alt: string): string { + return alt + .replace(/\\/g, '\\\\') + .replace(/\]/g, '\\]') + .replace(/`/g, '\\b') + .replace(/\r\n|\r|\n/g, '\\n'); +} + +function unescapeAlt(alt: string): string { + return alt.replace(/\\([nb\]\\])/g, (_match, escaped: string) => + escaped === 'n' ? '\n' : escaped === 'b' ? '`' : escaped, + ); +} + +/** The token written into a body to place an attached image. */ +export function imageReference(index: number, alt: string | null): string { + return `!(${index})[${alt === null ? '' : escapeAlt(alt)}]`; +} + +/** + * Splits prose into text and image reference segments. References past the last image slot stay as text, so a body + * written before its images are attached keeps exactly what the author typed. + */ +export function splitImageReferences(prose: string): BodySegment[] { + const matches = [...prose.matchAll(pattern)]; + + if (matches.length === 0) { + return [{ type: 'text', text: prose }]; + } + + const segments: BodySegment[] = []; + let offset = 0; + + for (const match of matches) { + const token = match[0]; + const position = match.index ?? 0; + + if (position > offset) { + segments.push({ + type: 'text', + text: prose.slice(offset, position), + }); + } + + const index = Number(match[1]); + + const alt = unescapeAlt(match[2]).trim(); + + if (index > maxImages) { + segments.push({ type: 'text', text: token }); + } else { + segments.push({ + type: 'image', + index, + alt: alt === '' ? null : alt, + }); + } + + offset = position + token.length; + } + + if (offset < prose.length) { + segments.push({ type: 'text', text: prose.slice(offset) }); + } + + return segments; +} + +/** Applies the image reference tokenizer to prose only, leaving code and code blocks alone. */ +export function imageReferences(segments: BodySegment[]): BodySegment[] { + return segments.flatMap((segment) => + segment.type === 'text' + ? splitImageReferences(segment.text) + : [segment], + ); +} + +/** The 1-based positions of the attached images a body places inline. */ +export function referencedImageIndexes(segments: BodySegment[]): Set { + const indexes: number[] = []; + + for (const segment of segments) { + if (segment.type === 'image') { + indexes.push(segment.index); + } + } + + return new Set(indexes); +} diff --git a/resources/js/pages/notification/index.tsx b/resources/js/pages/notification/index.tsx index 1428874df4..1f63f6b06f 100644 --- a/resources/js/pages/notification/index.tsx +++ b/resources/js/pages/notification/index.tsx @@ -1072,7 +1072,10 @@ function OwnCommitExcerpt({ segments }: { segments: BodySegment[] }) { function QuotedOwnCommit({ commit, }: { - commit: Pick | DeletedCommit | null; + commit: + | Pick + | DeletedCommit + | null; }) { if (commit === null || isDeleted(commit)) { return ; diff --git a/resources/js/types/commit.ts b/resources/js/types/commit.ts index 6caf8dc6aa..a586145ed6 100644 --- a/resources/js/types/commit.ts +++ b/resources/js/types/commit.ts @@ -60,6 +60,13 @@ export type CommitImage = { export type BodySegment = | { type: 'text'; text: string } | { type: 'code'; code: string } + | { + type: 'image'; + index: number; + alt: string | null; + // How much of the image a feed shows when its bottom is faded and clipped. + visibleHeight?: number; + } | { type: 'block'; language: string | null; @@ -78,6 +85,7 @@ export type CommitTranslation = { body_segments: BodySegment[]; preview_segments: BodySegment[] | null; guild_mentions?: GuildMentions; + feed_segments: BodySegment[] | null; } | null; }; @@ -107,6 +115,7 @@ export type Commit = { organization_mentions?: Record | null; body_segments: BodySegment[]; preview_segments: BodySegment[] | null; + feed_segments: BodySegment[] | null; translation?: CommitTranslation | null; status: CommitStatus; is_checking?: boolean; @@ -144,6 +153,7 @@ export type QuotedCommit = Pick< | 'body' | 'body_segments' | 'preview_segments' + | 'feed_segments' | 'guild_mentions' | 'status' | 'is_checking' diff --git a/resources/js/types/notification.ts b/resources/js/types/notification.ts index 8a7a253337..4a32ac2be0 100644 --- a/resources/js/types/notification.ts +++ b/resources/js/types/notification.ts @@ -69,7 +69,10 @@ export type Notification = subject_id: null; commit: Omit & { quoted_commit?: - | Pick + | Pick< + Commit, + 'id' | 'body_segments' | 'feed_segments' | 'deleted_at' + > | DeletedCommit | null; }; diff --git a/tests/Feature/Controllers/Api/CommitControllerTest.php b/tests/Feature/Controllers/Api/CommitControllerTest.php index 2d0348dda6..0593e8991e 100644 --- a/tests/Feature/Controllers/Api/CommitControllerTest.php +++ b/tests/Feature/Controllers/Api/CommitControllerTest.php @@ -344,6 +344,7 @@ ['type' => 'code', 'code' => '@Override'], ], 'preview_segments' => null, + 'feed_segments' => null, 'mentions' => [['handle' => 'nunomaduro', 'offset' => 4, 'length' => 11, 'kind' => 'user', 'id' => null]], 'status' => 'approved', 'is_pinned' => false, @@ -370,6 +371,7 @@ 'author' => $author($root->user), 'body_segments' => [['type' => 'text', 'text' => 'Who broke prod?']], 'preview_segments' => null, + 'feed_segments' => null, 'mentions' => [], 'status' => 'approved', 'is_pinned' => false, diff --git a/tests/Feature/Controllers/Api/LogControllerTest.php b/tests/Feature/Controllers/Api/LogControllerTest.php index 6757f8b0f9..b7cfea93a9 100644 --- a/tests/Feature/Controllers/Api/LogControllerTest.php +++ b/tests/Feature/Controllers/Api/LogControllerTest.php @@ -82,6 +82,7 @@ ], 'body_segments' => [['type' => 'text', 'text' => 'It was DNS.']], 'preview_segments' => null, + 'feed_segments' => null, 'mentions' => [], 'status' => 'approved', 'is_pinned' => false, diff --git a/tests/Feature/Controllers/Api/NotificationControllerTest.php b/tests/Feature/Controllers/Api/NotificationControllerTest.php index 57784d42c5..3811561c9a 100644 --- a/tests/Feature/Controllers/Api/NotificationControllerTest.php +++ b/tests/Feature/Controllers/Api/NotificationControllerTest.php @@ -68,6 +68,7 @@ 'author' => ['type' => 'user', ...$user($replied->actor->user)], 'body_segments' => [['type' => 'text', 'text' => $reply->body]], 'preview_segments' => null, + 'feed_segments' => null, 'mentions' => [], 'status' => 'approved', 'is_pinned' => false, @@ -83,6 +84,7 @@ 'author' => ['type' => 'user', ...$user($this->user)], 'body_segments' => [['type' => 'text', 'text' => $reply->parent->body]], 'preview_segments' => null, + 'feed_segments' => null, 'mentions' => [], 'status' => 'approved', 'is_pinned' => false, diff --git a/tests/Feature/Controllers/Api/ScheduledCommitControllerTest.php b/tests/Feature/Controllers/Api/ScheduledCommitControllerTest.php index 63708d14bc..0b3fbe3cfd 100644 --- a/tests/Feature/Controllers/Api/ScheduledCommitControllerTest.php +++ b/tests/Feature/Controllers/Api/ScheduledCommitControllerTest.php @@ -70,6 +70,20 @@ ->and(Commit::query()->count())->toBe(0); }); +it('keeps image references as text in a scheduled draft, until images exist to attach', function (): void { + ScheduledCommit::factory()->for($this->user)->create([ + 'scheduled_at' => now()->addHour(), + 'body' => 'Look !(1)[the build] and `!(2)[code]`', + ]); + + signedApiRequest($this->keyPair, 'GET', route('api-scheduled-commit.index')) + ->assertOk() + ->assertJsonPath('data.0.body_segments', [ + ['type' => 'text', 'text' => 'Look !(1)[the build] and '], + ['type' => 'code', 'code' => '!(2)[code]'], + ]); +}); + it('schedules a poll that opens with its commit at the due time', function (): void { signedApiRequest($this->keyPair, 'POST', route('api-scheduled-commit.store'), [ 'body' => 'Tabs or spaces?', diff --git a/tests/Unit/BodyBlocks.test.ts b/tests/Unit/BodyBlocks.test.ts new file mode 100644 index 0000000000..c8acec0c3d --- /dev/null +++ b/tests/Unit/BodyBlocks.test.ts @@ -0,0 +1,77 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { bodyBlocks, bodySegments } from '../../resources/js/lib/code.ts'; + +test('keeps one blank line after an inline image', () => { + const blocks = bodyBlocks(bodySegments('Before\n!(1)[Alt]\n\nAfter')); + + assert.deepEqual(blocks, [ + { + quoted: false, + segments: [ + { type: 'text', text: 'Before\n' }, + { type: 'image', index: 1, alt: 'Alt' }, + { type: 'text', text: '\n' }, + { type: 'text', text: 'After' }, + ], + }, + ]); +}); + +test('drops the boundary newline when no blank line was written', () => { + const blocks = bodyBlocks(bodySegments('Before\n!(1)[Alt]\nAfter')); + + assert.deepEqual(blocks, [ + { + quoted: false, + segments: [ + { type: 'text', text: 'Before\n' }, + { type: 'image', index: 1, alt: 'Alt' }, + { type: 'text', text: 'After' }, + ], + }, + ]); +}); + +test('does not leave a blank line between adjacent images', () => { + const blocks = bodyBlocks(bodySegments('!(1)[First]\n!(2)[Second]')); + + assert.deepEqual(blocks, [ + { + quoted: false, + segments: [ + { type: 'image', index: 1, alt: 'First' }, + { type: 'image', index: 2, alt: 'Second' }, + ], + }, + ]); +}); + +test('leaves an inline reference on the same line', () => { + const blocks = bodyBlocks(bodySegments('Before !(1)[Alt] after')); + + assert.deepEqual(blocks, [ + { + quoted: false, + segments: [ + { type: 'text', text: 'Before ' }, + { type: 'image', index: 1, alt: 'Alt' }, + { type: 'text', text: ' after' }, + ], + }, + ]); +}); + +test('leaves an image at the end of the body alone', () => { + const blocks = bodyBlocks(bodySegments('Before\n!(1)[Alt]')); + + assert.deepEqual(blocks, [ + { + quoted: false, + segments: [ + { type: 'text', text: 'Before\n' }, + { type: 'image', index: 1, alt: 'Alt' }, + ], + }, + ]); +}); diff --git a/tests/Unit/CommitBodyImages.test.tsx b/tests/Unit/CommitBodyImages.test.tsx new file mode 100644 index 0000000000..b1bc46519d --- /dev/null +++ b/tests/Unit/CommitBodyImages.test.tsx @@ -0,0 +1,204 @@ +import assert from 'node:assert/strict'; +import { App } from '@inertiajs/react'; +import type { ComponentProps } from 'react'; +import { renderToStaticMarkup } from 'react-dom/server'; +import { test } from 'vite-plus/test'; +import { + CommitBody, + CommitBodyExcerpt, +} from '../../resources/js/components/commit-body'; +import type { ShownImage } from '../../resources/js/components/commit-images'; +import type { BodySegment } from '../../resources/js/types'; + +function renderBody( + segments: BodySegment[], + images: ShownImage[] = [], + onImageOpen?: (index: number) => void, + pasteis: unknown = null, +) { + return renderToStaticMarkup( + ( + + )} + initialPage={ + { + component: 'Preview', + url: '/', + version: null, + props: { + errors: {}, + auth: { user: null, pasteis, isAdmin: false }, + }, + clearHistory: false, + encryptHistory: false, + } as unknown as ComponentProps['initialPage'] + } + />, + ); +} + +function renderExcerpt(segments: BodySegment[]) { + return renderToStaticMarkup( + } + initialPage={ + { + component: 'Preview', + url: '/', + version: null, + props: { + errors: {}, + auth: { user: null, pasteis: null, isAdmin: false }, + }, + clearHistory: false, + encryptHistory: false, + } as unknown as ComponentProps['initialPage'] + } + />, + ); +} + +const images: ShownImage[] = [ + { id: 'first', url: '/images/first.webp', description: null }, + { id: 'second', url: '/images/second.webp', description: null }, +]; + +test('renders an inline image where the body places it', () => { + const markup = renderBody( + [ + { type: 'text', text: 'Coffee ' }, + { type: 'image', index: 1, alt: 'Woke up to Coffee' }, + { type: 'text', text: ' then code.' }, + ], + images, + ); + + assert.match(markup, /
/); +}); + +test('uses a generic alt and no caption when the reference has no text', () => { + const markup = renderBody([{ type: 'image', index: 2, alt: null }], images); + + assert.match(markup, /alt="Attached image 2"/); + assert.match(markup, /src="\/images\/second\.webp"/); + assert.doesNotMatch(markup, /
{ + const markup = renderBody( + [{ type: 'image', index: 1, alt: ':smile: pasteis /dev/null' }], + images, + undefined, + { remaining: 1, day: '2026-11-26' }, + ); + + assert.match(markup, /alt="😄 pasteis \/dev\/null"/); + assert.match(markup, /😄/); + assert.match(markup, /pastel-de-nata\.svg/); + assert.match(markup, /title="\/dev\/null"/); + assert.match(markup, /text-transparent/); +}); + +test('keeps an unresolved reference as literal text', () => { + const markup = renderBody([ + { type: 'text', text: 'Before ' }, + { type: 'image', index: 1, alt: 'Later' }, + ]); + + assert.match(markup, /Before/); + assert.match(markup, /!\(1\)\[Later\]/); + assert.doesNotMatch(markup, /
{ + const markup = renderBody([{ type: 'image', index: 1, alt: 'a]b\\c' }]); + + assert.match(markup, /!\(1\)\[a\\\]b\\\\c\]/); +}); + +test('clips, shades, and expands a partly shown feed image in place', () => { + const markup = renderBody( + [{ type: 'image', index: 1, alt: 'Tall', visibleHeight: 280 }], + [{ ...images[0], width: 530, height: 600 }], + () => {}, + ); + + assert.match(markup, /data-image-crop/); + assert.match(markup, /data-image-scrim/); + assert.match(markup, /feed-image-scrim pointer-events-none/); + assert.match(markup, /data-image-expand-surface/); + assert.match(markup, /data-image-expand/); + assert.match(markup, /border-foreground\/20 bg-card\/95/); + assert.doesNotMatch(markup, /mask-b-from-/); + assert.match(markup, /aspect-ratio:530 \/ 304/); + assert.match(markup, /max-width:530px/); + assert.doesNotMatch(markup, /style="[^"]*height:\d+px/); + assert.doesNotMatch(markup, /]*group[^>]*>[\s\S]*data-image-chevron/); + assert.doesNotMatch(markup, /
{ + const markup = renderBody( + [ + { + type: 'image', + index: 1, + alt: 'Beyond the sea', + visibleHeight: 209, + }, + ], + [{ ...images[0], width: 1100, height: 461 }], + () => {}, + ); + + assert.match(markup, /data-image-crop/); + assert.match(markup, /aspect-ratio:530 \/ 222/); + assert.match(markup, /max-width:530px/); + assert.doesNotMatch(markup, /style="[^"]*height:\d+px/); +}); + +test('leaves a whole body image uncropped and captioned', () => { + const markup = renderBody( + [{ type: 'image', index: 1, alt: 'Whole' }], + [{ ...images[0], width: 530, height: 600 }], + ); + + assert.doesNotMatch(markup, /data-image-crop/); + assert.doesNotMatch(markup, /data-image-scrim/); + assert.doesNotMatch(markup, /data-image-expand/); + assert.match(markup, /Whole<\/figcaption>/); +}); + +test('hides image references from clamped excerpts', () => { + const markup = renderExcerpt([ + { type: 'text', text: 'Coffee ' }, + { type: 'image', index: 1, alt: 'Woke up to Coffee' }, + { type: 'text', text: ' then code.' }, + ]); + + assert.match(markup, /Coffee/); + assert.match(markup, /then code\./); + assert.doesNotMatch(markup, /!\[Woke up to Coffee\]\(1\)/); + assert.doesNotMatch(markup, /!\(1\)\[Woke up to Coffee\]/); + assert.doesNotMatch(markup, /
{ +test('keeps the uploaded image until it fails to load', () => { assert.ok( renderToStaticMarkup().includes( 'src="/images/missing.webp"', @@ -62,17 +63,26 @@ const commit: Commit = { ); }); - test('fits a single feed image instead of cropping it to fill the width', () => { +test('fits a single feed image instead of cropping it to fill the width', () => { const markup = renderToStaticMarkup(); assert.match(markup, /class="[^"]*\bobject-contain\b/); assert.doesNotMatch(markup, /class="[^"]*\bobject-cover\b/); }); - test('covers landscape grid images and contains tall ones', () => { - assert.equal(gridImageObjectFit({ width: 80, height: 800 }), 'object-contain'); - assert.equal(gridImageObjectFit({ width: 1200, height: 800 }), 'object-cover'); - assert.equal(gridImageObjectFit({ width: 100, height: 100 }), 'object-cover'); +test('covers landscape grid images and contains tall ones', () => { + assert.equal( + gridImageObjectFit({ width: 80, height: 800 }), + 'object-contain', + ); + assert.equal( + gridImageObjectFit({ width: 1200, height: 800 }), + 'object-cover', + ); + assert.equal( + gridImageObjectFit({ width: 100, height: 100 }), + 'object-cover', + ); assert.equal(gridImageObjectFit({}), 'object-cover'); const markup = renderToStaticMarkup( @@ -109,7 +119,7 @@ const commit: Commit = { ); }); - test('shows the short image hash instead of the alt text while the image loads', () => { +test('shows the short image hash instead of the alt text while the image loads', () => { const markup = renderToStaticMarkup(); const placeholder = markup.match( /