Repository navigation
feat(admin): optional link on portable-text image blocks - #3167
Conversation
🦋 Changeset detectedLatest commit: bc5025f The changes in this PR will be included in the next version bump. This PR includes changesets to release 12 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
|
All contributors have signed the CLA ✍️ ✅ |
|
I have read the CLA Document and I hereby sign the CLA |
Overlapping PRsThis PR modifies files that are also changed by other open PRs:
This may cause merge conflicts or duplicated work. A maintainer will coordinate. |
@emdash-cms/admin
@emdash-cms/auth
@emdash-cms/auth-atproto
@emdash-cms/blocks
@emdash-cms/cloudflare
@emdash-cms/contentful-to-portable-text
emdash
create-emdash
@emdash-cms/gutenberg-to-portable-text
@emdash-cms/plugin-cli
@emdash-cms/plugin-test
@emdash-cms/plugin-types
@emdash-cms/registry-client
@emdash-cms/registry-lexicons
@emdash-cms/registry-loader
@emdash-cms/registry-moderation
@emdash-cms/registry-verification
@emdash-cms/sandbox-workerd
@emdash-cms/x402
@emdash-cms/plugin-ai-moderation
@emdash-cms/plugin-atproto
@emdash-cms/plugin-audit-log
@emdash-cms/plugin-color
@emdash-cms/plugin-embeds
@emdash-cms/plugin-field-kit
@emdash-cms/plugin-forms
@emdash-cms/plugin-webhook-notifier
commit: |
There was a problem hiding this comment.
This is a well-scoped, approved feature (Discussion #2741) that adds a wrapped link to Portable Text image blocks consistently across the admin editor and the Astro renderer. The implementation is mostly careful: half-populated { blank: true } objects are dropped on save, Lingui wrapping is present, and tests cover the blank-preservation regression from #704.
I found three issues worth addressing before merge:
- Legacy image-link shape collision. The WordPress/Gutenberg converter has been emitting image links as
link: "url"(a plain string). The new core/admin converters andImage.astrotreatlinkas{ href, blank? }. Existing imported posts with string links will silently drop their link metadata the first time they are edited. The PT→PM converters, renderer, and ideally the Gutenberg converter + WordPress URL rewriter should normalize both shapes. ImageDetailPanelstate-sync omission. The existinguseEffectthat resets form state for a new attribute snapshot does not resetlinkHref/linkBlank, leaving stale link state if the panel is ever updated in place.- Same-page anchor handling.
Link.astroforces same-tab behavior for#sectionanchors even whenblankis true;Image.astroshould mirror that behavior for consistency.
Fixing #1 is the most important — it prevents data loss for any site that has imported WordPress content with linked images.
Findings
-
[needs fixing]
packages/core/src/content/converters/portable-text-to-prosemirror.ts:665convertImage dereferences
block.link.href/blank, assuminglinkis already the new object shape. Existing WordPress/Gutenberg imports store image links aslink: "url"strings, so loading such a post silently drops the link here and loses it on the next save. Normalize both legacy strings and the new object before building the ProseMirror attrs.link: normalizeImageLink(block.link),Add a small helper in this file (or in
converters/types.ts):function normalizeImageLink(link: unknown): { href: string; blank?: boolean } | null { if (!link) return null; if (typeof link === "string") { const href = link.trim(); return href ? { href } : null; } if (typeof link === "object" && "href" in link) { const href = typeof (link as Record<string, unknown>).href === "string" ? ((link as Record<string, unknown>).href as string).trim() : ""; if (!href) return null; return (link as Record<string, unknown>).blank === true ? { href, blank: true } : { href }; } return null; }
-
[needs fixing]
packages/admin/src/components/PortableTextEditor.tsx:1242The admin PT→PM conversion makes the same object-only assumption as the core converter. Existing imported content with
link: "url"will lose its link when opened in the editor. Use the same normalization so both legacy strings and the new object shape round-trip.link: normalizeImageLink(imageBlock.link),(Define
normalizeImageLinklocally or import a shared helper from the core converters.) -
[needs fixing]
packages/core/src/components/Image.astro:83The renderer only reads
link.href, so a legacylink: "url"from an existing WordPress import would not render as a link even after the converters normalize it. Accept either shape in the render path.const rawHref = typeof link === "string" ? link : link?.href; const linkHref = rawHref ? sanitizeHref(rawHref) : null; -
[needs fixing]
packages/gutenberg-to-portable-text/src/index.ts:236The Gutenberg converter is still emitting the old
link: stringshape. Now that the canonical Portable Text image block uses{ href, blank? }, new imports should produce the same shape so downstream code does not need to carry two shapes forever.link: linkUrl ? { href: linkUrl } : undefined,Also update
packages/gutenberg-to-portable-text/src/types.tsandpackages/core/src/astro/routes/api/import/wordpress/rewrite-url-helpers.tsso the type and the WordPress URL rewriter operate on the new object shape. -
[needs fixing]
packages/core/src/astro/routes/api/import/wordpress/rewrite-url-helpers.ts:120After moving the Gutenberg converter to the object shape, this rewriter will miss imported image links because it reads
block.linkas a string. Handle both legacy strings and the new object.if (block._type === "image" && block.link) { const href = typeof block.link === "string" ? block.link : block.link.href; const newUrl = findMatchingUrl(href, exactMap, baseMap); if (newUrl) { if (typeof block.link === "string") { block.link = newUrl; } else { block.link.href = newUrl; } changed = true; urlsRewritten++; } } -
[needs fixing]
packages/admin/src/components/editor/ImageDetailPanel.tsx:153-162The existing
useEffectresets alt/caption/title/asset/size/alignment when the attribute snapshot changes, but it omitslinkHrefandlinkBlank. If the panel is ever updated in place (or the node-key trigger changes), the link fields stay stale.React.useEffect(() => { setAlt(attributes.alt ?? ""); setCaption(attributes.caption ?? ""); setTitle(attributes.title ?? ""); setAsset(attributes); setHasCustomSize(attributes.displayWidth != null || attributes.displayHeight != null); setDisplayWidth(attributes.displayWidth ?? undefined); setDisplayHeight(attributes.displayHeight ?? undefined); setLockAspectRatio(true); setAlignment(attributes.alignment); setLinkHref(attributes.link?.href ?? ""); setLinkBlank(Boolean(attributes.link?.blank)); // eslint-disable-next-line react-hooks/exhaustive-deps -- the node token identifies a new attribute snapshot }, [nodeKey]); -
[suggestion]
packages/core/src/components/Image.astro:84Link.astro suppresses
target="_blank"for same-page anchors (#section) because opening an on-page jump in a new tab is undesirable. Image.astro currently honorsblank: trueunconditionally, so an image linked to#sectionwould open in a new tab. Consider mirroring Link.astro.const linkHref = link?.href ? sanitizeHref(link.href) : null; const isSamePageAnchor = !!linkHref && linkHref.startsWith("#"); const linkTarget = link?.blank && !isSamePageAnchor ? "_blank" : undefined; const linkRel = link?.blank && !isSamePageAnchor ? "noopener noreferrer" : undefined;
…hors same-tab Addresses the three review findings on emdash-cms#3167. Legacy link shape: `gutenberg-to-portable-text` emits `link: "https://…"` (a bare string) for linked images, so WordPress-imported content carries that shape while the editor writes `{ href, blank? }`. The converters and `Image.astro` read `link.href` directly, which silently dropped the link on imported posts. A shared `normalizeImageLink()` now accepts both shapes; the PT type, `Image.astro`, the PT→PM converter and the admin editor go through it, so a legacy string renders and is upgraded to the object shape on its next round-trip. The WordPress URL rewriter handles both shapes too (it previously assumed a string). Admin has no dependency on the core package, so it carries a small mirror of the helper. Panel resync: `ImageDetailPanel`'s node-switch effect reset every field except `linkHref`/`linkBlank`, leaving the previous image's link in the form. Both are now reset with the rest. Same-page anchors: `Image.astro` honoured `blank` unconditionally, unlike `marks/Link.astro`, which never opens `#section` links in a new tab. The image wrapper now mirrors that rule. Tests: unit coverage for `normalizeImageLink` and the legacy-string round-trip, URL rewriting for both link shapes, Astro render cases for new-tab / same-page-anchor / legacy-string links, and the panel resync test now covers the link fields. Co-Authored-By: Claude <[email protected]>
|
Thanks for the review. All three are addressed in 5aa743b.
Tests added for the normaliser, the legacy-string round-trip, URL Generated by Claude Code |
5aa743b to
c1ac676
Compare
…hors same-tab Addresses the three review findings on emdash-cms#3167. Legacy link shape: `gutenberg-to-portable-text` emits `link: "https://…"` (a bare string) for linked images, so WordPress-imported content carries that shape while the editor writes `{ href, blank? }`. The converters and `Image.astro` read `link.href` directly, which silently dropped the link on imported posts. A shared `normalizeImageLink()` now accepts both shapes; the PT type, `Image.astro`, the PT→PM converter and the admin editor go through it, so a legacy string renders and is upgraded to the object shape on its next round-trip. The WordPress URL rewriter handles both shapes too (it previously assumed a string). Admin has no dependency on the core package, so it carries a small mirror of the helper. Panel resync: `ImageDetailPanel`'s node-switch effect reset every field except `linkHref`/`linkBlank`, leaving the previous image's link in the form. Both are now reset with the rest. Same-page anchors: `Image.astro` honoured `blank` unconditionally, unlike `marks/Link.astro`, which never opens `#section` links in a new tab. The image wrapper now mirrors that rule. Tests: unit coverage for `normalizeImageLink` and the legacy-string round-trip, URL rewriting for both link shapes, Astro render cases for new-tab / same-page-anchor / legacy-string links, and the panel resync test now covers the link fields. Co-Authored-By: Claude <[email protected]>
There was a problem hiding this comment.
This re-review confirms that all three issues from the previous review have been addressed:
- Legacy
link: stringshape —normalizeImageLink()now lives inpackages/core/src/content/converters/image-link.tsand is used by the core PT↔PM converters,Image.astro, and (via a mirrored local helper) the admin editor. Existing WordPress-imported linked images keep their link and are upgraded to the object shape on the first round-trip. ImageDetailPanelstate sync — the resetuseEffectnow resetslinkHrefandlinkBlankalongside the other fields, with a regression test.- Same-page anchor handling —
Image.astromirrorsLink.astro:#sectionlinks never open in a new tab.
The approach is sound: read-time normalization is a defensible way to support legacy strings without touching the Gutenberg package, and the new UI surfaces are properly Lingui-wrapped.
I found one new issue: the PR claims the image link can be edited from the bubble menu, but the bubble menu's shouldShow only allows TextSelection and AllSelection. Images in this editor are selected via NodeSelection, so the bubble menu never appears for an image and the new image-link bubble-menu code is unreachable. Toolbar and sidebar editing still work, but the bubble-menu path is dead.
Fixing that plus a focused regression test for the bubble-menu image-link flow would make this ready to merge.
Findings
-
[needs fixing]
packages/admin/src/components/PortableTextEditor.tsx:3974The inline bubble menu's
shouldShowonly allowsTextSelectionorAllSelection, but images in this editor are selected with aNodeSelection(seeImageNodeView.handlePointerDownwhich callseditor.commands.setNodeSelection). Because of this, the bubble menu never appears when an image is selected, so the image-link support added to the bubble menu (activeMarks.imageLink, theeditor.isActive("image")branches inhandleSetLink/handleRemoveLink, etc.) is unreachable. The PR description says the bubble-menu link button works on image selections.Allow image
NodeSelections in this check (and importNodeSelectionso the condition can be type-safe):import { AllSelection, NodeSelection, TextSelection } from "@tiptap/pm/state";shouldShow={({ editor: activeEditor, element, state, view }) => { const { selection } = state; const isImageNodeSelection = selection instanceof NodeSelection && selection.node.type.name === "image"; return ( activeEditor.isEditable && (selection instanceof TextSelection || selection instanceof AllSelection || isImageNodeSelection) && !selection.empty && (view.hasFocus() || element.contains(document.activeElement)) ); }}Once this is wired up, add a browser test that selects an image node and opens/edits the link from the bubble menu so this path doesn't regress again.
There was a problem hiding this comment.
This is a focused re-review of the image-link feature. The three blockers from the previous review are resolved: legacy link: string links are normalized by the shared normalizeImageLink() helper, ImageDetailPanel now resets linkHref/linkBlank when the selected node changes, and Image.astro correctly treats #anchor links as same-page jumps. New UI strings are Lingui-wrapped and the changeset is user-facing and proportionate.
I found one remaining functional issue: the PR enables the inline bubble menu for image selections, but the shouldShow predicate still requires !selection.empty. A NodeSelection (the selection type used when an image node is selected) has the same anchor/head position, so selection.empty is true. Because of that guard, the inline bubble menu will still not appear for selected images and the new bubble-menu image-link code remains unreachable. The existing bubble-menu.test.tsx regression tests need this guard adjusted before they can exercise that path.
Aside from that, the PR is in good shape. One small accessibility/usability suggestion is noted.
…is selected The toolbar link button already switched its tooltip to "Image link" when an image is selected, but its accessible name stayed "Insert Link", so screen reader users heard a different label from the one shown. The aria-label now follows the same condition as the tooltip. The three tests that open the link control with an image selected now locate the button by the exact name "Image link", so they fail if the two drift apart again. Co-Authored-By: Claude <[email protected]>
|
Thanks for the re-review. On the The Generated by Claude Code |
# Conflicts: # packages/core/src/components/Image.astro # packages/core/src/content/converters/portable-text-to-prosemirror.ts
There was a problem hiding this comment.
This is the right change for #2497 / Discussion #2741: it adds an optional link object to Portable Text image blocks, surfaces it in the admin toolbar, bubble menu, and image detail panel, normalizes the legacy WordPress string shape on read, and has Image.astro render a sanitized anchor. All three blockers from the previous review are resolved:
- Legacy
link: stringvalues are normalized through the sharednormalizeImageLink()helper. ImageDetailPanelresetslinkHref/linkBlankvia thenodeKeyeffect when the selected node changes.Image.astrocorrectly treats#anchorlinks as same-page jumps and never opens them in a new tab.- The inline bubble-menu
shouldShowguard now allows imageNodeSelections even though theirselection.emptyistrue, so the new image-link bubble-menu code is actually reachable.
I read the converter pair, the Astro renderer, the admin editor/link/bubble-menu code, ImageDetailPanel, ImageNode, and the tests. The implementation is clean and the test coverage (converter round-trip, legacy-string upgrade, half-populated drop, render output, toolbar/bubble-menu/panel regression cases) is solid.
The only remaining functional gap is in packages/core/src/import/utils.ts: relativizeContentLinks() still assumes an image block’s link is a bare string. Now that the canonical shape is { href, blank? }, any content carrying the object shape through that helper will silently skip internal-link relativization, leaving absolute WordPress-domain URLs in image blocks. The sibling rewritePortableTextUrls() already handles both shapes; relativizeContentLinks() should do the same.
Findings
-
[needs fixing]
packages/core/src/import/utils.ts:348-350relativizeContentLinks()passesblock.linkstraight torelativizeUrl(url: string), which only works when the link is the legacy bare string. The canonical image link shape introduced by this PR is{ href, blank? }, so object-linked image blocks are not relativized and keep pointing at the old WordPress domain.Mirror the shape handling used by
rewritePortableTextUrls()and preserve theblankflag when rewriting an object link:case "image": { // asset.url stays absolute (media pass), only the click-through link let href: string | null = null; if (typeof block.link === "string") { href = block.link; } else if (block.link && typeof block.link === "object" && typeof (block.link as { href?: unknown }).href === "string") { href = (block.link as { href: string }).href; } if (href) { const relativized = relativizeUrl(href, sourceHost); if (relativized) { if (typeof block.link === "string") { block.link = relativized; } else { (block.link as { href: string }).href = relativized; } } } break; }Please also add an object-link case to
packages/core/tests/unit/import/relativize-links.test.ts(e.g.link: { href: "${SITE}/gallery/", blank: true }→link: { href: "/gallery/", blank: true }).
There was a problem hiding this comment.
Re-review of #3167 — this is the right, approved change for #2497 / Discussion #2741. Since the previous review, the remaining functional blocker has been fixed and the two earlier inline nits have been addressed.
I checked:
packages/core/src/content/converters/image-link.tsand the two converters — the newnormalizeImageLinkhelper correctly upgrades legacy string links and drops half-populated{ blank: true }objects on save.packages/core/src/components/Image.astro— now wraps images in a sanitized<a>whenlink.hrefis set, ignorestarget="_blank"for same-page anchors (#section), and handles the legacy bare-string shape.packages/admin/src/components/PortableTextEditor.tsx— the toolbar and bubble menu detect image selections, pre-populate from the image link, preserve theblankflag when only the URL changes, and the bubble-menushouldShowguard now correctly lets imageNodeSelections through.packages/admin/src/components/editor/ImageDetailPanel.tsx— the link URL input and "Open in new tab" checkbox are reset via thenodeKeyeffect when the selected node changes.packages/core/src/import/utils.ts—relativizeContentLinks()now handles both the legacy bare-string and the canonical{ href, blank? }object shape, preservingblankwhen rewriting.- Tests added/updated for converter round-trips, legacy-string upgrades, half-populated link drops, render output, import relativization, and toolbar/bubble/panel regression cases.
All user-facing strings are Lingui-wrapped, the changeset is clear, and there are no new queries on logged-out routes. No remaining issues found.
ascorbic
left a comment
There was a problem hiding this comment.
Reviewed the current head after merging main and resolving the image media/link converter conflicts. The image-selection controls, legacy link normalization, renderer behavior, WordPress link relativization, and shared Portable Text type are covered by focused regressions. Root build, package typecheck, lint, and targeted admin/core tests pass.
What does this PR do?
Supersedes #704 (@drudge's implementation, re-ported onto current
mainper the handoff in that PR). Approved in Discussion #2741.Adds an optional
link: { href: string; blank?: boolean }to Portable Text image blocks, round-tripped through the PT ↔ ProseMirror converters.ImageDetailPanelgains a "Link URL" input and an "Open in new tab" checkbox as a secondary surface.Image.astrowraps the image in<a>whenlink.hrefis set, viasanitizeHref();blankaddstarget="_blank" rel="noopener noreferrer".href) are dropped on save so{ blank: true }never leaks into Portable Text.Relative to #704: re-ported onto current
main(the original no longer applied cleanly —identityAttrs/attrsWithPortableTextKey, imagealignmentand Kumo imports had landed on the same lines); new UI strings are wrapped with Lingui per the review; and the case flagged on #704 where editing an image link's URL from the toolbar/bubble menu dropped an existingblank: trueis fixed, with tests.Closes #2497
Type of change
Checklist
pnpm typecheckpassespnpm lintpassespnpm testpasses (or targeted tests for my change)pnpm formathas been runmessages.pochanges included.AI-generated code disclosure
Screenshots / test output
Targeted tests run locally:
packages/coreconverter suites (45 passing) andpackages/adminbrowser tests forImageDetailPanel, toolbar, bubble menu, image selection and alignment (169 passing).