Repository navigation
Fix saving Image Cropper and File Upload editors inside a block - #103
Merged
PerplexDaniel merged 1 commit intoJul 27, 2026
Conversation
…ad) inside a block The inner ContentPropertyData was created without a ContentKey or PropertyTypeKey, so property editors that store files against the content key (Image Cropper, MediaPicker3, File Upload) received Guid.Empty and threw "Invalid content key" on save. Set both keys before calling the inner FromEditor, mirroring Umbraco core's BlockValuePropertyValueEditorBase. Fixes PerplexDigital#102
Member
|
Thanks @talhamalik4025 for your detailed issue report and the PR. I'm very busy today but will have a look early next week. The code looks good but I also need to verify it works as intended. |
nadrummond
added a commit
to n3oltd/umbraco-extensions
that referenced
this pull request
Jul 26, 2026
The workaround set ContentKey to data.Key - the block item's own key - while its
comment claimed it did "exactly as Umbraco's own block editor does". It does not.
Umbraco threads the owning document's key down:
// BlockValuePropertyValueEditorBase.cs:224 (release/17.6)
ContentKey = contentKey,
reaching MapBlockItemDataFromEditor from BlockEditorPropertyValueEditor as
editorValue.ContentKey, which ContentEditingServiceBase populates from
content.Key. The upstream fix for this same defect,
PerplexDigital/Perplex.ContentBlocks#103, uses editorValue.ContentKey too.
Two consequences of the divergence:
- UniqueMediaPathScheme derives the media folder by hashing
Combine(itemGuid, propertyGuid), so files uploaded through a block landed under
a path derived from the block key. Removing this workaround when the upstream
fix ships would silently move that basis to the document key - so the "remove
this folder once the fix ships" instruction was not the no-op it promised.
- data.Key comes from the posted BlockItemData, whose Key is a plain property
with no lazy assignment, so it can be Guid.Empty - the very "Invalid content
key" throw being worked around. editorValue.ContentKey cannot be: IContent.Key
mints a value on read when unset.
Now behaviour-equivalent to the upstream fix, so deleting the workaround later
does not move the media path basis. Object initializer replaced with assignments
per house convention.
Two blocks of the same element type on one page now share a media directory,
because the basis no longer includes the block key. Same-named uploads in two
such blocks overwrite rather than sitting side by side. That is what Umbraco core
does for Block List and Block Grid and what the upstream fix does, and matching
it is the point of the change. Existing files are unaffected: the cropper editor
returns the stored value unchanged when no new file is posted, so a path is never
recomputed for content already saved.
re n3oltd/work#729
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASqLpsxy1jkRfcpkrrXYio
nadrummond
added a commit
to n3oltd/umbraco-extensions
that referenced
this pull request
Jul 26, 2026
…ocks 4.0.0) (#906) * Migrate N3O.Umbraco.Blocks to Umbraco 17 / .NET 10 (Perplex.ContentBlocks 3.0.1 -> 4.0.0) - Blocks / Blocks.Perplex / Blocks.Preview / Blocks.StaticAssets targeted to net10; Perplex.ContentBlocks 3.0.1 -> 4.0.0 (v4 API: ElementTypeKey, BlockNameTemplate; per-block NestedContent data-type creation dropped - v4 has no per-block data type). - Blocks.Preview backoffice UI ported AngularJS -> React/TS (Vite), shipped as RCL static web assets; block-preview uses authFetch for the [Authorize] endpoint. - Perplex v4 "Invalid content key" workaround: Image Cropper / File Upload nested in a block now save correctly. N3OContentBlocksValueEditor / N3OContentBlocksPropertyEditor set ContentKey/PropertyTypeKey and the composer excludes Perplex's own editor. Stopgap for PerplexDigital/Perplex.ContentBlocks#102 (fix PR #103) - remove when it ships. - Include the ContentHelper Perplex-v4 block-content parse fix (BLOCKER-02) so pages with Perplex blocks actually save at runtime on v17. re n3oltd/work#729 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * Update PerplexBlockDefinition.cs Signed-off-by: talhamalik4025 <105341627+talhamalik4025@users.noreply.github.com> * Blocks.Perplex: remove dead per-block data-type-creation remnants in PerplexBlockTypesService Perplex v4 has no per-block data type (only the element type is needed), so v13's per-block data-type creation was already dropped. This removes its now-unused leftovers: the migration-review TODO comment and the _propertyEditors / _configurationEditorJsonSerializer dependencies that only served the removed data-type creation. No behaviour change; removal reason + Perplex source are in the PR description. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * Update ContentHelper.cs Signed-off-by: talhamalik4025 <105341627+talhamalik4025@users.noreply.github.com> * Update BlocksComposer.cs Signed-off-by: talhamalik4025 <105341627+talhamalik4025@users.noreply.github.com> * Blocks.Perplex: remove unused DataTypeKey/DataTypeId from PerplexBlockDefinition Perplex v4's IContentBlockDefinition dropped DataTypeKey/DataTypeId (a block uses only ElementTypeKey). Nothing reads these on PerplexBlockDefinition, so remove them plus the now-unused N3O.Umbraco.Utilities using (IdScope.BlockDataType was its only consumer). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * Blocks: restore FormatBlockData as a v17-compatible extension Ported to Umbraco v17 - operates on BlockItemData.Values (mutating BlockPropertyValue in place) instead of the removed v13 PropertyValues/RawPropertyValues, and fixes the v13 Content Picker duplicate-key crash. Still consumed by client sites' custom block previewers (site-mh OurBlockPreviewer), so it must not be dropped. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * Update block-preview-app.tsx Signed-off-by: talhamalik4025 <105341627+talhamalik4025@users.noreply.github.com> * Blocks: remove explanatory comments from block preview + FormatBlockData Strip the descriptive comments from the block-preview web-component shell, its uui JSX typings and vite config, and the FormatBlockData extension. Comment-only change; no behaviour change. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * Blocks.Preview: point the plugin at the packages that actually exist The plugin referenced @n3o/build and @n3o/backoffice-core. Neither name exists in this repo; the workspace packages are @repo/build-config and @n3oltd/backoffice-core. Before this commit tsc --noEmit reported 48 errors: the extended tsconfig could not be resolved, and the unresolvable mixin import degraded the base class to {}, cascading into TS2339 on attachShadow, consumeContext, observe and every other HTMLElement/UmbElement member. vite build could not load its own config. After it, tsc --noEmit is clean and vite emits the mapped specifier "@n3oltd/backoffice-core". This corrects the source only. The runtime failure - the tracked bundle importing a bare "@n3o/backoffice-core" that no import map declares, so the module never evaluates and the blockEditorCustomView silently falls back to the built-in block view - persists until that stale artefact is regenerated: the package is not yet in the npm workspace, so nothing rebuilds it. Fixed by the following commits, which move it into frontend/ and stop tracking the bundle. The API surface was already correct: UmbAuthFetchMixin, UmbElementMixin and the AuthFetch type are all real exports of @n3oltd/backoffice-core. re n3oltd/work#729 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ASqLpsxy1jkRfcpkrrXYio * Blocks.Preview: move the plugin into the frontend workspace convention The plugin sat at N3O.Umbraco.Blocks.StaticAssets/Extensions/. The literal directory name "frontend" is load-bearing in four independent places, so "Extensions" disconnected the package from all of them at once: - src/package.json workspace globs (frontend/*, */frontend/*, */*/frontend/*) - npm ci never linked it and turbo run build never built it, with no error. - src/.syncpackrc.json, so version policy never applied to it. - Directory.Build.props:9, which gates N3OHasFrontend on Exists('$(MSBuildProjectDirectory)\frontend') - so RestoreFrontendDependencies, BuildFrontendWorkspace and BuildFrontend all skipped this project. - Directory.Build.targets:51, so edits here did not invalidate the build stamp. Moved to frontend/blocks-preview/ and aligned with the Data exemplars: - package name @n3oltd/blocks-preview, matching the @n3oltd/<plugin> convention. - outDir dist with the App_Plugins folder encoded in the entry key, so BuildFrontend's frontend/*/dist/** glob copies it to wwwroot/App_Plugins/N3O.Umbraco.Blocks.Preview/ and re-registers it as Content for the static web assets pipeline. Writing straight into wwwroot bypassed that seam and left turbo.json's "outputs": ["dist/**"] caching nothing. - extends @repo/build-config/tsconfig-react, which already sets jsx: react-jsx, instead of the base config plus a hand-set jsx. - react/react-dom as peerDependencies and @types/react* as devDependencies, per the npm dependency convention in AGENTS.md. src/package-lock.json regenerated with a plain npm install (no omit=optional): the 26 @esbuild/* and 25 @rollup/rollup-* platform optional-dep entries are preserved, and @n3oltd/blocks-preview now resolves as a workspace member. The regeneration also clears both stale @n3oltd/platforms-preview entries - the node_modules link and the packages record - left behind by a package that no longer exists in the tree. Verified: npm ci followed by turbo run build --filter=@n3oltd/blocks-preview builds the package (tsc --noEmit clean) and emits dist/N3O.Umbraco.Blocks.Preview/block-preview.js, which is the path umbraco-package.json already points at. re n3oltd/work#729 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ASqLpsxy1jkRfcpkrrXYio * Blocks.StaticAssets: declare the shared React runtime dependency The project ships a React backoffice bundle but never set N3OReactPlugin, so Directory.Build.targets:2-3 did not import src/build/N3O.Umbraco.ReactPlugin.props and no ProjectReference to N3O.Umbraco.ReactRuntime was added. The published package's only dependency was N3O.Umbraco.Blocks, so a consumer installing N3O.Umbraco.Blocks.StaticAssets got no /App_Plugins/N3O.Umbraco.ReactRuntime/ and therefore no import map: block-preview.js failed on its bare "react", "react-dom/client" and "react/jsx-runtime" imports and the custom view never registered. The props file exists precisely so this "can never be forgotten". StaticWebAssetBasePath and the node_modules DefaultItemExcludes are dropped: Directory.Build.props:3,12 now supply both, since the project has a frontend/ folder. Matches N3O.Umbraco.Data.csproj, which sets N3OReactPlugin and neither of the other two. re n3oltd/work#729 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ASqLpsxy1jkRfcpkrrXYio * Blocks.Preview: stop tracking the generated backoffice bundle block-preview.js and block-preview.js.map were force-added past .gitignore:393-394, whose comment states the rule: generated bundles are emitted into wwwroot/App_Plugins by the BuildFrontend target and only the hand-authored umbraco-package.json manifests stay tracked. They were the only tracked .js under any wwwroot/App_Plugins in the repo. The predicted failure had already happened: the bundle was written once in c330250 and never regenerated, while 23cbca6 and f74f5e6 went on to edit the sources. The shipped artefact was two commits behind its own source - it still contains a comment that HEAD deleted - and, because the package was outside every build mechanism, nothing would ever have refreshed it. With the plugin now in the frontend workspace and N3OReactPlugin set, BuildFrontend regenerates both files from frontend/blocks-preview/dist/ on every build and registers them as static web assets. The manifest stays tracked. re n3oltd/work#729 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ASqLpsxy1jkRfcpkrrXYio * ContentHelper: read composed properties from block elements GetContentPropertiesForBlockListOrGridElement enumerated contentType.PropertyGroups, which is only the element type's own grouped properties. Umbraco exposes the full set as CompositionPropertyTypes: ContentTypeComposition.SelectMany(x => x.CompositionPropertyTypes) .Select(AcquireProperty) .Union(PropertyTypes) and PropertyTypes is itself NoGroupPropertyTypes unioned with the grouped ones, so PropertyGroups is the narrowest of the three. Two kinds of property were therefore missing from the returned ContentProperties, silently and with no error: everything inherited from a composition, and the element type's own ungrouped properties. Consumers affected are every caller of IContentHelper.GetContentProperties - data export, content validation on save, content access control and both Cropper handlers. This is not hypothetical. Across live databases: site-mh-uk-production 136 element types 248 own 285 composed (54%) site-mr-uk-production 100 element types 231 own 186 composed (45%) site-afh-uk-production 146 element types 411 own 179 composed (30%) 12-15 element types per site have no own properties at all and so returned nothing whatsoever. The composed properties are real content: Link contributes linkContent / linkExternalUrl / linkText to 25 element types on afh-uk, and the crowdfunding Goal compositions contribute amount, priceHandles, tags and fundDimension1-3. The defect is in the shared block element parser, so it applies equally to native Block List/Grid (site-mh-uk-production: 40 and 11 property types) and to Perplex, whose branch already routed into the same method. It predates the Perplex v4 work. Effect on export is to populate, not to widen: GetUmbracoProperties builds element columns from CompositionPropertyGroups, so columns for composed grouped properties were already emitted and simply always blank. They now carry values. Composed ungrouped properties are returned here but still have no export column, which is a remaining asymmetry rather than a regression. re n3oltd/work#729 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ASqLpsxy1jkRfcpkrrXYio * ContentHelper: skip block elements that cannot be resolved Three inputs that occur in real data each crashed the parser: - A block whose content is an empty object. Perplex's v3-to-v4 migration writes exactly that for any block whose content array was absent or unparseable (M001_MigrateFromNestedContentToBlockList: "No existing valid content, initialize with an empty object"). {} satisfies `is JObject`, so it reached the element parser and GetBlockElementKey threw InvalidOperationException on an element carrying neither a key nor a legacy udi. - A block whose contentTypeKey is missing, where Guid.Parse received null and threw ArgumentNullException, or whose element type has been deleted, where _contentTypeService.Get returned null and contentType.CompositionPropertyTypes threw NullReferenceException. - A block whose key is present but unparseable, where Guid.Parse threw FormatException without ever considering the legacy udi. All are on the content save path via ContentValidationHandler and on the data export path via ProcessExportHandler, neither of which wraps GetContentProperties in a try, so any one of them took out saving or exporting the whole document. Unresolvable elements are now skipped, matching Perplex's own ContentBlocksValueDeserializer.Refine, which drops blocks whose element type cannot be resolved rather than failing the property. GetBlockElementKey becomes TryGetBlockElementKey, which also means an unparseable key now falls through to the legacy udi instead of throwing. Both call sites drop nulls. re n3oltd/work#729 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ASqLpsxy1jkRfcpkrrXYio * ContentHelper: dispatch Perplex block content by its stored shape The Perplex branch read each block's content only as a v4 Block Editor element and skipped anything else, so a v3 payload - where content is a NestedContent array - contributed nothing at all. Every Perplex property on a site whose ContentBlocks migration has not run returned zero properties from IContentHelper.GetContentProperties, silently, on both the save and the export path. That is the state of the estate today, not a hypothetical: across site-afh-uk-production and site-mr-uk-production every stored ContentBlocks row is version 3 (912 and 305 rows respectively, zero v4). The Perplex path is now a thin adapter. It knows only the envelope - that blocks live under "blocks" and each carries its payload under "content" - and hands the payload to whichever shared element parser matches its shape: the Block List/Grid element parser for the v4 shape, the NestedContent parser for the v3 one. Callers get ContentProperties either way and do not need to know which shape was stored. The discriminator is the presence of contentTypeKey rather than the envelope's version field, so a row whose version was not rewritten still parses by what it actually contains. The NestedContent element parser gets the same guards the Block List/Grid one received in the previous commit, and elements that are not objects are skipped rather than cast. It is reachable again now, and both the empty object Perplex's migration writes for a block with no valid content and a null array entry would otherwise reach it and throw. re n3oltd/work#729 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ASqLpsxy1jkRfcpkrrXYio * Blocks.Perplex: pass the owning content key to nested property editors The workaround set ContentKey to data.Key - the block item's own key - while its comment claimed it did "exactly as Umbraco's own block editor does". It does not. Umbraco threads the owning document's key down: // BlockValuePropertyValueEditorBase.cs:224 (release/17.6) ContentKey = contentKey, reaching MapBlockItemDataFromEditor from BlockEditorPropertyValueEditor as editorValue.ContentKey, which ContentEditingServiceBase populates from content.Key. The upstream fix for this same defect, PerplexDigital/Perplex.ContentBlocks#103, uses editorValue.ContentKey too. Two consequences of the divergence: - UniqueMediaPathScheme derives the media folder by hashing Combine(itemGuid, propertyGuid), so files uploaded through a block landed under a path derived from the block key. Removing this workaround when the upstream fix ships would silently move that basis to the document key - so the "remove this folder once the fix ships" instruction was not the no-op it promised. - data.Key comes from the posted BlockItemData, whose Key is a plain property with no lazy assignment, so it can be Guid.Empty - the very "Invalid content key" throw being worked around. editorValue.ContentKey cannot be: IContent.Key mints a value on read when unset. Now behaviour-equivalent to the upstream fix, so deleting the workaround later does not move the media path basis. Object initializer replaced with assignments per house convention. Two blocks of the same element type on one page now share a media directory, because the basis no longer includes the block key. Same-named uploads in two such blocks overwrite rather than sitting side by side. That is what Umbraco core does for Block List and Block Grid and what the upstream fix does, and matching it is the point of the change. Existing files are unaffected: the cropper editor returns the stored value unchanged when no new file is posted, so a path is never recomputed for content already saved. re n3oltd/work#729 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ASqLpsxy1jkRfcpkrrXYio * Data.PerplexBlocks: stop rewriting content blocks JSON through Newtonsoft Importing a spreadsheet containing a ContentBlocks column silently emptied the property. Two separate faults on the same round trip: - The v4 ContentBlocksValue is annotated for System.Text.Json ([JsonPropertyName], [JsonExtensionData], [JsonIgnore]), and this code serialised it with Newtonsoft, which honours none of them. Newtonsoft emitted CLR names - "Version", "Blocks", "Content" - while Perplex reads the stored value with Umbraco's IJsonSerializer, a SystemTextJsonSerializer configured with PropertyNamingPolicy = CamelCase and PropertyNameCaseInsensitive left at its default of false. Nothing bound, so Deserialize produced Version = 0, Blocks = null and ContentBlocksValueConverter returned ContentBlocks.Empty: every block on the imported page gone, with no error. - Import deserialised into the v4 model at all. The exported cell is the block JSON as it stands on the property, and every stored row in the estate is still v3, where content is a NestedContent array rather than a BlockItemData object. Round-tripping that through a v4 model discards it whichever serializer is used. Import now writes the exported JSON back through SetJson, so nothing is dropped that the model does not represent, for either shape. The cell is validated first - well-formed JSON carrying a "blocks" member - and reported through the ErrorLog the converter already receives, so a hand-edited or truncated cell fails the import loudly instead of persisting a value that Perplex would later read as an empty page. Nothing is lost by skipping the model: Set never ran Refine or ContentBlocksValidator, which live on the deserialize and content-editing paths. Set(ContentBlocksValue) is kept for callers that build a model, and uses IJsonSerializer so what it writes is what Perplex can read. Note the exported cell is not the stored bytes: ContentHelper produces it by parsing the stored string to a JToken and re-serialising with Newtonsoft, which normalises ISO date strings to the server timezone and coerces large or high-precision numbers. That predates this change and is unaffected by it, but the import now persists that normalised text. ContentBlocksPropertyBuilder's constructor gains a parameter. It is resolved from DI everywhere in this repo; a downstream site constructing it directly would need to pass IJsonSerializer. re n3oltd/work#729 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ASqLpsxy1jkRfcpkrrXYio * Blocks.Perplex: give each block its name in the block head BlockNameTemplate returned null, so the title in every collapsed block head rendered empty: pcb-block-head only draws it when the template is set, and pcb-block falls back to an empty string. Perplex v4 introduces BlockNameTemplate as the replacement for the Template property that v1-v3 carried on the per-block NestedContent data type. The v13 code set that to definition.Name, so returning Name restores what editors saw before the upgrade. The data type creation itself is gone because v4 needs only the element type. re n3oltd/work#729 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ASqLpsxy1jkRfcpkrrXYio * Blocks.Perplex: fail loudly when a block content type cannot be created CreateAsync returns Task<Attempt<ContentTypeOperationStatus>> and both results were discarded, so a rejected create - duplicate alias, invalid property type, permissions - left an unsaved IContentType behind and boot carried on. The two failures compound. GetOrCreateContentTypeCompositionAsync returns the unsaved composition, which is then assigned as ContentTypeComposition on the element type, so that create fails too. The site starts cleanly, every block silently lacks its element type, and the first symptom is Perplex declining to render blocks with nothing in the log to explain it. Both attempts are now checked and throw with the operation status, matching GetOrCreateContentTypeContainer directly below, which has always thrown on a failed CreateContainer. re n3oltd/work#729 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ASqLpsxy1jkRfcpkrrXYio * Blocks.Perplex: pin Perplex.ContentBlocks exactly at 4.0.2 N3OContentBlocksValueEditor copies the body of Perplex's own ContentBlocksValueEditor.FromEditor, because Umbraco's BlockValuePropertyValueEditorBase.MapBlockItemDataFromEditor is protected on an abstract class the Perplex editor does not derive from. A copy of someone else's method is only correct against the version it was copied from, and "4.0.0" is a minimum, so any transitive bump could float the base out from under it with no code change and no signal. Pinned to an exact version for as long as the copy exists; remove the brackets when the upstream fix ships and the workaround goes. 4.0.2 rather than 4.0.0 because both patches matter to this estate: 4.0.1 re-adds mandatory preset blocks that are missing from existing content, which is exactly the state migrated v3 content arrives in, and 4.0.2 hides isHidden categories in the add-block modal. re n3oltd/work#729 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ASqLpsxy1jkRfcpkrrXYio * Blocks: align Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation with Cms N3O.Umbraco.Blocks pinned 10.0.7 while N3O.Umbraco.Cms pinned 10.0.8. The two sit in the same graph, so NuGet unifies to the higher version anyway, and the csproj carries NoWarn NU1605 so the downgrade warning that would otherwise surface the split never appears. re n3oltd/work#729 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ASqLpsxy1jkRfcpkrrXYio * Blocks.Perplex: mark the workaround with the TODO the repo greps for The removal note read "Reported upstream - remove this folder ... once the fix ships". This repo's idiom for work that is deliberately parked against a future event is a bare "// TODO Remove", as in Composer.cs, ContentCacheExtensions.cs and ContentLocatorExtensions.cs. A developer bumping Perplex.ContentBlocks greps TODO, not "Reported upstream". Also names the exact version pin as a third thing to undo, so the whole workaround comes out together. re n3oltd/work#729 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ASqLpsxy1jkRfcpkrrXYio * Blocks.Preview: use the typed workspace context and build the URL properly The document workspace context was consumed as `unknown` and cast to a hand-written structural type. Both members it names are public and typed on the context already, so the cast bought nothing and cost type-checking of the whole callback - and it was wrong: it declared unique as Observable<string | undefined> where UmbEntityUnique is string | null. Dropping the annotation and the cast type-checks clean once #nodeKey admits null, and removes the two inline import() type expressions, which appear nowhere else in this repo. The query string was four uninterpolated values concatenated by hand, with a stray slash before the "?" and a dead `?? ''` on a field initialised to ''. Now built with URLSearchParams. #contentKey was read but never guarded, so an empty contentUdi was posted before the block entry context resolved. Server-side UdiParser.Parse("") throws, the controller turns that into an error banner and returns 200, and the client rendered it as a successful preview. Both keys are now guarded and passed in as narrowed parameters. #documentTypeKey held context.contentElementTypeKey - the block's element type, not a document type - so it is renamed. The query parameter keeps its wire name. Also: Accept: application/json, as every exemplar sends; replaceAll over a regex; the debounce hoisted to a named constant; and the redundant undefined check before clearTimeout, which is a defined no-op, removed. re n3oltd/work#729 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ASqLpsxy1jkRfcpkrrXYio * Blocks.Preview: reload when the contexts a request depends on resolve Only connectedCallback and authFetchChanged scheduled a load. The block entry and block manager context callbacks, and the observers for contentKey and contentElementTypeKey, assigned their field and stopped there. Contexts resolve asynchronously and in no guaranteed order. UMB_AUTH_CONTEXT is app-level and consumed in the mixin constructor, so it typically resolves first; authFetchChanged then fires a load that returns immediately because the block manager and element type key are not set yet, and nothing schedules another. The element sits on "Loading preview..." forever. It works today only because the ordering usually happens to favour it. Every observer that feeds a request parameter now reschedules, which is what the Data exemplars do by re-issuing their render from each observer. #scheduleReload already clears the pending timer, so a burst of context resolutions collapses into one request. re n3oltd/work#729 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ASqLpsxy1jkRfcpkrrXYio * Blocks.Preview: make preview failures visible and recoverable A failed request was swallowed by `if (!response.ok) return;`, and a network or malformed-body failure was an unhandled rejection inside the reload timer. Either way the element stayed on "Loading preview..." with nothing in the UI to say why. Worse, it never recovered. #loaded only became true on success and #onDataChanged was gated on it, so after one failed request every subsequent edit to the block was swallowed by the guard - the block was wedged until the editor was reloaded. That is two concerns fused into one flag: "have we ever loaded", used to suppress the debounce during initial property assignment, and "what should we show". They are now separate. A PreviewState discriminated union in types.ts models loading, ready and error, so there is somewhere for a failure to be rendered, and #onDataChanged always reschedules. Failures also surface through UMB_NOTIFICATION_CONTEXT, as the AngularJS version did via umbRequestHelper.resourcePromise's "Failed getting block preview markup", and as the Data exemplars do. The response is validated rather than asserted: `as string` over json()'s any put an HTML challenge page or a ProblemDetails object straight into the DOM as [object Object]. Requests are also cancellable now. Reordering a block grid detaches and reattaches each element, which previously left orphaned POSTs whose continuations mutated a detached instance, and two edits 500ms apart could resolve out of order and leave the older preview on screen. Each load aborts the one before it, disconnectedCallback aborts any in flight, and an aborted request is not reported as an error. re n3oltd/work#729 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ASqLpsxy1jkRfcpkrrXYio * Blocks.Preview: render the preview in an iframe again The AngularJS view wrote the response into an iframe with document.write. The port replaced that with dangerouslySetInnerHTML into the backoffice's own shadow root, which is not equivalent: - Markup assigned via innerHTML never executes its <script> elements. That is the HTML specification, not a bug. Any block whose template needs JavaScript to render - carousels, maps, accordions, tabs - showed inert and looked broken to an editor. - The endpoint returns a whole rendered document. Fragment parsing discards its html, head and body wrappers, so document-level selectors in the site's own stylesheet stop matching and the preview no longer resembles the page. - The markup ran in the backoffice document rather than a separate one. srcDoc restores all three: scripts run, the site stylesheet applies to a real document, and the preview is a document of its own. The frame stays same-origin, so contentDocument.body can still be measured - by a ResizeObserver rather than the original's three 100ms polls, so the frame also tracks content that changes height after load. The 0.9 zoom-out that made more of a block visible is kept, but applied properly. transform does not affect layout, so previously every block reserved its full unscaled height and left roughly a tenth of it empty underneath. The surface now takes the scaled height and the frame is widened to compensate. re n3oltd/work#729 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ASqLpsxy1jkRfcpkrrXYio --------- Signed-off-by: talhamalik4025 <105341627+talhamalik4025@users.noreply.github.com> Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Co-authored-by: Noor Drummond <noor@ankabut.com>
Member
|
@talhamalik4025 Great work, thank you! Your fix works well. I'll release this in v4.0.3 soon (today). |
Contributor
Author
|
@PerplexDaniel Great. Thanks |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #102.
If you put an Umbraco Image Cropper or File Upload editor on a block's element type, saving the page fails with "Invalid content key". In
ContentBlocksValueEditor.FromEditorthe innerContentPropertyDatais created without aContentKeyorPropertyTypeKey, so both default toGuid.Empty.ImageCropperPropertyValueEditorandFileUploadPropertyValueEditorboth explicitly throw"Invalid content key"in that case, and need the key to build the media storage path. Editors that only store a reference (e.g. Media Picker v3) ignore the two keys, which is why everything else saves fine.This sets both keys before calling the inner
FromEditor, taking the content key from the incomingeditorValue– the same approach Umbraco core takes inBlockValuePropertyValueEditorBase.MapBlockItemDataFromEditor(umbraco/Umbraco-CMS#18976).Verified on Umbraco 17: with this change the Image Cropper saves correctly inside a block (the file is stored against the content), and reference-based editors like Media Picker are unaffected (Media Picker stores a media-library reference, not a file on the content). File Upload uses the same content-key mechanism as the Image Cropper – the identical
"Invalid content key"guard – so it's covered by the same fix.