Move the empty editable block-property affordance out of per-view template
boilerplate into the block render helpers. GetBlock{List,Grid}HtmlAsync and the
single-block GetBlockHtmlAsync now emit an annotated empty container
(<div class="umb-block-{list,grid,single}" data-umb-block-property="alias">)
from their alias-bearing overloads when the property is editable-in-visual-editor
and the visual editor is active, via a shared BlockEmptyState helper. The
blocklist/blockgrid/embedded-blockgrid default views revert to their plain form
and the ViewData alias plumbing is removed. The guest gains a single-block
empty-container branch; the element resolves the single-block schema alias so the
add produces a correctly shaped value. Works automatically for any template using
the standard helper, including custom ones.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Mirror the sample-site empty-state handling into the embedded BlockGrid/default.cshtml
that ships to new installs, so empty editable block grids are annotated and offer
an add-content affordance in the visual editor. Gated on preview/visual-editor mode,
so normal front-end rendering of empty grids is unchanged.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Replace the non-idiomatic global:: qualification with plain unqualified type names.
The sample site's _ViewImports.cshtml already imports Umbraco.Extensions and
Umbraco.Cms.Core.Models.PublishedContent, so BlockGridTemplateExtensions /
BlockListTemplateExtensions / VisualEditorPropertyTracker resolve directly — and
without a leading 'Umbraco.' the UmbracoHelper property no longer shadows the namespace.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
UmbracoViewPage exposes an 'Umbraco' property (UmbracoHelper) that shadows the
'Umbraco' root namespace inside Razor code blocks, so 'Umbraco.Extensions...' and
'Umbraco.Cms...' bound to the helper and failed to compile at render time. Force
namespace resolution with global:: in both block partials (the block-list one had
the same latent error since the tidy-up round but was never rendered empty).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Home.cshtml rendered bodyText via the model-only GetBlockGridHtmlAsync overload,
which can't flow the property alias, so an empty grid there wouldn't annotate for
the visual editor. Align it with the other sample templates (Blogpost/ContentPage/
Product) which already pass (Model, "bodyText").
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The guest runs in the preview iframe and is bundled standalone by esbuild, not via
the backoffice import map, so morphdom is imported directly from node_modules.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The server's PropertyTypeAppearance viewmodel exposes EditableInVisualEditor but
OpenApi.json was stale (only labelOnTop), so regenerating the server API client
dropped the property and broke the property-type data sources that consume it.
Add it to the schema so the generated client is consistent with the server.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Add SA1600-compliant XML documentation to VisualEditorControllerBase (class summary)
and RenderVisualEditorController (constructor + action). Move [ApiVersion("1.0")] from
the abstract base to the concrete controller, matching the pattern used by
CultureControllerBase/AllCultureController and DataTypeControllerBase/CreateDataTypeController.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Exposes IVisualEditorRenderService via POST /umbraco/management/api/v1/visual-editor/render,
authorized for back-office users, as part of the partial re-render (Phase 3) implementation.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
- Add <param> and <returns> XML doc tags to IVisualEditorContentFactory.CreateWithOverridesAsync (SA1611/SA1615)
- Refactor override loop: resolve property+editor once via ResolveEditorAsync; continue on failure so unresolvable aliases leave the base node value untouched instead of silently blanking with null
- Merge variant PropertyData instead of replacing the whole array: strip only the matching (culture, segment) entry and append the new override entry, preserving sibling cultures/segments
- Add integration test: CreateWithOverrides_Merges_Variant_Override_Preserving_Other_Cultures (confirmed FAIL before fix, PASS after)
- Add integration test: CreateWithOverrides_Returns_Null_For_Unknown_Document_Key
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Introduces IVisualEditorContentFactory (public contract in Umbraco.Core) and its
implementation VisualEditorContentFactory (internal in Umbraco.PublishedCache.HybridCache).
The factory resolves a document's draft IContent via IContentService, builds a
ContentCacheNode via ICacheNodeFactory, overlays caller-supplied unsaved property values
(converted from editor format to source format via FromEditor), then converts the mutated
node to a preview IPublishedContent via IPublishedContentFactory — matching the approach
proven by the throwaway spike. Registered as singleton in AddUmbracoHybridCache().
Integration test covers TextBox, RichText, and BlockList overrides end-to-end.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Ensure requests to fetch ancestors after retrieving search results are batched to avoid a single query exceeding the maximum URL length.
* Guard against undefined ancestor entries from a failed batch
batchTryExecute resolves each chunk via tryExecute, which never rejects, so
a per-chunk failure comes back as a fulfilled result carrying an error and
leaves an undefined hole in the amalgamated data without surfacing an error.
Detect that before mapping and return an explicit error instead of throwing.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Assert ancestor id uniqueness and silence direct-api lint rule
Strengthen the batching tests to assert every search-result id is requested
exactly once (Set size), not just that the total count matches. Add the
no-direct-api-import disable on the controller's api callback, matching the
existing url data sources, since the call is wrapped by the controller.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Addessed Codescene warnings.
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Prevent empty domain cache during concurrent initialization.
* Addressed code review comments and added further comment to the code.
* Use Lock object.
* perf(tree): coalesce concurrent identical tree data requests
The tree data request manager hit the network on every call, so multiple
concurrent consumers (sidebar tree, breadcrumb structure, pickers) each
fetched the same data independently — e.g. three identical tree/document/root
requests per document-workspace load.
Apply the existing UmbManagementApiInFlightRequestCache (already used by the
item and detail request managers) to the tree request manager via a shared
static cache, coalescing concurrent identical root/children/ancestors/siblings
calls into a single in-flight request, cleared on settle (in-flight only, so
no stale-cache risk). The document tree opts in; other trees are unchanged
until they pass a cache.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* test(tree): cover request coalescing; address review feedback
- Add focused tests: concurrent identical root requests share one call,
the in-flight entry is cleared on settle, and no cache means no coalescing.
- Build the cache key lazily (only when a cache is wired) so non-opted-in
trees keep the original lightweight path.
- Constrain the #coalesce generic to drop the cast on cache.set.
- Document the new inflightRequestCache arg; trim the comment to one line.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Tolerate invalid data type configuration when getting the editor value storage type.
* Add logging in case of error.
* Resolve warning.
* Removed exception from warning (it's not useful).
* Log an error instead of a warning.
* Menu Structure: Guard against use-after-destroy in async structure request
When navigating to a trashed item, the IS_NOT_TRASHED condition initially
permits the standard menu structure context, which is then destroyed once the
workspace confirms the item is trashed. The in-flight async #requestStructure()
could resume after destruction and call setValue() on a completed subject,
throwing "_subject is undefined".
Guard the state mutations with the framework's existing _host-cleared-on-destroy
signal, and handle the previously fire-and-forget #requestStructure() promises so
a teardown mid-request is silently abandoned rather than surfacing as an uncaught
rejection. Applied to both the variant and non-variant menu structure base
contexts.
* Menu Structure: Make #requestStructure non-throwing instead of catching at call sites
Per PR review feedback: replace the blanket .catch(() => {}) wrappers with
early returns inside #requestStructure(). The _host guard already prevents
post-destroy state mutation; the throws only fire for can't-happen missing
observable states and were producing unhandled rejections with no caller
able to act on them.
* Added console warning, if the host is still available
* Block Grid: Guard validator against torn-down manager on navigation
The form-control mixin's updated() hook runs validators when the element
re-renders during teardown. If navigation has already disposed _manager,
checkBlockTypeConfigurationValidity would throw "Cannot read properties
of undefined (reading 'getContentTypeKeyOfContentKey')".
Early-return as valid when the manager is gone and use optional chaining
on the per-entry lookup as a safety net.
* Removed optional chaining of `_manager`
As `_manager` has already been checked.
* Reverting the `_manager` optional chaining
As TypeScript compiler doesn't like it, (inside the `filter` callback).
* Update uploaded media file name to a friendly name.
* Correct test description for acronym handling.
The case JUST-A-FILE.jpg verifies all-uppercase words are preserved
as acronyms, not that lowercase words get lowercased.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* Match server-side StripFileExtension semantics in toFriendlyName.
The TypeScript helper previously delegated to getFileExtension, which
diverges from the C# StripFileExtension on two edge cases:
- a trailing dot ("file.") is stripped by the server but not the client
- an "extension" containing whitespace is preserved by the server but
stripped by the client
Inlined a stripFileExtension helper that mirrors the C# rules exactly,
making the "keep in sync" cross-reference accurate. Added tests for both
divergent cases and replaced the contrived leading/trailing whitespace
test with a realistic interior-whitespace case.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* Add parity test for trailing-whitespace extension span.
Restores the ' spaced-name.jpg ' case as a parity test against
StripFileExtension's "extension containing whitespace is preserved"
rule. Output is 'Spaced Name.Jpg' (Jpg title-cased, matching the
server's TextInfo.ToTitleCase behaviour on the now-unstripped extension).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* Handle getContext rejection in ensureMediaNameFromFile.
getContext rejects on timeout when the dataset context never resolves;
callers used void ensureMediaNameFromFile(...) so an unhandled rejection
would bubble. Catch the rejection and treat it as an absent context.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
* Creating notification objects and status
* Adjusting service and tracker to support cancelable notifications
* Adding Operation Status Results to base controller.
* Adding notification support to the delete controller.
* Integration tests
* Changes in accordance to CR
* Changes in accordance to code review
* Fixed further use of obsolete methods in tests.
* Added comment explaining why messages on create or update cancellation are suppressed.
---------
Co-authored-by: Andy Butland <abutland73@gmail.com>
* Added constant setting for element folder permission
* Added api helper for element folder
* Added api helper for user group with element folder permission
* Added ui helper for element folder permission in user group
* Added tests for element folder permission
* Added locator for restore element
* Added api helper for Combined element + element folder permission methods
* Added more tests for restore element folder
* Make tests run in the pipeline
* Fixed comments
* Reverted npm command
* Updated createEmptyElementType
* Updated tests due to test helper changes
* Added ui helper for not applicable message for element type
* Added tests for showing message for non-applicable Element Type settings
* Added tests for preventing disabling isElement when elements of that type exist
* Make tests run in the pipeline
* Fixed comments
* Update tests/Umbraco.Tests.AcceptanceTest/tests/DefaultConfig/Settings/DocumentType/DocumentTypeSettingsTab.spec.ts
Co-authored-by: Andreas Zerbst <73799582+andr317c@users.noreply.github.com>
* Reverted npm command
---------
Co-authored-by: Andreas Zerbst <73799582+andr317c@users.noreply.github.com>
* Adds conditions to Document Recycle Bin
that the user must have "Read" permission.
* Directly imports Media Recycle Bin condition
this will remove an extra fetch request.
* Add SonarCloud CI workflow
Adds a manual-dispatch GitHub Actions workflow for SonarQube Cloud
analysis (build, unit test coverage, scan). Moves file_header_template
and SA1636/SA1633 suppression from .editorconfig comments and
.globalconfig into the active .editorconfig .NET language conventions
section, removing the duplicated suppression from .globalconfig.
* Remove branch filter from pull_request trigger in SonarCloud workflow
Runs analysis on all PRs regardless of target branch.
* Adjust sonarcloud gh action based on feedback
* Add .sonarqube to .gitignore
* Attempt to split build and analysis in order to be able to run in PRs from forks
* Adjust SonarCloud workflows
* Rename SonarCloud workflows to reflect their actual purpose
* Remove sonar.coverage.exclusions
* Include .github in sonar analysis
* Include build directory in sonar analysis
* Apply sonarcloud workflow fixes from test branch
* Remove setup-dotnet step from upload workflow
* Use default branch from context instead of hardcoded main in analysis workflow
* Update checkout action to v6 in upload workflow
* Add actions: read permission to upload workflow
* Enable SCM integration in upload workflow
* Improve cohost polyfill
* Apply suggestions from code review
Co-authored-by: Andy Butland <abutland73@gmail.com>
* Move <target/> part of the polyfill to targets file.
---------
Co-authored-by: Andy Butland <abutland73@gmail.com>
* Improve cohost polyfill
* Apply suggestions from code review
Co-authored-by: Andy Butland <abutland73@gmail.com>
* Move <target/> part of the polyfill to targets file.
---------
Co-authored-by: Andy Butland <abutland73@gmail.com>
* Added tests
* Cleaned up
* Updated command
* Fixes based on comments
* Split tests
* Updated helpers
* Fixed constant helper after merge
* Use correct helper
* Added constant for element search
* Added ui helper for element backoffice search
* Added tests for element backoffice search
* Updated tests for finding element by name
* Apply suggestion from @andr317c
Co-authored-by: Andreas Zerbst <73799582+andr317c@users.noreply.github.com>
* Cleaned up
* Reverted npm command
* Fixed npm command
---------
Co-authored-by: Andreas Zerbst <andr317c@live.dk>
Co-authored-by: Andreas Zerbst <73799582+andr317c@users.noreply.github.com>
* Backoffice: Strip inherited class comments from TypeDoc API docs
TypeDoc copies the nearest documented ancestor's class comment onto every
undocumented subclass, which meant every UmbLitElement descendant on
apidocs.umbraco.com showed "The base class for all Umbraco LitElement
elements." as its own description. This plugin clears class-level
comments whose sourcePath doesn't match the reflection's own file, so
classes with no JSDoc render blank instead of borrowing the base's text.
Inherited member comments (methods, properties) are left alone.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* Backoffice: Address review comments on TypeDoc strip-inherited plugin
Drop the misleading "strip trailing line/column" sentence — nothing actually
strips, and a future TypeDoc release that appends positions to sourcePath
would now self-document its breakage instead of being hidden by a comment.
Document the sources[0]-only limitation around declaration merging in the
docblock so the constraint is visible to future maintainers.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
* perf(core): parallelize independent boot API requests
UmbServerConnection.connect() awaited server status and configuration
sequentially even though they are independent reads; run them with
Promise.allSettled so both errors surface (the app cannot function
without either) while saving a round-trip.
During app startup, public (login) extension registration was awaited
before the auth flow; kick it off in parallel and await it only before
routing, where the login screen actually needs it.
Each serialized call costs a full management-API round-trip, which is
negligible locally but ~150 ms each on high-latency (e.g. Cloud) hosts.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor(core): only mark connection connected once both calls succeed
Move isConnected.setValue(true) out of #setStatus() into connect() after
the allSettled check, so the observable never reflects a partially
established connection when configuration fails but status succeeded.
Addresses review feedback on the parallelized connect().
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat: removes @hey-api/openapi-ts from the login project
this is an ongoing project to be able to finally merge 'login' into 'client'
* docs(login): update CLAUDE.md to reflect removal of @hey-api/openapi-ts
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Potential fix for pull request finding
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
* Entity refs render readonly when their workspace URL can't be resolved.
Also fixes name on remove dialog.
* Apply read-only on the picked content ref only in the non-routable link picker
* Address PR feedback: simplify document item resolver guard in the link picker, document the implicit uui-card-media disabled dependency in input-media, and cover the disabled card state with a test.
* Drop out of date comments.
* Simplify updates.
---------
Co-authored-by: leekelleher <leekelleher@gmail.com>
* Render $index in block detail overlay label.
* Cache $index, resolve append sentinel, and cover with unit tests.
* refactor(block): use pipeline for index deduplication and clean up stale observer
* Rename function to remove the unnecessary umb prefix.
---------
Co-authored-by: leekelleher <leekelleher@gmail.com>
* Show the edit permissions for document type button only for users with settings access.
* Fix translation for message (the "Permissions" tab is not called "Structure").
* Addressed code review feedback.
* Suppress CS0618 obsolete API warnings in Umbraco.Examine.Lucene
Each obsolete API in this project cannot be migrated to its
non-obsolete replacement without either a breaking public API
change or a change in runtime behaviour:
- LuceneIndex.CommitCount: obsolete with no replacement; retained
in diagnostics metadata to preserve existing output
- IHostingEnvironment.MapPathContentRoot: the IHostEnvironment
extension replacement resolves a different environment
abstraction
- FileSystemDirectoryFactory base constructor: the non-obsolete
overload alters Lucene directory configuration behaviour
Each warning is suppressed locally with an explanatory comment
rather than changed, preserving existing behaviour.
Fixes#15015
* Tightened up comments. Added obsoletion version on unversioned attributes.
Removed warning supressions and fixed constructors.
---------
Co-authored-by: Andy Butland <abutland73@gmail.com>
`core/manifests.ts` already imports and spreads `core/search/manifests.ts`
into its aggregate (line 23 + 58), so importing `searchManifests`
separately in `.storybook/preview.js` and spreading it next to
`coreManifests` registered the same manifests twice. Remove the redundant
import and spread.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
PR #22957 deleted every package's `manifests.ts` and consolidated the
exports into `umbraco-package.ts`, but `.storybook/preview.js` still
imported from the old paths. The result was a Vite resolve error during
`npm run build-storybook` (first failure: "Could not resolve
../src/packages/block/manifests from .storybook/preview.js").
37 import paths swapped from `…/<pkg>/manifests` to
`…/<pkg>/umbraco-package`. The two packages that still expose their
manifests via a standalone `manifests.ts` — `core` and `core/search` —
are left untouched.
Verified by `npm run build-storybook` — succeeds.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
PR #22995 added `input-tiptap.stories.ts` with an import from
`'../../manifests.js'`, but PR #22957 (already on release/17.5.0) had
deleted that file and moved the `manifests` array into
`umbraco-package.ts`. The merge into release/17.5.0 didn't catch the dead
import, so Storybook 404s on the story load.
Point the import at the new home — `manifests` is still exported by name,
so this is a one-line path fix.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Display variant node name on sort children dialog.
* Preserve user sort order when patching variant names on culture change
Patch names in-place on the existing _tableItems rather than rebuilding
from _children, so a user's drag-sorted or column-ordered arrangement is
not silently reverted if the app culture changes while the modal is open.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Refactor to reduce cyclomatic complexity of #resolveName method.
* Resolve sort dialog variant names and icons via item data resolvers
Replace the inlined variant-name logic in the content sort dialog with the
shared UmbItemDataResolver abstraction, and add UmbMediaItemDataResolver so
media items resolve their active-culture name and icon the same way documents
do. Each content sort entity action now supplies its resolver through manifest
meta, flowing into the modal via a new content-specific modal data type and a
base-action _getModalData() hook. This also removes the previously hard-coded
document icon in the dialog.
* Disable load more when page of items is being retrieved.
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: leekelleher <leekelleher@gmail.com>
* Fix migration of embedded block data when blocks are direct siblings in the 13 RTE source code.
* Apply suggestions from code review to update comments.
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
* Address review: keep RteBlockHelper in original namespace; tidy docs and comment
- Move RteBlockHelper back to Umbraco.Cms.Infrastructure.Migrations.Upgrade.V_15_0_0.LocalLinks
to avoid a binary breaking change within the obsolete window (scheduled removal in v18).
Kept as its own file rather than reverting it into LocalLinkRteProcessor.cs.
- Add a <remarks> note on ConvertBlockUdisToKeys explaining that blocks with malformed UDIs
are dropped rather than preserved.
- Replace the opaque "fix recursive hiccup" comment in LocalLinkRteProcessor with one that
describes what the line actually does.
- Move RteBlockHelperTests back to mirror the production namespace.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Fix migration of embedded block data when blocks are direct siblings in the 13 RTE source code.
* Apply suggestions from code review to update comments.
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
* Address review: keep RteBlockHelper in original namespace; tidy docs and comment
- Move RteBlockHelper back to Umbraco.Cms.Infrastructure.Migrations.Upgrade.V_15_0_0.LocalLinks
to avoid a binary breaking change within the obsolete window (scheduled removal in v18).
Kept as its own file rather than reverting it into LocalLinkRteProcessor.cs.
- Add a <remarks> note on ConvertBlockUdisToKeys explaining that blocks with malformed UDIs
are dropped rather than preserved.
- Replace the opaque "fix recursive hiccup" comment in LocalLinkRteProcessor with one that
describes what the line actually does.
- Move RteBlockHelperTests back to mirror the production namespace.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Batch WHERE IN queries to avoid SQL Server 2100-parameter limit and add memory files.
* Drop past-incident references from SQL parameter-limit docs
The memory files should describe the current rule and safe patterns;
specific historical bugs belong in commit history, not CLAUDE.md.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Update comments from code review
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
* Addressed memory file feedback.
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
* Tiptap: Load enabled extensions in parallel and inline manifest APIs
Replace the for…of/await loop in umb-input-tiptap's #loadExtensions with
Promise.all over .map, so all enabled Tiptap extension APIs are fetched
in parallel. Configured-extension order in _extensions is preserved.
Inline the first-party Tiptap manifest API references: every
`api: () => import('./X.tiptap-api.js')` and the equivalent toolbar /
statusbar / kind references now use a static top-of-file import and
`api: ClassName`. The dynamic `await import('rich-text-essentials.tiptap-api.js')`
fallback in input-tiptap.element.ts is inlined for the same reason.
External (plugin-supplied) Tiptap extensions and the lazy modal/toolbar
UI element imports are unchanged.
Why: on Umbraco Cloud, opening a document workspace with a rich text
editor takes ~16 s uncached, of which ~14.6 s is a single serial
waterfall — 31 extension APIs fetched one after the other from a
for…of await loop, ~170 ms RTT stacked. Replacing the loop with
Promise.all collapses that to roughly one round-trip; eagerly bundling
the first-party manifests removes the dynamic chunk explosion that made
the waterfall so long in the first place. The toolbar APIs (~20 of them)
already load in a sub-100 ms parallel burst against the same server,
confirming HTTP/2 multiplexing handles bulk parallel requests fine.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Tiptap: Inline element references for toolbar/statusbar/modal/clipboard manifests
Extends the manifest-inlining pass to the remaining `element: () => import(...)`
and runtime API loader sites in the Tiptap package — toolbar/menu/action-button
kinds, the table & character-map & anchor modals, the colour-picker button, the
property-editor configuration UIs, both clipboard translators, the style-menu
kind, and the default toolbar API fallback in tiptap-toolbar.element.ts.
Result on the same Cloud test site (uncached, 17.5-rc):
Tiptap chunk count: 71 → 4
Total tiptap bytes: ~3.2 MB → ~3.1 MB (essentially unchanged)
Phase 5 of the load — the serial extension chain — collapses to a single
consolidated chunk fetch.
`input-tiptap.element.ts` and `property-editor-ui-tiptap.element.ts` are
intentionally not inlined into anything else: `<umb-input-tiptap>` is a public
element usable standalone (custom dashboards, workspace views), and the
property-editor shell loads via the property-editor UI loader. They remain
exported as their own modules.
CLAUDE.md updated to document the new convention for first-party Tiptap
extensions (direct class refs) and the carve-out for external plugin
extensions that may keep `() => import(...)` to ship their API code in a
separate chunk.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Tiptap: Move extension APIs and elements into a shared lazy boundary chunk
The previous PR collapsed ~70 Tiptap chunks into 3 by inlining first-party API
and element references directly into manifest files. That win came with a real
downside flagged in code review (lke / mra): the API/element implementation
bytes ended up in the manifest registration bundle, so every workspace —
including ones without an RTE — paid ~700 KB of Tiptap code on boot.
This commit keeps the chunk-coalescing win but restores the lazy boundary by
routing every first-party manifest's `api` / `element` reference through a
single shared bundle file `extensions/extension-apis.bundle.ts`. Each manifest
holds a dynamic-import thunk pointing at that one bundle, so:
- Rollup still emits a single chunk for all Tiptap extension code (no chunk
explosion).
- The manifest registration bundle stays slim — it carries only metadata
(alias / label / icon / group / kind / forExtensions) plus the thunks.
- The bundle is only fetched the first time `<umb-input-tiptap>` actually
mounts.
Data-type configuration UIs (`extensions-configuration`,
`toolbar-configuration`, `statusbar-configuration`) read manifest metadata
via `umbExtensionsRegistry.byType(...)` only — they never call
`loadManifestApi` / `loadManifestElement`, so the data-type editor continues
to work without loading any Tiptap implementation code.
Property-editor UI elements (`tiptap-rte`, the three configuration UIs) also
revert to `() => import('./X.element.js')` so each loads on demand from its
own chunk rather than being inlined into the manifest bundle.
`umb-input-tiptap` no longer statically imports the Rich Text Essentials API;
it prepends the alias to the observed list instead, so essentials resolves
through the same lazy bundle as every other extension.
Added a test and stories file that mount `<umb-input-tiptap>` standalone (no
property-editor wrapper) to make the public usage pattern explicit.
Built and verified via `npm run build:for:cms`:
- `dist-cms/packages/tiptap/manifests.js` 48 KB (eager at boot)
- `dist-cms/packages/tiptap/extension-apis.bundle-*.js` 84 KB (lazy)
- `dist-cms/packages/tiptap/tiptap-toolbar-element-api-base-*.js` 654 KB
(lazy dependency of the bundle)
- per-element property-editor UI chunks load on demand when settings open
`npm run check:circular`, `npm run compile`, `npx wtr src/packages/tiptap`
all pass.
Related to #21152, builds on #22995.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Tiptap: Don't mount <umb-input-tiptap> in the standalone test
Mounting the element via fixture() spins up an UmbTiptapRteContext that
consumes UMB_SERVER_CONTEXT. In the unit-test runtime no server context
provider exists, so the context request stays pending. When @open-wc's
fixture tears down at end-of-file the request rejects with
"host disconnected" — surfaced as an unhandled promise rejection that
web-test-runner counts as a fatal runner error, exiting 1 even though every
individual test passed. The rejection happened to be in flight while a
block-grid clipboard test was active in CI, which is why the failure surfaced
there rather than in the tiptap test file itself.
Drop the manifest-registration assertion too — pulling the package-level
`manifests.ts` aggregator triggers a transitive 404 on the
`@umbraco-cms/backoffice/tiptap` importmap entry in the wtr environment.
The class-export + custom-element-registration checks are enough to prove
standalone exportability. The Storybook stories still cover the visual
end-to-end load path.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Use direct imports in core manifests
* Extract theme aliases into constants file
---------
Co-authored-by: Jacob Overgaard <752371+iOvergaard@users.noreply.github.com>
* Backoffice: Add Cache-Control headers to cache-busted backoffice assets (AB#68478)
Adds a UseUmbracoBackOfficeCacheHeaders middleware that sets
Cache-Control: public, max-age=31536000, immutable on responses served
from the cache-busted backoffice path (/umbraco/backoffice/<hash>/*).
The hash in the URL is derived from the Umbraco version, so the URL
itself invalidates on every release - making 'immutable' safe regardless
of whether individual filenames contain a content hash.
In debug mode the cache-bust hash changes per request, so the header is
set to 'no-cache' to avoid filling the browser disk cache with single-use
entries.
Design is non-destructive to consumer customisation, addressing the
review feedback on the v14 attempt (#14475):
- Does not touch StaticFileOptions; consumer
services.Configure<StaticFileOptions>(...) and OnPrepareResponse
callbacks continue to work unchanged.
- Sets the header via Response.OnStarting with a ContainsKey guard, so
any synchronous Cache-Control set upstream wins; consumer OnStarting
callbacks registered later fire first (LIFO) and also win.
- Skips non-2xx responses to avoid long-lived caching of error responses.
Related: GH #21152, PR #22896.
* Backoffice: Correct rationale for no-cache in debug mode
Reword the XML doc on UseUmbracoBackOfficeCacheHeaders to reflect that
IBackOfficePathGenerator is a singleton, so the cache-bust hash is
computed once at startup even in debug mode (per Copilot review on
#22951). The reason for no-cache is not "hash changes per request" but
that built assets may change in place during dev iteration; no-cache
allows fast 304 revalidation while no-store would force full
re-downloads.
No functional change.
* Backoffice: Add unit tests for UseUmbracoBackOfficeCacheHeaders
Covers six scenarios via a minimal in-process pipeline composed with
Microsoft.AspNetCore.TestHost:
- Production: 200 under hash prefix gets immutable header
- Debug: 200 under hash prefix gets no-cache
- Non-2xx under prefix: header not set (status gate)
- Path outside prefix: header not set (path gate)
- Consumer synchronous override: ContainsKey guard skips, consumer wins
- Consumer OnStarting override: LIFO ordering lets consumer win
Adds Microsoft.AspNetCore.TestHost to Umbraco.Tests.UnitTests (standard
Microsoft package, version pinned in tests/Directory.Packages.props).
* Backoffice: Extract cache-headers logic into IMiddleware class
Matches the existing Umbraco middleware convention (BootFailedMiddleware,
PreviewAuthenticationMiddleware, UmbracoRequestMiddleware, etc.) per
Kenn's note: prefer UseMiddleware<T>() with a DI-resolved class over
inline builder.Use lambdas.
The new UmbracoBackOfficeCacheHeadersMiddleware:
- Implements IMiddleware; registered as a singleton in AddWebComponents
- Computes prefix and header value once in the constructor (both
dependencies are singletons themselves, so this is stable)
- Behaviour is unchanged from the inline version
The UseUmbracoBackOfficeCacheHeaders extension method becomes a thin
UseMiddleware<T>() wrapper. Tests updated to register the middleware in
the TestServer DI container so it can be resolved through UseMiddleware.
* Backoffice: Document IMiddleware convention in Web.Common CLAUDE.md
Adds an explicit "Convention" note before the middleware list so future
contributors (and AI assistants) default to the IMiddleware class +
AddSingleton + UseMiddleware<T>() pattern rather than inline
builder.Use(async ...) lambdas. Also lists the new
UmbracoBackOfficeCacheHeadersMiddleware in the folder structure and
middleware reference.
* Backoffice: Tighten middleware convention note with full corroboration
Lists every IMiddleware implementer in the codebase (10/10) and calls
out the two known inline-lambda exceptions (CspNonceExtensions,
WebApplicationExtensions) so the rule reads as the established
convention rather than an absolute, while still steering new work
toward IMiddleware + AddSingleton + UseMiddleware<T>().
* Backoffice: Register cache-headers middleware in AddBackOfficeCore
DI scope validation runs in Development/CI and pre-checks every
singleton's dependency graph can be constructed. The middleware was
registered in AddWebComponents (which runs for every Umbraco bootstrap),
but its IBackOfficePathGenerator dependency is only registered by
AddBackOffice(). The previous CI run on this branch surfaced the
problem in four Delivery-only/Website-only bootstrap tests
(CoreWithDeliveryApi_BootsSuccessfully, DeliveryOnlyScenario_BootsSuccessfully,
etc.) with "Unable to resolve service for type 'IBackOfficePathGenerator'
while attempting to activate 'UmbracoBackOfficeCacheHeadersMiddleware'".
Move the registration alongside IBackOfficePathGenerator in
AddBackOfficeCore (Api.Management), which is the same scope as the
backoffice itself. This also matches the wire-up gate in
UmbracoApplicationBuilder.cs that only calls UseUmbracoBackOfficeCacheHeaders
when IBackOfficeEnabledMarker is registered.
CLAUDE.md updated with the rule ("register the middleware next to its
dependencies' registration") and a pitfall note about DI scope validation.
* Backoffice: Address review feedback from AndyButland (PR #22951)
- Move UseUmbracoBackOfficeCacheHeadersTests from Umbraco.Tests.UnitTests
to Umbraco.Tests.Integration. It uses HostBuilder + TestServer to
exercise the real HTTP pipeline, which is integration-shaped rather
than unit-shaped. Drop Microsoft.AspNetCore.TestHost from UnitTests
(Mvc.Testing in Integration provides it transitively) and from
tests/Directory.Packages.props.
- Soften the misleading "no trailing slash" comment in
UmbracoBackOfficeCacheHeadersMiddleware — we trim anyway, so the
comment is now framed as defensive normalisation.
- Trim the dense middleware convention note in Web.Common/CLAUDE.md to
one paragraph (rule + the two known inline-lambda exceptions). Move
the DI-scope-validation pitfall narrative out of CLAUDE.md and into a
three-line code comment next to the AddSingleton call in
AddBackOfficeCore where it actually applies.
* Backoffice: HTTP verb gate, 304 inclusion, namespace + unused using (PR #22951 review)
Three more from AndyButland's review:
1. Verb gate + 304 inclusion in UmbracoBackOfficeCacheHeadersMiddleware.
Restrict the path-prefix match to GET and HEAD so POST/PUT/DELETE
responses and OPTIONS (CORS preflight) responses don't get tagged as
immutable. Include 304 alongside 2xx in the status gate so
intermediate caches (CDN/proxy) receive the Cache-Control directive on
revalidation responses too. Extended the test suite with four new
cases: NotModifiedResponseUnderPrefix_SetsImmutable,
HeadRequestUnderPrefix_SetsImmutable,
OptionsRequestUnderPrefix_DoesNotSetHeader,
PostRequestUnderPrefix_DoesNotSetHeader. All 10 tests pass.
2. Test namespace updated to Umbraco.Cms.Tests.Integration.* to match
the convention used by ~629 other files in Umbraco.Tests.Integration
(vs the 2 outliers I copied from).
3. Drop unused 'using Umbraco.Extensions;' from the test file.
* Backoffice: Extract conditional checks to satisfy CodeScene complexity gate
CodeScene flagged InvokeAsync with "Complex Conditional" (advisory rule,
code health impact 9.69) after the verb + 304 additions in the prior
commit. Extract the two checks into IsCacheableAssetRequest and
ShouldSetCacheControl helper methods. No behaviour change; tests still
green (10/10, 149 ms).
* Stabilise rollback E2E test by waiting for document reload before asserting.
* Condense rollback wait comment per code-review feedback.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Addressed code review feedback.
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* ensure the order from the search endpoints taking a collection of keys is preserved
* Align cosmetic changes to ensure later merge up doesn't run into conflicts.
---------
Co-authored-by: Lan Nguyen Thuy <lnt@umbraco.dk>
Co-authored-by: Andy Butland <abutland73@gmail.com>
* Use direct imports in core manifests
* Extract theme aliases into constants file
---------
Co-authored-by: Jacob Overgaard <752371+iOvergaard@users.noreply.github.com>
* update order search result for element, member type, dictionary...
* undo dictionary search API
* reorder search value
* Apply OrderByRequestedIds
* add unit tests for search order
* Reverted unnecessarily changed files, minor test clean-up, aligned controllers for XML docs.
---------
Co-authored-by: Lan Nguyen Thuy <lnt@umbraco.dk>
Co-authored-by: Andy Butland <abutland73@gmail.com>
* Add IgnoredDelayChanged event to allow updates during back-off
* Make Period and IgnoredDelay settable on RecurringBackgroundJobBase with auto-raising events
* Address PR review: handle CTS race, restore negative-IgnoredDelay guard, clarify setter remarks
- Swallow ObjectDisposedException in OnIgnoredDelayChanged for the shutdown race where an in-flight handler reads the to-be-disposed CTS via Interlocked.Exchange before Dispose disposes it.
- Restore "skip back-off when IgnoredDelay <= TimeSpan.Zero (and not Timeout.InfiniteTimeSpan)" guard in IgnoreAndWaitAsync to defend against direct IRecurringBackgroundJob implementations / property overrides returning a negative value that would otherwise tight-loop via ComputeNextDelay clamping to zero.
- Add regression test for the negative-IgnoredDelay skip path.
- Mirror the constructor "stored without raising" remark on the Period and IgnoredDelay setter doc comments.
* Dispose newly-installed CTS when shutdown race wins the rotate-and-cancel
* Clarify XML docs.
* Introduce helper for cancellation source rotate and cancel.
---------
Co-authored-by: Andy Butland <abutland73@gmail.com>
* Support anchor fragments that are included in the data attribute but missing in the href when migrating local links.
* Addressed code review feedback.
* Support anchor fragments that are included in the data attribute but missing in the href when migrating local links.
* Addressed code review feedback.
* Workspace Actions: Restore waiting state for buttons with additional options
The waiting state was suppressed whenever a workspace action reported
hasAdditionalOptions() (e.g. Save and publish on multi-variant sites),
so users saw the button jump straight from idle to the success tick
with no in-flight feedback.
Always set 'waiting' on click (unless the action is a link). The
variant-picker modal still opens on top of the button, so the spinner
is effectively invisible during selection — but it becomes visible
as soon as the modal closes and the publish request is in flight.
Fixes#22551
* Workspace Actions: Spin button only while real work is in flight
Replace the eager always-set-waiting behaviour from the previous commit
with an opt-in `isPending` signal so the spinner appears only while
actual work (validation + HTTP) is happening - not while the variant
picker modal is open, and never as a spurious success tick when the
user cancels the modal.
Changes:
- Add optional `isPending: Observable<boolean>` to UmbWorkspaceAction
and a default UmbBooleanState + protected setPending() on the base
class. Optional + backwards compatible for external implementers.
- Add optional `onActionStarting` callback (via a shared
UmbWorkspaceActionExecutionOptions type) to
UmbPublishableWorkspaceContext.saveAndPublish and
UmbSaveableWorkspaceContext.requestSave. The document publishing
context and content detail workspace base invoke the callback at the
join point right after the variant picker resolves (or is skipped
for the single-variant case), so it never fires when the modal is
cancelled.
- Wire the document save and save-and-publish actions to clear pending
at the start of execute() and pass an onActionStarting callback that
flips it true when work begins.
- Update the workspace action element to observe api.isPending: when
the observable is present the waiting state is driven by the
observable (and the success tick is suppressed if the action
resolves without ever signalling pending - i.e. a cancellation).
When the observable is absent the element falls back to the legacy
eager-waiting behaviour. Failures always surface the failed tick.
Fixes#22551
* Reduce cyclomatic complexity of #onClick and _handleSave
CodeScene Code Health Review flagged two complexity issues:
- UmbWorkspaceActionElement.#onClick reached cyclomatic complexity 9
(threshold is < 9). Extracted the api-execution branch into a new
private #runApiAction helper so #onClick collapses to a simple
link-vs-action dispatch.
- _handleSave was already over the threshold (14); my optional-chain
callback invocation pushed it to 16. Moved the
`executionOptions?.onActionStarting?.()` call into a #notifyActionStarting
helper so the call site is a plain method call and contributes zero
cyclomatic complexity to _handleSave.
No behavioural change.
* Reduce cyclomatic complexity of #handleSaveAndPublish
Same fix as the previous commit's #notifyActionStarting extraction in
content-detail-workspace-base: move the optional-chain callback
invocation into a private helper so #handleSaveAndPublish stays at its
pre-PR cyclomatic complexity (15) instead of degrading to 17.
No behavioural change.
* DRY: extract notifyWorkspaceActionStarting into a shared utility
Both UmbDocumentPublishingWorkspaceContext.#handleSaveAndPublish and
UmbContentDetailWorkspaceContextBase._handleSave had identical private
optional-chain callback off the host method's cyclomatic complexity.
Replace both with a single exported notifyWorkspaceActionStarting()
utility co-located with UmbWorkspaceActionExecutionOptions. This:
- Removes a duplication point between the two contexts.
- Gives future workspace context implementations a ready-made way to
honour the optional callback without re-inventing the helper or
paying the cyclomatic-complexity cost at the call site.
No behavioural change.
* Rename isPending -> isExecuting to mirror the execute() method
Niels suggested correlating the observable's name with the action's
`execute()` method, so the symbol set is now:
- isExecuting (observable on UmbWorkspaceAction interface)
- _isExecuting / setExecuting (UmbWorkspaceActionBase)
- #observeIsExecuting / #executionStarted (workspace-action element)
- isExecutingObserver (observer alias)
Pure rename; no behavioural change.
* Address Copilot review: lazy isExecuting, observer scope, finally reset
Five Copilot findings on PR #22554. Three real regressions + two
contract violations, all addressed:
1. UmbWorkspaceActionBase always exposing `isExecuting` made every
existing subclass appear to opt in to the new modal-aware flow,
suppressing waiting/success states for actions that never call
setExecuting(true). Made `_isExecuting`/`isExecuting` lazy: only
created on the first setExecuting() call. Opt-in subclasses call
`setExecuting(false)` in their constructor so the observable is
exposed before the workspace-action element reads it. Subclasses
that don't opt in keep `isExecuting` undefined and the element
falls back to legacy eager waiting feedback.
2. Element observation of `isExecuting` now lives inside #runApiAction
so it tracks whichever api is actually invoked (`_actionApi ?? #api`),
correctly handling subclasses like UmbSaveAndPreviewWorkspaceActionElement
that swap in a different api at runtime. The shared observer alias
replaces any previous observation on re-clicks.
3. UmbSaveWorkspaceAction and UmbDocumentSaveAndPublishWorkspaceAction
now wrap their execute() body in try/finally and reset
setExecuting(false) on completion so the observable honours the
"true while execute() is performing real work, false otherwise"
contract instead of getting stuck at true between executions.
No behavioural change for actions that already worked correctly before
this PR; the regression-prone "always exposed" behaviour is gone.
* Address Claude review: Elements gap, type placement, tests + cleanup
Three follow-ups on top of c15eb2d0bc:
1. Elements gap — UmbElementSaveAndPublishWorkspaceAction +
UmbElementPublishingWorkspaceContext now wire through the same
onActionStarting/notifyWorkspaceActionStarting handshake as the
Document equivalents, so multi-variant Elements (Forms, Commerce, etc.)
get the spinner-after-modal behaviour rather than no spinner at all.
2. Type placement — moved UmbWorkspaceActionExecutionOptions out of
publishable-workspace-context.interface.ts into its own file so the
saveable interface no longer has a directional dependency on the
publishable one. Both peer contexts now import from the same neutral
location.
3. Unit tests — added blackbox coverage for notifyWorkspaceActionStarting
(no-op on undefined options/callback, invokes when present) and the
UmbWorkspaceActionBase.setExecuting lazy-opt-in contract (undefined
until first call, observable then exposed, value flips, sequential
emissions, stable reference across calls).
Code-review cleanup applied on the same pass:
- Dropped the redundant `setExecuting(false)` at the start of execute()
in the save and save-and-publish actions; the finally block plus
UmbBooleanState's value-dedup already cover idempotency on retries.
- Removed an overlong block comment on `_isExecuting`; the JSDoc on
setExecuting already documents the lazy/opt-in contract for subclasses.
- Trimmed an internal motivation comment from notify-workspace-action-
starting.function.ts that referenced cyclomatic complexity.
- Extracted a tiny makeAction() helper in the controller test to remove
the `{ meta: {} as never }` repetition.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Workspace Actions: Align Save button state with Save & Publish (Andy review feedback)
Two related fixes addressing the variant-Save inconsistency Andy reported:
- Element catch block now only sets `failed` once `#executionStarted` is
true. Pre-flight rejections (user cancelling a variant-picker modal,
context-missing throws, etc.) leave the button idle, matching the
silent-cancel path used by `#handleSaveAndPublish`. Legacy actions
that don't opt in to `isExecuting` are unaffected because they set
`#executionStarted = true` eagerly on click.
- `UmbDocumentWorkspaceContext._handleSave` and
`UmbElementWorkspaceContext._handleSave` now accept and forward the
`UmbWorkspaceActionExecutionOptions` argument to `super._handleSave`.
The previous overrides dropped the parameter, so the
`onActionStarting` callback supplied by `UmbSaveWorkspaceAction` never
fired - which is why Save showed no waiting/success indicator even
on a successful submit.
Result: Save and Save-and-publish now behave identically -
cancel = no indicator, submit = waiting then success - for both
invariant and multi-variant documents and elements.
* Docs: Document the modal-aware execution feedback contract for workspace actions
New 'Button state when the action opens a modal' subsection in
docs/workspaces.md explaining the three-piece contract:
UmbWorkspaceActionExecutionOptions + notifyWorkspaceActionStarting +
UmbWorkspaceActionBase.setExecuting. Covers third-party authoring of
modal-aware buttons, the cancel/pre-flight idle behaviour, and the
silent-parameter-drop pitfall on _handleSave overrides.
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Workspace Actions: Restore waiting state for buttons with additional options
The waiting state was suppressed whenever a workspace action reported
hasAdditionalOptions() (e.g. Save and publish on multi-variant sites),
so users saw the button jump straight from idle to the success tick
with no in-flight feedback.
Always set 'waiting' on click (unless the action is a link). The
variant-picker modal still opens on top of the button, so the spinner
is effectively invisible during selection — but it becomes visible
as soon as the modal closes and the publish request is in flight.
Fixes#22551
* Workspace Actions: Spin button only while real work is in flight
Replace the eager always-set-waiting behaviour from the previous commit
with an opt-in `isPending` signal so the spinner appears only while
actual work (validation + HTTP) is happening - not while the variant
picker modal is open, and never as a spurious success tick when the
user cancels the modal.
Changes:
- Add optional `isPending: Observable<boolean>` to UmbWorkspaceAction
and a default UmbBooleanState + protected setPending() on the base
class. Optional + backwards compatible for external implementers.
- Add optional `onActionStarting` callback (via a shared
UmbWorkspaceActionExecutionOptions type) to
UmbPublishableWorkspaceContext.saveAndPublish and
UmbSaveableWorkspaceContext.requestSave. The document publishing
context and content detail workspace base invoke the callback at the
join point right after the variant picker resolves (or is skipped
for the single-variant case), so it never fires when the modal is
cancelled.
- Wire the document save and save-and-publish actions to clear pending
at the start of execute() and pass an onActionStarting callback that
flips it true when work begins.
- Update the workspace action element to observe api.isPending: when
the observable is present the waiting state is driven by the
observable (and the success tick is suppressed if the action
resolves without ever signalling pending - i.e. a cancellation).
When the observable is absent the element falls back to the legacy
eager-waiting behaviour. Failures always surface the failed tick.
Fixes#22551
* Reduce cyclomatic complexity of #onClick and _handleSave
CodeScene Code Health Review flagged two complexity issues:
- UmbWorkspaceActionElement.#onClick reached cyclomatic complexity 9
(threshold is < 9). Extracted the api-execution branch into a new
private #runApiAction helper so #onClick collapses to a simple
link-vs-action dispatch.
- _handleSave was already over the threshold (14); my optional-chain
callback invocation pushed it to 16. Moved the
`executionOptions?.onActionStarting?.()` call into a #notifyActionStarting
helper so the call site is a plain method call and contributes zero
cyclomatic complexity to _handleSave.
No behavioural change.
* Reduce cyclomatic complexity of #handleSaveAndPublish
Same fix as the previous commit's #notifyActionStarting extraction in
content-detail-workspace-base: move the optional-chain callback
invocation into a private helper so #handleSaveAndPublish stays at its
pre-PR cyclomatic complexity (15) instead of degrading to 17.
No behavioural change.
* DRY: extract notifyWorkspaceActionStarting into a shared utility
Both UmbDocumentPublishingWorkspaceContext.#handleSaveAndPublish and
UmbContentDetailWorkspaceContextBase._handleSave had identical private
#notifyActionStarting helpers introduced in this PR purely to keep the
optional-chain callback off the host method's cyclomatic complexity.
Replace both with a single exported notifyWorkspaceActionStarting()
utility co-located with UmbWorkspaceActionExecutionOptions. This:
- Removes a duplication point between the two contexts.
- Gives future workspace context implementations a ready-made way to
honour the optional callback without re-inventing the helper or
paying the cyclomatic-complexity cost at the call site.
No behavioural change.
* Rename isPending -> isExecuting to mirror the execute() method
Niels suggested correlating the observable's name with the action's
`execute()` method, so the symbol set is now:
- isExecuting (observable on UmbWorkspaceAction interface)
- _isExecuting / setExecuting (UmbWorkspaceActionBase)
- #observeIsExecuting / #executionStarted (workspace-action element)
- isExecutingObserver (observer alias)
Pure rename; no behavioural change.
* Address Copilot review: lazy isExecuting, observer scope, finally reset
Five Copilot findings on PR #22554. Three real regressions + two
contract violations, all addressed:
1. UmbWorkspaceActionBase always exposing `isExecuting` made every
existing subclass appear to opt in to the new modal-aware flow,
suppressing waiting/success states for actions that never call
setExecuting(true). Made `_isExecuting`/`isExecuting` lazy: only
created on the first setExecuting() call. Opt-in subclasses call
`setExecuting(false)` in their constructor so the observable is
exposed before the workspace-action element reads it. Subclasses
that don't opt in keep `isExecuting` undefined and the element
falls back to legacy eager waiting feedback.
2. Element observation of `isExecuting` now lives inside #runApiAction
so it tracks whichever api is actually invoked (`_actionApi ?? #api`),
correctly handling subclasses like UmbSaveAndPreviewWorkspaceActionElement
that swap in a different api at runtime. The shared observer alias
replaces any previous observation on re-clicks.
3. UmbSaveWorkspaceAction and UmbDocumentSaveAndPublishWorkspaceAction
now wrap their execute() body in try/finally and reset
setExecuting(false) on completion so the observable honours the
"true while execute() is performing real work, false otherwise"
contract instead of getting stuck at true between executions.
No behavioural change for actions that already worked correctly before
this PR; the regression-prone "always exposed" behaviour is gone.
* Address Claude review: Elements gap, type placement, tests + cleanup
Three follow-ups on top of c15eb2d0bc:
1. Elements gap — UmbElementSaveAndPublishWorkspaceAction +
UmbElementPublishingWorkspaceContext now wire through the same
onActionStarting/notifyWorkspaceActionStarting handshake as the
Document equivalents, so multi-variant Elements (Forms, Commerce, etc.)
get the spinner-after-modal behaviour rather than no spinner at all.
2. Type placement — moved UmbWorkspaceActionExecutionOptions out of
publishable-workspace-context.interface.ts into its own file so the
saveable interface no longer has a directional dependency on the
publishable one. Both peer contexts now import from the same neutral
location.
3. Unit tests — added blackbox coverage for notifyWorkspaceActionStarting
(no-op on undefined options/callback, invokes when present) and the
UmbWorkspaceActionBase.setExecuting lazy-opt-in contract (undefined
until first call, observable then exposed, value flips, sequential
emissions, stable reference across calls).
Code-review cleanup applied on the same pass:
- Dropped the redundant `setExecuting(false)` at the start of execute()
in the save and save-and-publish actions; the finally block plus
UmbBooleanState's value-dedup already cover idempotency on retries.
- Removed an overlong block comment on `_isExecuting`; the JSDoc on
setExecuting already documents the lazy/opt-in contract for subclasses.
- Trimmed an internal motivation comment from notify-workspace-action-
starting.function.ts that referenced cyclomatic complexity.
- Extracted a tiny makeAction() helper in the controller test to remove
the `{ meta: {} as never }` repetition.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Workspace Actions: Align Save button state with Save & Publish (Andy review feedback)
Two related fixes addressing the variant-Save inconsistency Andy reported:
- Element catch block now only sets `failed` once `#executionStarted` is
true. Pre-flight rejections (user cancelling a variant-picker modal,
context-missing throws, etc.) leave the button idle, matching the
silent-cancel path used by `#handleSaveAndPublish`. Legacy actions
that don't opt in to `isExecuting` are unaffected because they set
`#executionStarted = true` eagerly on click.
- `UmbDocumentWorkspaceContext._handleSave` and
`UmbElementWorkspaceContext._handleSave` now accept and forward the
`UmbWorkspaceActionExecutionOptions` argument to `super._handleSave`.
The previous overrides dropped the parameter, so the
`onActionStarting` callback supplied by `UmbSaveWorkspaceAction` never
fired - which is why Save showed no waiting/success indicator even
on a successful submit.
Result: Save and Save-and-publish now behave identically -
cancel = no indicator, submit = waiting then success - for both
invariant and multi-variant documents and elements.
* Docs: Document the modal-aware execution feedback contract for workspace actions
New 'Button state when the action opens a modal' subsection in
docs/workspaces.md explaining the three-piece contract:
UmbWorkspaceActionExecutionOptions + notifyWorkspaceActionStarting +
UmbWorkspaceActionBase.setExecuting. Covers third-party authoring of
modal-aware buttons, the cancel/pre-flight idle behaviour, and the
silent-parameter-drop pitfall on _handleSave overrides.
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Backoffice: Coalesce small Rollup chunks across all workspaces (AB#67983)
Set experimentalMinChunkSize=10_000 as the default in the shared Vite
helper. Every workspace inherits the coalescing automatically; the
threshold can still be overridden per workspace (pass 0 to disable).
Impact on dist-cms output:
- packages/core .js files: 981 -> 272 (-72%)
- All workspaces combined .js files: 2194 -> 1401 (-36%)
- Welcome dashboard .js requests: 510 -> 497 (-2.5%)
- packages/ufm requests in particular: 23 -> 12 (-48%)
- Gzipped bundle total: -1.2%
- Raw bytes: +1.4% (small overhead from merged chunks; gzip wins it back)
All entry chunks are preserved, so every public
@umbraco-cms/backoffice/<sub> import keeps resolving without changes
to package.json exports or tsconfig paths.
Further consolidation (collapsing core's per-subpath entries into a
single bundle with stubs) was prototyped but hits a TDZ cycle between
the eager entry and its dynamic-import descendants. Tracked for v18,
not part of this change.
* Backoffice: Normalise umbraco-package + manifests shapes (AB#67983)
Aligns the two outliers with the conventions used by the other 38
first-party packages:
- documents/umbraco-package.ts now uses the lazy bundle pattern
(type: 'bundle', js: () => import('./manifests.js')) instead of
eagerly importing manifests at module evaluation. The bundle
initializer auto-loads the manifests at boot, so behaviour is
unchanged.
- umbraco-news/manifests.ts now exports `manifests: Array<...>`
instead of a bare `dashboard` object. The bundle initializer
enumerates exports regardless of name, so behaviour is unchanged.
Preparatory cleanup so future build-time manifest aggregation can
treat every workspace uniformly.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Backoffice: Coalesce small Rollup chunks across all workspaces (AB#67983)
Set experimentalMinChunkSize=10_000 as the default in the shared Vite
helper. Every workspace inherits the coalescing automatically; the
threshold can still be overridden per workspace (pass 0 to disable).
Impact on dist-cms output:
- packages/core .js files: 981 -> 272 (-72%)
- All workspaces combined .js files: 2194 -> 1401 (-36%)
- Welcome dashboard .js requests: 510 -> 497 (-2.5%)
- packages/ufm requests in particular: 23 -> 12 (-48%)
- Gzipped bundle total: -1.2%
- Raw bytes: +1.4% (small overhead from merged chunks; gzip wins it back)
All entry chunks are preserved, so every public
@umbraco-cms/backoffice/<sub> import keeps resolving without changes
to package.json exports or tsconfig paths.
Further consolidation (collapsing core's per-subpath entries into a
single bundle with stubs) was prototyped but hits a TDZ cycle between
the eager entry and its dynamic-import descendants. Tracked for v18,
not part of this change.
* Backoffice: Normalise umbraco-package + manifests shapes (AB#67983)
Aligns the two outliers with the conventions used by the other 38
first-party packages:
- documents/umbraco-package.ts now uses the lazy bundle pattern
(type: 'bundle', js: () => import('./manifests.js')) instead of
eagerly importing manifests at module evaluation. The bundle
initializer auto-loads the manifests at boot, so behaviour is
unchanged.
- umbraco-news/manifests.ts now exports `manifests: Array<...>`
instead of a bare `dashboard` object. The bundle initializer
enumerates exports regardless of name, so behaviour is unchanged.
Preparatory cleanup so future build-time manifest aggregation can
treat every workspace uniformly.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Compute next delay to compensate for time drift
* Use SemaphoreSlim to properly handle exceptions, cancellation tokens and triggering immediate executions
* Add RecurringBackgroundJobBase to contain default values and hide obsoleted method
* Add NextExecutionStrategy parameter to adjust the schedule after triggered executions
* Add TriggerExecution methods to RecurringBackgroundJobHostedServiceRunner
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Handle cancellation (application shutdown) and publish RecurringBackgroundJobCanceledNotification
* Match hosted services by Type instead of type name string
* Extract shared helper for TriggerExecution tests
* Clear trigger state when initial delay is interrupted
* Clear _nextExecutionSkipOnOvershoot unconditionally
* Combine ComputeNextDelay tests
* Consolidate trigger state into an immutable record for thread safety
* Use ConcurrentDictionary for thread-safe hosted service lookup
* Remove hosted services from dictionary on stop
* Fix API compatibility errors
* Removed unneeded using.
* Register RecurringBackgroundJobHostedServiceRunner as resolvable singleton
* Remove failed hosted service from dictionary when StartAsync throws
* Use semaphore signaling instead of Task.Delay in trigger tests
Use semaphore signaling instead of Task.Delay in trigger tests 2
* Inject TimeProvider into RecurringHostedServiceBase for deterministic testing
Fix timeprovider
* Use DelayCalculator.GetDelay instead of RecurringHostedServiceBase.GetDelay
* Fix Exception_In_PerformExecuteAsync_Does_Not_Kill_Loop test
* Avoid disposing period-change CTS while wait loop may still reference it
* Configure IEventMessagesFactory mock to return real EventMessages
* Clarify TriggerExecution(TimeSpan) docs and add ChangePeriod test
* Validate period is positive and use GetOrAdd to avoid creating unused hosted services
* Set up Period and Delay on mock job to satisfy constructor validation
* Ensure PeriodChanged event is unsubscribed again
* Fix trigger state race, simplify ReleaseSignal, and add canceled notification test
Fix trigger state
* Use Interlocked for _period reads/writes and implement thread-safe dispose pattern
* Remove hosted service from dictionary before stopping to prevent triggering during shutdown
* Replace Task.Yield with semaphore timeouts in negative assertions
* Tidy RecurringBackgroundJobBase docs and runner error handling
* Wait IgnoredDelay after ignored execution to prevent tight looping when Period is short or zero
* Add IRecurringBackgroundJobTrigger<TJob> for opt-in job triggering
* Register IRecurringBackgroundJobTrigger as open generic and drop AddTriggerableRecurringBackgroundJob
* Fix and add parameter validation
* Allow Timeout.InfiniteTimeSpan as Period for manual-trigger-only recurring jobs
* Migrate built-in jobs to RecurringBackgroundJobBase and require ITriggerableRecurringBackgroundJob in runner trigger overloads
* Support infinite Delay and honor TriggerExecution(TimeSpan) issued during the initial delay
* Handle edge case of backoff via InfiniteTimeSpan.
* Refactored large method.
* Added clarifying documentation.
* Suppress ExecutionContext flow when starting the recurring background loop, restoring previous timer behaviour.
* Relocate Suppress ExecutionContext flow to avoid package validation error.
* Align IRecurringBackgroundJobTrigger generic type constraint with AddRecurringBackgroundJob
* Rename ApplyTriggerState to ComputeNextDelayFromTriggerState
* Allow Timeout.InfiniteTimeSpan as IgnoredDelay to fully disable a job for the remaining application lifecycle
* Fix generic type constraint
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Andy Butland <abutland73@gmail.com>
* Compute next delay to compensate for time drift
* Use SemaphoreSlim to properly handle exceptions, cancellation tokens and triggering immediate executions
* Add RecurringBackgroundJobBase to contain default values and hide obsoleted method
* Add NextExecutionStrategy parameter to adjust the schedule after triggered executions
* Add TriggerExecution methods to RecurringBackgroundJobHostedServiceRunner
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Handle cancellation (application shutdown) and publish RecurringBackgroundJobCanceledNotification
* Match hosted services by Type instead of type name string
* Extract shared helper for TriggerExecution tests
* Clear trigger state when initial delay is interrupted
* Clear _nextExecutionSkipOnOvershoot unconditionally
* Combine ComputeNextDelay tests
* Consolidate trigger state into an immutable record for thread safety
* Use ConcurrentDictionary for thread-safe hosted service lookup
* Remove hosted services from dictionary on stop
* Fix API compatibility errors
* Removed unneeded using.
* Register RecurringBackgroundJobHostedServiceRunner as resolvable singleton
* Remove failed hosted service from dictionary when StartAsync throws
* Use semaphore signaling instead of Task.Delay in trigger tests
Use semaphore signaling instead of Task.Delay in trigger tests 2
* Inject TimeProvider into RecurringHostedServiceBase for deterministic testing
Fix timeprovider
* Use DelayCalculator.GetDelay instead of RecurringHostedServiceBase.GetDelay
* Fix Exception_In_PerformExecuteAsync_Does_Not_Kill_Loop test
* Avoid disposing period-change CTS while wait loop may still reference it
* Configure IEventMessagesFactory mock to return real EventMessages
* Clarify TriggerExecution(TimeSpan) docs and add ChangePeriod test
* Validate period is positive and use GetOrAdd to avoid creating unused hosted services
* Set up Period and Delay on mock job to satisfy constructor validation
* Ensure PeriodChanged event is unsubscribed again
* Fix trigger state race, simplify ReleaseSignal, and add canceled notification test
Fix trigger state
* Use Interlocked for _period reads/writes and implement thread-safe dispose pattern
* Remove hosted service from dictionary before stopping to prevent triggering during shutdown
* Replace Task.Yield with semaphore timeouts in negative assertions
* Tidy RecurringBackgroundJobBase docs and runner error handling
* Wait IgnoredDelay after ignored execution to prevent tight looping when Period is short or zero
* Add IRecurringBackgroundJobTrigger<TJob> for opt-in job triggering
* Register IRecurringBackgroundJobTrigger as open generic and drop AddTriggerableRecurringBackgroundJob
* Fix and add parameter validation
* Allow Timeout.InfiniteTimeSpan as Period for manual-trigger-only recurring jobs
* Migrate built-in jobs to RecurringBackgroundJobBase and require ITriggerableRecurringBackgroundJob in runner trigger overloads
* Support infinite Delay and honor TriggerExecution(TimeSpan) issued during the initial delay
* Handle edge case of backoff via InfiniteTimeSpan.
* Refactored large method.
* Added clarifying documentation.
* Suppress ExecutionContext flow when starting the recurring background loop, restoring previous timer behaviour.
* Relocate Suppress ExecutionContext flow to avoid package validation error.
* Align IRecurringBackgroundJobTrigger generic type constraint with AddRecurringBackgroundJob
* Rename ApplyTriggerState to ComputeNextDelayFromTriggerState
* Allow Timeout.InfiniteTimeSpan as IgnoredDelay to fully disable a job for the remaining application lifecycle
* Fix generic type constraint
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Andy Butland <abutland73@gmail.com>
* Add item data resolver support to picker data sources
* add js docs
* remove duplicated fallback logic
* wip unit tests of requestItemName method
* Use DocumentVariantStateModel in mock documents to fix compiler
* Update input-entity-data.context.ts
* Update input-entity-data.context.test.ts
- ElementPickerValueConverterTests: also stub the new synchronous IPublishedElementCache.GetById,
since Moq does not execute default interface implementations.
- PropertyCacheLevelTests.CacheUnknownTest: access a property inside Assert.Throws to trigger the
now-lazy property wrapper materialization.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Fix edit of a variant property composed to an invariant document.
* Collapse multi-line guard comment to a single line per project policy.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Add unit test coverage for invariant content with a culture-variant composition property.
Adds a third mock document/document-type pair representing an invariant
content type whose flattened property list contains a culture-variant
property (the runtime shape produced when a variant composition is applied
to an invariant content type) and a setPropertyValue test asserting the
value is stored as a culture/segment-invariant entry.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Remove null guard for segment variant documents, as null segment is the default segment.
* update mock data and tests to include real compositions
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Mads Rasmussen <madsr@hey.com>
* Fix edit of a variant property composed to an invariant document.
* Collapse multi-line guard comment to a single line per project policy.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Add unit test coverage for invariant content with a culture-variant composition property.
Adds a third mock document/document-type pair representing an invariant
content type whose flattened property list contains a culture-variant
property (the runtime shape produced when a variant composition is applied
to an invariant content type) and a setPropertyValue test asserting the
value is stored as a culture/segment-invariant entry.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Remove null guard for segment variant documents, as null segment is the default segment.
* update mock data and tests to include real compositions
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Mads Rasmussen <madsr@hey.com>
* feat(components): adds `umb-entity-frame` component + Storybook stories
* fix(components): address review feedback for `umb-entity-frame`
- Remove `pointer-events: auto` from `.tab` so the overlay is truly passive
(was intercepting events above the parent and causing hover flicker when
toggled via opacity).
- Replace `--uui-color-surface` tab text with `--uui-color-selected-contrast`
(the proper paired contrast token) and expose
`--umb-entity-frame-contrast-color` so consumers can override when supplying
a non-default `--umb-entity-frame-color`. Fixes contrast in dark and
high-contrast themes.
- Add `aria-hidden="true"` to `.tab`; the frame is purely decorative and the
parent owns the real semantics.
- Add a unit test verifying slot content takes precedence over the `label`
property.
* Removed `aria-hidden` from the label tab
As will need to be used with assistive technologies.
* Defensively handle log file corruptions by amalgamating errors per file and reporting as warning.
* Addressed code review comments.
* Use local reference to Newtonsoft.Json so it's clear we are only using it for exception handling.
---------
Co-authored-by: Kenn Jacobsen <kja@umbraco.dk>
* Remove the ability to enable or disable the redirect tracker from the UI.
* Addressed code review feedback.
* Update OpenApi.json.
* Regenerate backend SDK from updated OpenApi.json
* Update UI to use lozenge status indicator rather than an imperative action.
* Further UX tweak.
---------
Co-authored-by: Laura Neto <12862535+lauraneto@users.noreply.github.com>
* Add benchmark test for measuring improvements to children and descendant retrieval.
* Remove unnecessary sort from retrieval of children.
* Return the result of the filtered collection of children/decendants without materialising.
* Lazily build property wrappers when materializing IPublishedContent.
* Cache the ordered children list on NavigationNode.
* Cache descendants per parent on the navigation snapshot.
* Add synchronous fast path for retrieved of cached content.
* Additional unit tests.
* Add TODO to make UpdateSortOrder internal.
* Addressed code review feedback.
* Further unit tests.
* Future-proofed code comments.
* Add benchmark test for measuring improvements to children and descendant retrieval.
* Remove unnecessary sort from retrieval of children.
* Return the result of the filtered collection of children/decendants without materialising.
* Lazily build property wrappers when materializing IPublishedContent.
* Cache the ordered children list on NavigationNode.
* Cache descendants per parent on the navigation snapshot.
* Add synchronous fast path for retrieved of cached content.
* Additional unit tests.
* Add TODO to make UpdateSortOrder internal.
* Addressed code review feedback.
* Further unit tests.
* Future-proofed code comments.
Adds a 'Default UI language vs fallback culture' subsection so package
authors don't conflate the active UI locale (en-US by default) with the
fallback dictionary culture (en). A third-party language pack overriding
canonical keys must declare 'culture: en-US' on a default install,
otherwise the registry filters it out — the keys come from en.ts but
the override extension's culture has to match the active locale.
Surfaced by a tester report after PR #22743 merged the login screen's
localization into the backoffice client: the registry was forcing 'en'
active at boot (fixed in PR #22822) which masked the distinction, and
the docs didn't spell it out either.
* Localization: Honor DefaultUILanguage on initial load (closes#22808)
Closes#22808.
Previously, the configured DefaultUILanguage was silently overridden to
'en' at startup because the UmbLocalizationRegistry constructor called
loadLanguage(UMB_DEFAULT_LOCALIZATION_CULTURE) unconditionally. The
configured locale rendered into <html lang="..."> by Razor never had a
chance to flow through to the active language.
Changes:
- localization.registry.ts: stop forcing the active language to 'en'
in the constructor. Initial state is canonicalised from
document.documentElement.lang, falling back to 'en' for empty or
malformed input. The extension filter now always includes the
default culture alongside the active locale so 'en' translations
remain available as a key-level fallback regardless of which
language is active. A synchronous tap mirrors the active locale to
document.lang and the manager when the state changes, so a fresh
element rendered between loadLanguage() and the async translation
load picks up the right language immediately.
- localization.manager.ts: drop the MutationObserver on
document.documentElement and rely on the registry as the single
channel for language changes. setActiveLanguage accepts a `silent`
option so the synchronous tap can update fields without firing a
consumer notification (translations may still be loading). A new
notifyLanguageChanged() method is fired by the registry once
translations are in place.
- app.element.ts: subscribe to umbLocalizationRegistry.currentLanguage
in connectedCallback and mirror it onto the host element's lang
attribute, so myApp.lang reflects the source of truth rather than a
stale snapshot of <html lang>.
- auth.element.ts (login app): same lang subscription, plus after the
slim backoffice controller registers extensions, prefer the
visitor's navigator.language if a matching localization extension
exists (falls through baseName -> language -> en automatically).
Tests: new initialization tests for the registry, manager
setActiveLanguage tests, and the controller tests refactored to use
the new explicit setActiveLanguage API instead of writing directly to
document.documentElement.lang.
* Login: Only override DefaultUILanguage with navigator.language when default has no translation
If the admin sets DefaultUILanguage to a language we have a translation for,
respect that choice over the visitor's browser language. Falling back to
navigator.language only when the configured default isn't available avoids
silently ignoring the admin's explicit setting (e.g., DefaultUILanguage='da-DK'
on a site whose visitor's browser is 'en-GB' should still show Danish).
* Simplify: split setActiveLanguage from notifyLanguageChanged
Drop the silent option in favor of two intent-revealing methods:
setActiveLanguage updates the active language and direction without
side-effects; notifyLanguageChanged tells all connected controllers
to re-render against the current state. Callers compose them based
on what they need (the registry's pipeline updates language sync
then flushes notifications after async translation load).
Also extracts baseLocaleOf() helper, simplifies the navigator.language
match logic in the login app's #applyPreferredLanguage, and removes
narration-style comments in the new code.
* Restore deprecated UmbLocalizationManager.updateAll for backward compat
The old MutationObserver-driven updateAll() field was technically part
of the manager's public surface. Restore it as a deprecated alias that
reads document.lang/dir and forwards to setActiveLanguage + notifyLanguageChanged,
with a runtime UmbDeprecation warning pointing consumers at the new API.
* Fix deprecation removal version to v20 + correct baseLocaleOf JSDoc
Per the deprecation policy in CLAUDE.md (current major + 2): a method
deprecated in v18 must remain through v19 before removal, so the
earliest removal is v20, not v19.
Also corrects the baseLocaleOf JSDoc — Intl.Locale.baseName can include
script subtags (e.g. 'zh-Hant-TW'), not just language and region.
* Scope the active language to the host element, drop navigator.language
- Razor now sets `lang` on `<umb-app>` and `<umb-auth>` from
DefaultUILanguage. The element passes its lang through on connect, so
the host owns its own scope — future multi-backoffice scenarios (e.g.
signing into two Umbraco Cloud sites in the same document) get their
own language without fighting over a global `<html lang>`.
- The registry no longer reads or writes `document.documentElement.lang`.
Host elements drive it via `loadLanguage()`; `<html lang>` stays as
whatever Razor rendered.
- Removed the navigator.language preference detection in the login app.
Not in scope for the bug fix and adds behavior the admin can't opt out
of. The existing current-user-locale flow already handles per-user
preference after login.
- Tests updated to assert on `umbLocalizationManager.documentLanguage`
instead of `document.documentElement.lang`.
* Set <html lang="en"> to match the static (noscript) text in the templates
The page's `<html lang>` should describe the language of the document's
own innate content. Both Index.cshtml files only contain English static
text (the noscript fallback), so the page-level lang is now "en".
The dynamic UI inside <umb-app> / <umb-auth> carries its own `lang`
attribute (from DefaultUILanguage), which overrides for that subtree —
correct per the HTML spec for language inheritance.
* Drop deprecated UmbLocalizationManager.updateAll
It was public as an artifact of being an arrow function so it could be
passed to a MutationObserver without binding — not because it was
intended as part of the public API. External usage is effectively
zero, and the new explicit setActiveLanguage + notifyLanguageChanged
covers anyone who did reach for it.
* Docs: document active-language-on-host pattern in package-development.md
After PR #22822, the active UI language is driven by the shell elements
(<umb-app>, <umb-auth>) via their own lang attribute, not by <html lang>.
Document that so future contributors don't reach for the global.
* Collapse setActiveLanguage + notifyLanguageChanged into one method
The silent-write path is just `manager.documentLanguage = ...` — no new
method needed; the field is already public and was always writable. The
notify path keeps setActiveLanguage, which now both sets and notifies.
Net: one new public method on the manager instead of two.
* Inline the active-language write in the registry, drop setActiveLanguage
The previous version added setActiveLanguage on the manager as
a 'cleaner API' than direct field writes. But the manager's fields
(documentLanguage, documentDirection, connectedControllers) have
always been public, the registry is the only caller, and the wrapper
was just more public surface to maintain through the eventual
manager/registry collapse.
Net: -70 lines across the test file, no new public methods on the
manager, the registry pipeline writes the fields and iterates the
controllers directly where it would have called setActiveLanguage.
* Document that documentLanguage/Direction are read-only for consumers
Note in JSDoc that the only supported way to change the active language
is umbLocalizationRegistry.loadLanguage(). The fields stay writable for
the registry pipeline (cross-module internal); the comment is here so
the next contributor doesn't reach for them as a shortcut and end up
with the manager state out of sync with what's actually loaded.
* Localization: Honor DefaultUILanguage on initial load (closes#22808)
Closes#22808.
Previously, the configured DefaultUILanguage was silently overridden to
'en' at startup because the UmbLocalizationRegistry constructor called
loadLanguage(UMB_DEFAULT_LOCALIZATION_CULTURE) unconditionally. The
configured locale rendered into <html lang="..."> by Razor never had a
chance to flow through to the active language.
Changes:
- localization.registry.ts: stop forcing the active language to 'en'
in the constructor. Initial state is canonicalised from
document.documentElement.lang, falling back to 'en' for empty or
malformed input. The extension filter now always includes the
default culture alongside the active locale so 'en' translations
remain available as a key-level fallback regardless of which
language is active. A synchronous tap mirrors the active locale to
document.lang and the manager when the state changes, so a fresh
element rendered between loadLanguage() and the async translation
load picks up the right language immediately.
- localization.manager.ts: drop the MutationObserver on
document.documentElement and rely on the registry as the single
channel for language changes. setActiveLanguage accepts a `silent`
option so the synchronous tap can update fields without firing a
consumer notification (translations may still be loading). A new
notifyLanguageChanged() method is fired by the registry once
translations are in place.
- app.element.ts: subscribe to umbLocalizationRegistry.currentLanguage
in connectedCallback and mirror it onto the host element's lang
attribute, so myApp.lang reflects the source of truth rather than a
stale snapshot of <html lang>.
- auth.element.ts (login app): same lang subscription, plus after the
slim backoffice controller registers extensions, prefer the
visitor's navigator.language if a matching localization extension
exists (falls through baseName -> language -> en automatically).
Tests: new initialization tests for the registry, manager
setActiveLanguage tests, and the controller tests refactored to use
the new explicit setActiveLanguage API instead of writing directly to
document.documentElement.lang.
* Login: Only override DefaultUILanguage with navigator.language when default has no translation
If the admin sets DefaultUILanguage to a language we have a translation for,
respect that choice over the visitor's browser language. Falling back to
navigator.language only when the configured default isn't available avoids
silently ignoring the admin's explicit setting (e.g., DefaultUILanguage='da-DK'
on a site whose visitor's browser is 'en-GB' should still show Danish).
* Simplify: split setActiveLanguage from notifyLanguageChanged
Drop the silent option in favor of two intent-revealing methods:
setActiveLanguage updates the active language and direction without
side-effects; notifyLanguageChanged tells all connected controllers
to re-render against the current state. Callers compose them based
on what they need (the registry's pipeline updates language sync
then flushes notifications after async translation load).
Also extracts baseLocaleOf() helper, simplifies the navigator.language
match logic in the login app's #applyPreferredLanguage, and removes
narration-style comments in the new code.
* Restore deprecated UmbLocalizationManager.updateAll for backward compat
The old MutationObserver-driven updateAll() field was technically part
of the manager's public surface. Restore it as a deprecated alias that
reads document.lang/dir and forwards to setActiveLanguage + notifyLanguageChanged,
with a runtime UmbDeprecation warning pointing consumers at the new API.
* Fix deprecation removal version to v20 + correct baseLocaleOf JSDoc
Per the deprecation policy in CLAUDE.md (current major + 2): a method
deprecated in v18 must remain through v19 before removal, so the
earliest removal is v20, not v19.
Also corrects the baseLocaleOf JSDoc — Intl.Locale.baseName can include
script subtags (e.g. 'zh-Hant-TW'), not just language and region.
* Scope the active language to the host element, drop navigator.language
- Razor now sets `lang` on `<umb-app>` and `<umb-auth>` from
DefaultUILanguage. The element passes its lang through on connect, so
the host owns its own scope — future multi-backoffice scenarios (e.g.
signing into two Umbraco Cloud sites in the same document) get their
own language without fighting over a global `<html lang>`.
- The registry no longer reads or writes `document.documentElement.lang`.
Host elements drive it via `loadLanguage()`; `<html lang>` stays as
whatever Razor rendered.
- Removed the navigator.language preference detection in the login app.
Not in scope for the bug fix and adds behavior the admin can't opt out
of. The existing current-user-locale flow already handles per-user
preference after login.
- Tests updated to assert on `umbLocalizationManager.documentLanguage`
instead of `document.documentElement.lang`.
* Set <html lang="en"> to match the static (noscript) text in the templates
The page's `<html lang>` should describe the language of the document's
own innate content. Both Index.cshtml files only contain English static
text (the noscript fallback), so the page-level lang is now "en".
The dynamic UI inside <umb-app> / <umb-auth> carries its own `lang`
attribute (from DefaultUILanguage), which overrides for that subtree —
correct per the HTML spec for language inheritance.
* Drop deprecated UmbLocalizationManager.updateAll
It was public as an artifact of being an arrow function so it could be
passed to a MutationObserver without binding — not because it was
intended as part of the public API. External usage is effectively
zero, and the new explicit setActiveLanguage + notifyLanguageChanged
covers anyone who did reach for it.
* Docs: document active-language-on-host pattern in package-development.md
After PR #22822, the active UI language is driven by the shell elements
(<umb-app>, <umb-auth>) via their own lang attribute, not by <html lang>.
Document that so future contributors don't reach for the global.
* Collapse setActiveLanguage + notifyLanguageChanged into one method
The silent-write path is just `manager.documentLanguage = ...` — no new
method needed; the field is already public and was always writable. The
notify path keeps setActiveLanguage, which now both sets and notifies.
Net: one new public method on the manager instead of two.
* Inline the active-language write in the registry, drop setActiveLanguage
The previous version added setActiveLanguage on the manager as
a 'cleaner API' than direct field writes. But the manager's fields
(documentLanguage, documentDirection, connectedControllers) have
always been public, the registry is the only caller, and the wrapper
was just more public surface to maintain through the eventual
manager/registry collapse.
Net: -70 lines across the test file, no new public methods on the
manager, the registry pipeline writes the fields and iterates the
controllers directly where it would have called setActiveLanguage.
* Document that documentLanguage/Direction are read-only for consumers
Note in JSDoc that the only supported way to change the active language
is umbLocalizationRegistry.loadLanguage(). The fields stay writable for
the registry pipeline (cross-module internal); the comment is here so
the next contributor doesn't reach for them as a shortcut and end up
with the manager state out of sync with what's actually loaded.
* Blueprints: Fix UdiEntityTypeHelper.ToUmbracoObjectType() for document blueprint containers
Adds the missing DocumentBlueprintContainer case so the conversion is
symmetric with FromUmbracoObjectType().
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Add missing case for MemberTypeContainer.
* Use reflection to ensure other future missed cases are surfaced without having to explicitly extend the tests.
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Andy Butland <abutland73@gmail.com>
* Blueprints: Fix UdiEntityTypeHelper.ToUmbracoObjectType() for document blueprint containers
Adds the missing DocumentBlueprintContainer case so the conversion is
symmetric with FromUmbracoObjectType().
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Add missing case for MemberTypeContainer.
* Use reflection to ensure other future missed cases are surfaced without having to explicitly extend the tests.
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Andy Butland <abutland73@gmail.com>
* Add auto upgrade coordination for load balanced setups
* Add tests
* Apply suggestions from code review
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
* Potential fix for pull request finding
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
* fix(infrastructure): move TryBecomeLeaderAsync inside try/catch in UnattendedUpgradeBackgroundService
Ensures DB exceptions thrown during migration coordination set BootFailed
rather than faulting the background service silently.
* Fix feedback
* Update src/Umbraco.Infrastructure/Install/MigrationCoordinator.cs
Co-authored-by: Andy Butland <abutland73@gmail.com>
* Recheck state
* fix(tests): update concurrent race test for post-claim DetermineRuntimeLevel check
The winner now calls DetermineRuntimeLevel() once from the post-claim check
and must see Upgrading; the loser polls twice before seeing Run. Transition
the mock on the second call instead of the first.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Andy Butland <abutland73@gmail.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* migrate relation type table collection view to table kind
* update page locator
* Request relations when workspace unique is set
* fix types
* split models
* Potential fix for pull request finding
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
* Potential fix for pull request finding
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
* Use constant for relation type collection alias + remove redundant fields
* Add observer keys in relation-type workspace view
---------
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
* Cache cacheversion on scope
* Add tests
* Cache: Use ConcurrentDictionary for the inner per-scope version map
The inner Dictionary<string, Guid> was not thread-safe. Replacing it
with ConcurrentDictionary<string, Guid> removes the hidden assumption
that the root scope is only accessed from a single thread at a time.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Update src/Umbraco.Core/Cache/IRepositoryCacheVersionAccessor.cs
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Update tests/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Cache/RepositoryCacheVersionAccessorTests.cs
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Update src/Umbraco.Web.Common/Cache/RepositoryCacheVersionAccessor.cs
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Skips failing test so we can run nightly. THIS NEEDS TO BE REVERTED
* Revert "Skips failing test so we can run nightly. THIS NEEDS TO BE REVERTED"
This reverts commit c34d1736c336b3fcf7803b44e88f6018fa45c275.
* Only write version once pr. scope
* Add tests
* Remove unnececary locks
* Fix thread-safety: replace HashSet with ConcurrentHashSet and use GetOrAdd to eliminate TOCTOU races
* Add unit tests for RepositoryCacheVersionService
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Andreas Zerbst <andr317c@live.dk>
Mocks: Add missing signalR property to mock server configuration response
The GetServerConfigurationResponse type was updated in #22700 to require
a signalR.skipNegotiation property, but the MSW mock handler was not
updated to match, causing a tsc compilation error.
Mocks: Add missing signalR property to mock server configuration response
The GetServerConfigurationResponse type was updated in #22700 to require
a signalR.skipNegotiation property, but the MSW mock handler was not
updated to match, causing a tsc compilation error.
* Core: Preserve path case in ShadowFileSystem
ShadowFileSystem stored staged files at their original case via _sfs.AddFile
but tracked them under a lowercased key (NormPath calling ToLowerInvariant).
On Complete(), Inner.AddFile(kvp.Key, _sfs.GetFullPath(kvp.Key)) reconstructed
the staged file's path from the lowercased key, so on case-sensitive file
systems (Linux) File.Move failed with FileNotFoundException whenever a path
contained any uppercase character.
Drop the ToLowerInvariant from NormPath and switch the tracking dictionary
to StringComparer.OrdinalIgnoreCase. Lookups remain case-insensitive
(matching Windows semantics) while the stored key now matches what was
written to disk. IsChild/IsDescendant updated to OrdinalIgnoreCase
StartsWith for consistency.
Added regression test reproducing the original FileNotFoundException with
Views/PageNotFound.cshtml.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Rename regression test to follow Can_ naming convention
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Track canonical staged path per shadow node
The case-insensitive node dictionary preserved only the first inserted
key, so re-staging a logical path with a different case (e.g. AddFile
"Views/Foo.cshtml" then "views/foo.cshtml") wrote a phantom second file
to _sfs on Linux while Complete still resolved the original key — leaving
orphaned shadow files and committing stale content.
Track the original-case staged path on each ShadowNode and route all
_sfs operations (AddFile, OpenFile, GetFullPath, GetLastModified,
GetCreated, GetSize, MoveFile, Complete) through that canonical path.
Inner.AddFile on commit still uses the stored dictionary key, so the
destination case in the inner file system is unchanged.
Expanded the regression test to also exercise OpenFile, GetSize and
AddFile against a different-cased path, and to assert that the staged
file is written exactly once.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Make ShadowNode.CanonicalPath non-nullable
Every node now carries the original-case path it tracks, set at construction.
This removes the defensive 'sf.CanonicalPath ?? path' fallbacks at the read
sites (OpenFile, GetFullPath, GetLastModified, GetCreated, GetSize, Complete)
which were unreachable but noise.
The GetCanonicalPath helper is gone; AddFile and MoveFile now use the existing
node variable inline ('sf?.CanonicalPath ?? path' — node can legitimately be
null when staging a path for the first time).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Address Copilot review: normalize delete key, cross-platform test
DeleteDirectory(recursive=false) stored the deletion marker under the
caller-supplied path (which can contain backslashes) instead of the
normalized key, so a follow-up NormPath-based lookup could miss the
deletion and IsChild scans could become inconsistent. Use normPath.
The shadow-second-file assertion in the regression test used
File.Exists on a different-cased path; that returns true on
case-insensitive file systems (Windows / default macOS) regardless of
the actual stored case, so the assertion was platform-dependent.
Replaced it with a directory-count check that's cross-platform.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Add cross-platform regression test so any reversion would be caught on a non-case sensitive file system.
* Cleaned up warnings, obsoletions and comments in the existing tests.
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Andy Butland <abutland73@gmail.com>
(cherry picked from commit abfa8cb144)
* Core: Preserve path case in ShadowFileSystem
ShadowFileSystem stored staged files at their original case via _sfs.AddFile
but tracked them under a lowercased key (NormPath calling ToLowerInvariant).
On Complete(), Inner.AddFile(kvp.Key, _sfs.GetFullPath(kvp.Key)) reconstructed
the staged file's path from the lowercased key, so on case-sensitive file
systems (Linux) File.Move failed with FileNotFoundException whenever a path
contained any uppercase character.
Drop the ToLowerInvariant from NormPath and switch the tracking dictionary
to StringComparer.OrdinalIgnoreCase. Lookups remain case-insensitive
(matching Windows semantics) while the stored key now matches what was
written to disk. IsChild/IsDescendant updated to OrdinalIgnoreCase
StartsWith for consistency.
Added regression test reproducing the original FileNotFoundException with
Views/PageNotFound.cshtml.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Rename regression test to follow Can_ naming convention
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Track canonical staged path per shadow node
The case-insensitive node dictionary preserved only the first inserted
key, so re-staging a logical path with a different case (e.g. AddFile
"Views/Foo.cshtml" then "views/foo.cshtml") wrote a phantom second file
to _sfs on Linux while Complete still resolved the original key — leaving
orphaned shadow files and committing stale content.
Track the original-case staged path on each ShadowNode and route all
_sfs operations (AddFile, OpenFile, GetFullPath, GetLastModified,
GetCreated, GetSize, MoveFile, Complete) through that canonical path.
Inner.AddFile on commit still uses the stored dictionary key, so the
destination case in the inner file system is unchanged.
Expanded the regression test to also exercise OpenFile, GetSize and
AddFile against a different-cased path, and to assert that the staged
file is written exactly once.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Make ShadowNode.CanonicalPath non-nullable
Every node now carries the original-case path it tracks, set at construction.
This removes the defensive 'sf.CanonicalPath ?? path' fallbacks at the read
sites (OpenFile, GetFullPath, GetLastModified, GetCreated, GetSize, Complete)
which were unreachable but noise.
The GetCanonicalPath helper is gone; AddFile and MoveFile now use the existing
node variable inline ('sf?.CanonicalPath ?? path' — node can legitimately be
null when staging a path for the first time).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Address Copilot review: normalize delete key, cross-platform test
DeleteDirectory(recursive=false) stored the deletion marker under the
caller-supplied path (which can contain backslashes) instead of the
normalized key, so a follow-up NormPath-based lookup could miss the
deletion and IsChild scans could become inconsistent. Use normPath.
The shadow-second-file assertion in the regression test used
File.Exists on a different-cased path; that returns true on
case-insensitive file systems (Windows / default macOS) regardless of
the actual stored case, so the assertion was platform-dependent.
Replaced it with a directory-count check that's cross-platform.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Add cross-platform regression test so any reversion would be caught on a non-case sensitive file system.
* Cleaned up warnings, obsoletions and comments in the existing tests.
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Andy Butland <abutland73@gmail.com>
The publish cleanse step strips the prerelease suffix from hoisted dependency
ranges via `semver.minVersion(...).major/minor/patch`. For `^2.0.0-rc.1`
this produced `^2.0.0`, which no published `@umbraco-ui/uui` version
currently satisfies, breaking extension installs against
`@umbraco-cms/backoffice@18.0.0-beta1`+.
Use the full SemVer (including any prerelease) as the floor so
`^2.0.0-rc.1` stays satisfiable by the actual published rc.
* Preserve user-supplied property editor UI group names.
* Add support for localised property editor groups, and use localised values for all core property editors.
* Fixed check to look for '#' as the first character of the provided group name.
* danish translation
---------
Co-authored-by: Niels Lyngsø <niels.lyngso@gmail.com>
Co-authored-by: Niels Lyngsø <nsl@umbraco.dk>
* Mark ServerEventSender as distributed cache notification handler
* Batch and deduplicate notifications in ServerEventSender
* Introduce IDistributedCacheAsyncNotificationHandler<T> and use it in ServerEventSender
* Add ServerEventSender unit tests and address PR review feedback
* Mark ServerEventSender as distributed cache notification handler
* Batch and deduplicate notifications in ServerEventSender
* Introduce IDistributedCacheAsyncNotificationHandler<T> and use it in ServerEventSender
* Add ServerEventSender unit tests and address PR review feedback
* Updated locator for user group table
* Updated json builder for user groups permission due to element folder permission
* Updated api helper to match with element folder permission
* Updated tests and add comments for the failing tests
* Add submit button state to sort dialog.
* Guard against re-entrant submit in sort-children-of modal.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Set failed button state when sort-children-of submit throws.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
(cherry picked from commit dfe93c5639)
* Add submit button state to sort dialog.
* Guard against re-entrant submit in sort-children-of modal.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Set failed button state when sort-children-of submit throws.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Dont fail silently on missing ambientscope
This makes it in line with other methods in the repo
* Pass on Cancellationtoken to the job to support gracefull job shutdown
(cherry picked from commit 5ae17ace6a)
* Dont fail silently on missing ambientscope
This makes it in line with other methods in the repo
* Pass on Cancellationtoken to the job to support gracefull job shutdown
* Login: Reuse backoffice localization for canonical login_* keys (closes#56402)
The login screen no longer ships its own localization tree. The slim backoffice controller registers the backoffice's built-in localization manifests, so all login screen text resolves from the same dictionary the in-backoffice auth view uses. Translators override one place; both screens reflect it.
All consumers in the Login project moved from auth_* to login_*. The Login project's localization/ directory is removed entirely. The auth.* keys it used to ship (form labels, mfa, invite, password reset) now live under login.* in the backoffice's en/da/de/nb/nl/sv lang files. Other backoffice languages fall back to en for these keys, automatically extending the login screen's language coverage.
* Backoffice localization: drop server-only email keys, add login.setPasswordInstruction in en/da/nb/sv
bottomText, resetPasswordEmailCopySubject, resetPasswordEmailCopyFormat, mfaSecurityCodeSubject and mfaSecurityCodeBody are read only by the server's own localization layer — they were dead weight in every backoffice lang dictionary that carried them. Removed across 23 lang files.
login.setPasswordInstruction is rendered on the new-password screen via the now-canonical login_* namespace; it was missing from en (the fallback), da, nb and sv. Added there using the same translation tone as the existing de/nl entries.
* Login: Honour legacy auth_greeting* overrides with UmbDeprecation warning
Translation packages still shipping 'auth_greeting0..6' overrides keep working on both welcome screens (the standalone login page and the in-backoffice umb-auth-view): when an auth_* greeting is registered the consumer prefers it, otherwise the canonical login_* key is used. Each legacy key triggers a one-time UmbDeprecation warning pointing at the canonical name. Scheduled for removal in v20.
* Fix Prettier formatting and correct issue references in deprecation message
Addresses Copilot review feedback on PR #22743:
- Run Prettier on the 6 backoffice lang files I added keys to (en/da/de/nb/nl/sv); the new entries used double quotes which violated the repo's singleQuote: true config and would have failed the format check.
- Update the UmbDeprecation 'solution' link and the inline source comments from #56402 (an ADO work item id) to #20082 (the actual GitHub issue tracking this work).
* Drop stale login_2fa* and login_mfaSecurityCodeMessage from bs.ts and cy.ts
Surfaced by 'devops/localization/compare-languages.js': bs and cy were the only lang files shipping these keys, and they have no en counterpart. The login_2fa* set is leftover from before the codebase renamed 2fa → mfa in the login flow (the live keys are login_mfa*). login_mfaSecurityCodeMessage is server-side only, like the other email-template keys cleaned up in 53ad52702e0. None of these are referenced anywhere in src/. The user-facing user_2fa* keys (consumed by current-user-mfa modals) are unrelated and untouched.
* Drop dead login_2fa* and login_mfaSecurityCodeMessage from nl, hr, tr
Same pattern as 26bc6211d27 (bs/cy cleanup), surfaced by re-running devops/localization/compare-languages.js after the previous pass:
- nl had both legacy 'login_2fa*' AND the canonical 'login_mfa*' (added in commit 1) sitting side by side after the auth.* → login.* port. Six true duplicates dropped, login_mfa* kept.
- hr and tr shipped legacy 'login_2fa*' that have no en counterpart, no consumer in src/, and no mfa pair locally. Dropped to align with en (the source of truth — every other locale should match it).
- All three files also still carried 'login_mfaSecurityCodeMessage' from the same family of server-side email-template keys cleaned up in 53ad52702e0; removed too.
user_2fa* / member_2fa keys are unrelated and untouched (consumed by current-user-mfa modals).
---------
Co-authored-by: leekelleher <leekelleher@gmail.com>
* Login: Consume sibling Umbraco.Web.UI.Client by source for v18 parity
The Login project previously depended on the published `@umbraco-cms/backoffice@^17.3.4` npm package for types, while at runtime the importmap served the in-repo v18 backoffice. The version mismatch forced `as any` workarounds and masked real API drift. Since v18 (with UUI 2.0) isn't on npm yet, switch Login to consume the sibling Client via a local `file:` dep so types and runtime align on v18.
Changes:
- Login `package.json`: `@umbraco-cms/backoffice` → `file:../Umbraco.Web.UI.Client`; added `pre{build,dev,watch}` hooks that run a guard script to fail fast when Client's `dist-cms/` is missing.
- Login `scripts/ensure-client-built.mjs`: new guard with a clear "build the Client first" message.
- Login `CLAUDE.md`: documents the contract and build ordering.
- StaticAssets `.csproj`: `BuildLogin` now depends on `BuildBackoffice` so MSBuild (and therefore the Azure pipeline) builds Client before Login automatically.
- Client `src/tsconfig.build.json`: `declaration: true` so `dist-cms/` ships `.d.ts`.
- Client `package.json`: new `build:types` step (`tsc --emitDeclarationOnly --incremental false && tsc-alias`) wired into `build:for:cms` after `build:workspaces`. Vite workspaces wipe their output dirs before rebuilding JS, stripping the tsc-emitted declarations; re-emitting after workspaces restores them. `tsc-alias` rewrites Client-internal path aliases (e.g. `@umbraco-cms/backoffice/external/lit`) to relative paths so sibling consumers can resolve them.
- `copy-to-cms.js`: filter `.d.ts` and `.tsbuildinfo` from the copy to `wwwroot/umbraco/backoffice` — they're only needed by sibling projects consuming `dist-cms` for types, not at runtime.
- `src/external/uui/vite.config.ts`: set `treeshake: false` so per-component `defineElement()` side-effect calls (used by UUI 2.0 for custom-element registration) are preserved in the bundle. Without this, `<uui-button>` etc. never register and the login screen renders empty controls.
- `src/external/uui/index.ts`: bare `import '@umbraco-ui/uui'` to make the side-effect intent explicit.
- Small v18-compat fixes for `Object.groupBy` (TS 8 types): removed stale `@ts-expect-error`, switched to `Object.entries` + `?? []` to satisfy the `Partial<Record>` return type.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Address review feedback and fix CI
- Add `ignoreDeprecations: "6.0"` to `tsconfig.json` and the tsconfig generator to silence the TS 6.0 warning about the implicit baseUrl that TypeScript assigns when `paths` is declared. This was the CI `build` failure. The generator is also synced with the user's es2022 → es2024 bump.
- Drop the now-redundant `--declaration` flag from `build:for:npm` (tsconfig.build.json now has `declaration: true`, so the flag was duplicating intent).
- Align Login's `engines` with the Client's (`node >=24.13`, `npm >=11`) so `file:` install doesn't trip EBADENGINE.
- Guard script: hardcode the relative "../Umbraco.Web.UI.Client" path in the error message instead of interpolating the absolute path, which overflowed the ASCII box in CI logs.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Login: update CLAUDE.md Node/npm versions to match engines
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* check-path-length: skip .d.ts/.tsbuildinfo and directory paths
The 120-char Windows MAX_PATH guard protects files that actually ship to
CMS installs. `.d.ts` and `.tsbuildinfo` live in `dist-cms/` for sibling
projects to consume as types and are filtered out by `copy-to-cms.js`
before reaching `wwwroot/umbraco/backoffice` — they never land on a
Windows CMS install. Directories on their own also don't trigger
MAX_PATH; only files within them do, and those are still checked.
Unblocks CI after enabling `declaration: true` in the Client build.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* check-path-length: extract exceedsPathLimit helper (CodeScene)
Decomposes the complex conditional flagged by CodeScene into a named
predicate with a docstring, clarifying when a path is reported.
* Login: switch to generated tsconfig paths; revert dist-cms type machinery
PR #22591 originally aligned Login's TypeScript types with the in-repo v18
backoffice by emitting `.d.ts` into Client's `dist-cms/` and consuming it
via a `file:` dep. That layered six side-effects across the Client build
(declaration: true, build:types step, tsc-alias in postbuild, copy-to-cms
filter, check:paths skip, MSBuild ordering). Reviewers pushed back.
This rework moves the type contract from "ship .d.ts in dist-cms" to
"point Login's tsconfig paths at Client's TypeScript source" — Login's
runtime behaviour is unchanged (vite still externalises /^@umbraco-cms/,
host importmap still serves the JS), only the type-resolution mechanism
swaps.
What's reverted (back to the pre-PR shape):
- src/Umbraco.Web.UI.Client/src/tsconfig.build.json: declaration: false
- src/Umbraco.Web.UI.Client/package.json: drops `build:types` script,
reverts `postbuild` to global-types only, drops `--declaration` from
the tsc CLI in `build:for:cms` and restores it in `build:for:npm`
- src/Umbraco.Web.UI.Client/devops/build/copy-to-cms.js: simple cpSync
- src/Umbraco.Web.UI.Client/devops/build/check-path-length.js: original
- src/Umbraco.Web.UI.Client/tsconfig.json + devops/tsconfig/index.js:
drops `ignoreDeprecations` (not needed once baseUrl is gone)
- src/Umbraco.Cms.StaticAssets/Umbraco.Cms.StaticAssets.csproj:
`BuildLogin` no longer depends on `BuildBackoffice`
What's new on the Login side:
- src/Umbraco.Web.UI.Login/devops/tsconfig/index.js: generator that
reads Client's `package.json` exports and emits a full `tsconfig.json`
with `paths` mapping every `@umbraco-cms/backoffice/<sub>` to
`../Umbraco.Web.UI.Client/src/.../index.ts`. Mirrors Client's existing
generator pattern (DON'T EDIT header, JSON.stringify with tabs).
- src/Umbraco.Web.UI.Login/tsconfig.json: regenerated; standalone `tsc`
works (no `--project` needed) and 140 path aliases resolve types
directly from Client's source.
- src/Umbraco.Web.UI.Login/package.json: drops `@umbraco-cms/backoffice`
npm dep entirely (file: was only nominal — types come via paths,
runtime via importmap, transitives via Client's own `node_modules`
which is `npm install`-ed by CI's backoffice-install.yml). Replaces
the `ensure-client-built` guard with the generator on `pre*` hooks
and adds `generate:tsconfig` for ad-hoc invocation.
- src/Umbraco.Web.UI.Login/CLAUDE.md: documents the new layered
contract (paths/externalisation/importmap) and the install-Client-
before-Login prerequisite.
- src/Umbraco.Web.UI.Login/scripts/ensure-client-built.mjs: deleted.
What stays from the original PR (independent fixes):
- src/Umbraco.Web.UI.Client/src/external/uui/{vite.config.ts,index.ts}:
`treeshake: false` + bare side-effect import — keeps UUI 2.0
per-component `defineElement` calls in the bundle so `<uui-button>`
etc. actually register.
- Object.groupBy cleanups in 6 element files (TS 8 type narrowing).
- Client tsconfig generator: target/lib bumped to ES2024, `baseUrl`
removed.
Verified locally:
- `cd Client && rm -rf dist-cms && cd ../Login && npx tsc` → clean
(proves Login compiles without Client's dist-cms)
- `cd Client && npm run build:for:cms` → 0 emitted .d.ts (back to
pre-PR shape), `check:paths` passes
- Login `npm run build` → 64 KB bundle (unchanged)
- Browser at https://localhost:44339/umbraco: UUI 2.0 components
render, login with `test@umbraco.com`/`test123456` succeeds and
redirects to /umbraco/section/content
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Login: address review — idempotent generator + correct MSBuild ordering
- StaticAssets.csproj: BuildLogin now depends on RestoreBackoffice (not
BuildBackoffice — Login doesn't need dist-cms types). Login's tsc walks
Client source via tsconfig path aliases and resolves transitive deps
(lit, rxjs, …) from Client's node_modules. Without this dependency a
fresh local `dotnet build` could run BuildLogin before Client is
installed; CI was already safe via backoffice-install.yml's npm ci.
- devops/tsconfig/index.js: skip rewrite when content is unchanged. Pre-
hooks ran the generator on every npm command and bumped tsconfig.json
mtime even when nothing changed, which can invalidate caches and rattle
watchers downstream. Read-then-compare-then-write makes the generator
truly idempotent.
- devops/tsconfig/index.js: derive the alias prefix from
`clientPkg.name` instead of hardcoding `@umbraco-cms/backoffice` so a
package rename can't silently break paths.
azure-pipelines.yml needs no changes — backoffice-install.yml already
runs `npm ci` in Client before dotnet build kicks in MSBuild.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Login: postinstall + dev-mode Vite alias + theme CSS path
Audit cleanup pass on the rework:
- Login package.json: collapse predev/prebuild/prewatch into a single
postinstall hook. The generator runs whenever npm install/ci runs
(locally + in CI via RestoreLogin's npm i + the dotnet build chain).
Removes the per-command "tsconfig.json already up to date" noise.
- Login vite.config.ts: in dev mode (`vite serve`), read `paths` from
the generated tsconfig.json and apply them as `resolve.alias` so Vite
can resolve `@umbraco-cms/backoffice/*` to Client source. Vite doesn't
honor tsconfig `paths` natively — without this `npm run dev` failed
with "Failed to resolve import @umbraco-cms/backoffice/utils ...".
Build mode (`vite build`) still externalises the namespace via the
unchanged rollupOptions.external regex; alias is dev-only.
- Login index.html: UUI 2.0 reorganised CSS — the old
`@umbraco-ui/uui-css/dist/uui-css.css` path no longer exists. Point
at `@umbraco-ui/uui/dist/themes/light.css` which is what Client now
ships. Path is relative through Client's node_modules since Login no
longer declares a UUI dep itself.
- Client input-entity-user-permission.element.ts: prettier flagged a
multi-line .map() arrow that should be inline; collapse to one line.
- Login CLAUDE.md: document the postinstall-driven generator.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Use Vite 8 native tsconfigPaths; drop helper plugin and trim comments
- Both vite.config.ts files use `resolve.tsconfigPaths: true` instead of the
`vite-tsconfig-paths` plugin. Plugin and dep removed.
- Trim explanatory comments on csproj target, generator, UUI vite config and
external/uui/index.ts to conclusions only.
* Login: tsconfig generator fails fast on unsupported exports shapes
Distinguish between the legitimate `.` self-reference (target === null) and
unexpected non-string targets (e.g., conditional exports objects). The latter
now throw with a clear message instead of being silently dropped from `paths`,
which would otherwise produce confusing 'Cannot find module' errors at tsc
time later.
* Login: allow Vite dev server to serve Client's UUI assets
The light.css imported from Client's node_modules pulls Lato fonts via
relative URL, which Vite refuses by default since they sit outside
Login's project root. Extend server.fs.allow to the parent directory
(both sibling projects).
* Client: regenerate tsconfig on postinstall
* Login: keep UUI registrations in dev mode
Vite 8's esbuild dep pre-bundle drops the per-component
`customElements.define()` side-effects in @umbraco-ui/uui (a known UUI
issue with Vite 8). Exclude UUI from optimizeDeps so it's served
unbundled in dev. Re-add the bare side-effect import in external/uui
so the entry module evaluates the chain. Production build is unaffected
(workspace's `treeshake: false` already preserves registrations).
Also document the new MSBuild Login targets in StaticAssets CLAUDE.md.
* Login: clarify why optimizeDeps.exclude is needed for UUI
Tested treeshake.moduleSideEffects: true in optimizeDeps.rollupOptions
on Vite 8 / Rolldown 1.0.0-rc.17 — registrations still get stripped.
Excluding the package from the pre-bundle is the only reliable workaround
until UUI's own Vite 8 upgrade lands. Comment captures the conclusion.
* Roll back Vite 8 → 7 in Client and Login
Vite 8.0.10 ships Rolldown 1.0.0-rc.17 which strips UUI 2.0
`customElements.define()` side-effects during dep pre-bundle, leaving
elements unregistered in dev mode. Rather than ship a v18 release tied
to a non-final Rolldown RC, revert the Vite bump and pick it up again
once Rolldown 1.0 final lands.
Changes:
- Client: vite ^8.0.10 → ^7.3.2; vite-plugin-static-copy ^4.1.0 → ^3.2.0;
re-add vite-tsconfig-paths plugin; drop native `resolve.tsconfigPaths`.
- Login: vite ^8.0.10 → ^7.3.2; add vite-tsconfig-paths; configure plugin
with `projects: ['./tsconfig.json', '../Umbraco.Web.UI.Client/tsconfig.json']`
so it can resolve `@umbraco-cms/backoffice/*` imports inside Client
source files (which would otherwise lack a discoverable tsconfig in
Login's project tree). Drop `optimizeDeps.exclude` (no longer needed
without Rolldown). Keep `server.fs.allow` for the cross-project font.
TypeScript 6 + ES2024 + tsconfig path generator + Login architectural
pivot all stay — those are independent of the Vite version.
Verified:
- Production https://localhost:44339/umbraco — login works
- Login dev http://localhost:5191/ — UUI registers, all custom elements defined
- Client dev http://localhost:5192/ — page loads, navigates to /section/content
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Address Copilot review
- vite.config.ts (Login): narrow server.fs.allow from the parent dir to
Login + Client only, reducing the dev server's read scope.
- external/uui/vite.config.ts (Client): replace blanket `treeshake: false`
with `moduleSideEffects: (id) => id.includes('@umbraco-ui/uui')` so
Rollup keeps UUI's per-component registration calls but tree-shakes the
rest. Bundle stays at 516 KB / 96 registered tags.
* fix merge overwrites
* update package lock
* fix: do not autogenerate tsconfig on postinstall
* removes postinstall script
* chore: generates tsconfig
* chore: update lockfile
* docs: updates claude.md
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Niels Lyngsø <niels.lyngso@gmail.com>
* Auth: un-deprecates getLatestToken and routes per-request fetches through it
getLatestToken is the only public API for "wait for any in-flight refresh,
trigger one if the access token has expired, then return". External and
internal consumers were warned off it without an equivalent replacement:
configureClient only helps @hey-api/openapi-ts clients, and consumers using
axios/ky/native fetch had no other gate.
- Removes the @deprecated JSDoc + UmbDeprecation.warn() call so the public
surface no longer prints a console warning per call.
- Uses getLatestToken.bind(this) for the auth callback inside configureClient
and the token callback inside getOpenApiConfiguration so both paths share
the same #ensureTokenReady gate.
- Replaces the hard-coded `Authorization: Bearer [redacted]` in unlinkLogin
and #makeLinkTokenRequest with `Bearer ${await getLatestToken()}` so those
fetches participate in the refresh coordination rather than firing with a
potentially-revoked cookie.
Also wires the UmbracoExtension template's entrypoint to call
authContext.configureClient(client), matching the v18 template change. The
framework awaits onInit, so this guarantees the API client is fully
configured before any element in the extension can use it.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Auth: tightens UmbAuthContext correctness and accepts any hey-api client
Pulls in a batch of non-breaking improvements to UmbAuthContext that came
out of an audit on the back of the un-deprecation work in this PR:
Public surface:
- configureClient(client) now accepts a new structural UmbApiClient type
(exported from @umbraco-cms/backoffice/http-client). Each @hey-api/openapi-ts
generation produces a fully-bound Client<…>; the backoffice's umbHttpClient
and an extension's regenerated client are structurally identical but TS
treats them as distinct generic instantiations. The widened parameter lets
extensions wire their own client without `as never` casts at call sites.
bindDefaultInterceptors keeps its strict typeof umbHttpClient parameter
(preserving autocomplete inside interceptor callbacks); the cast happens
once, internally.
Correctness:
- The auth context now holds a single UmbApiInterceptorController, lazy-
initialised on first configureClient() call. Previously each call
instantiated a new controller, which re-provided the UmbAuthSignalerContext
on the host and stacked listeners — visible the moment an extension also
called configureClient. One controller for the lifetime of the host, all
configured clients share it.
- completeAuthorizationRequest checks sessionStorage before asking
window.opener for the PKCE verifier. The previous order hung for the full
postMessage timeout whenever oauth_complete loaded with a non-OAuth
window.opener (which is set for ANY window.open target). The opener
postMessage timeout is also dropped from 5s to 1.5s — a real popup parent
responds within milliseconds; longer is just wait time for the unrelated-
opener case.
- The cross-tab 'authorized' BroadcastChannel handler now routes through
#setSessionLocally so the timestamp math stays in one place. The
'sessionUpdate' handler still applies pre-computed timestamps directly
(peer broadcast already did the math) but does so inside the
#inSessionUpdateCallback guard, so a synchronous session$ observer can no
longer trigger a spurious /token refresh on top of a peer's update.
- #ensureTokenReady drops its query-then-request pattern. Now always queues
behind the umb:token-refresh lock with a no-op callback — if the lock is
free it acquires immediately, if held it waits. Eliminates the race window
between query() and request().
- destroy() invokes #popupCleanup before tearing down so an in-flight popup
flow's window-level message listener and closed-poll interval don't leak
past the context's lifetime. The cleanup helper itself now resolves the
popup-flow Promise — every termination path (authorized, popup closed,
superseded by a new flow, context destroyed) is observable to the awaiter
instead of hanging forever.
Cleanup:
- makeAuthorizationRequest is annotated Promise<void> so the redirect and
popup branches share an explicit return type.
- unlinkLogin wraps the parsed problem-details payload in a real Error (with
the original payload exposed on `.cause`) so callers using `instanceof
Error` or expecting a stack trace get sane behaviour.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Auth: un-deprecates getLatestToken and routes per-request fetches through it
getLatestToken is the only public API for "wait for any in-flight refresh,
trigger one if the access token has expired, then return". External and
internal consumers were warned off it without an equivalent replacement:
configureClient only helps @hey-api/openapi-ts clients, and consumers using
axios/ky/native fetch had no other gate.
- Removes the @deprecated JSDoc + UmbDeprecation.warn() call so the public
surface no longer prints a console warning per call.
- Uses getLatestToken.bind(this) for the auth callback inside configureClient
and the token callback inside getOpenApiConfiguration so both paths share
the same #ensureTokenReady gate.
- Replaces the hard-coded `Authorization: Bearer [redacted]` in unlinkLogin
and #makeLinkTokenRequest with `Bearer ${await getLatestToken()}` so those
fetches participate in the refresh coordination rather than firing with a
potentially-revoked cookie.
Also wires the UmbracoExtension template's entrypoint to call
authContext.configureClient(client), matching the v18 template change. The
framework awaits onInit, so this guarantees the API client is fully
configured before any element in the extension can use it.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Auth: tightens UmbAuthContext correctness and accepts any hey-api client
Pulls in a batch of non-breaking improvements to UmbAuthContext that came
out of an audit on the back of the un-deprecation work in this PR:
Public surface:
- configureClient(client) now accepts a new structural UmbApiClient type
(exported from @umbraco-cms/backoffice/http-client). Each @hey-api/openapi-ts
generation produces a fully-bound Client<…>; the backoffice's umbHttpClient
and an extension's regenerated client are structurally identical but TS
treats them as distinct generic instantiations. The widened parameter lets
extensions wire their own client without `as never` casts at call sites.
bindDefaultInterceptors keeps its strict typeof umbHttpClient parameter
(preserving autocomplete inside interceptor callbacks); the cast happens
once, internally.
Correctness:
- The auth context now holds a single UmbApiInterceptorController, lazy-
initialised on first configureClient() call. Previously each call
instantiated a new controller, which re-provided the UmbAuthSignalerContext
on the host and stacked listeners — visible the moment an extension also
called configureClient. One controller for the lifetime of the host, all
configured clients share it.
- completeAuthorizationRequest checks sessionStorage before asking
window.opener for the PKCE verifier. The previous order hung for the full
postMessage timeout whenever oauth_complete loaded with a non-OAuth
window.opener (which is set for ANY window.open target). The opener
postMessage timeout is also dropped from 5s to 1.5s — a real popup parent
responds within milliseconds; longer is just wait time for the unrelated-
opener case.
- The cross-tab 'authorized' BroadcastChannel handler now routes through
#setSessionLocally so the timestamp math stays in one place. The
'sessionUpdate' handler still applies pre-computed timestamps directly
(peer broadcast already did the math) but does so inside the
#inSessionUpdateCallback guard, so a synchronous session$ observer can no
longer trigger a spurious /token refresh on top of a peer's update.
- #ensureTokenReady drops its query-then-request pattern. Now always queues
behind the umb:token-refresh lock with a no-op callback — if the lock is
free it acquires immediately, if held it waits. Eliminates the race window
between query() and request().
- destroy() invokes #popupCleanup before tearing down so an in-flight popup
flow's window-level message listener and closed-poll interval don't leak
past the context's lifetime. The cleanup helper itself now resolves the
popup-flow Promise — every termination path (authorized, popup closed,
superseded by a new flow, context destroyed) is observable to the awaiter
instead of hanging forever.
Cleanup:
- makeAuthorizationRequest is annotated Promise<void> so the redirect and
popup branches share an explicit return type.
- unlinkLogin wraps the parsed problem-details payload in a real Error (with
the original payload exposed on `.cause`) so callers using `instanceof
Error` or expecting a stack trace get sane behaviour.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Client: Aliased `DocumentVariantStateModel` for documents and document-blueprints packages
Hoist `UmbDocumentVariantState` and `UmbDocumentBlueprintVariantState` aliases (re-exporting `DocumentVariantStateModel`) into dedicated `variant-state.ts` leaf files. Internal package modules, mocks and the core split-view selector now consume the alias instead of referencing `DocumentVariantStateModel` directly, mirroring the structure on `v18/dev` to reduce upstream-merge conflicts.
* Revert mock data changes
to prevent importing the whole "document" module.
* Tweaked the `DocumentVariantStateModel` import for mock data
Otherwise this is problematic for cherry-picked commits for v18.0.
* Missed one!
`elementStartNodeIds` and `hasElementRootAccess` were added to
`UmbCurrentUserModel` by the Global Elements PR but the documents mock
data set was created without them, causing `undefined.map()` errors in
the document workspace CRUD tests.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Update stored color label if changed on save of document with color picker.
* Clarify intent of change event dispatch in label sync
* Make comparison case insensitive.
* Added unit tests for new behaviour.
* Order SQL before FetchOneToMany in dictionary entry retrieval to prevent duplicate items in collection view.
* Used PrimaryKey instead of UniqueId to take advantage of the clustered index.
* extend icons with information from theseaurus
* implement new icon search logic
* clean-up data
* icon manager
* sorting with a backup of the name
* refactor into a controller
* improve multi word group search
* embed lucide data
* rename tech into technology
* remove paper from dollar
* Potential fix for pull request finding
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
* Potential fix for pull request finding
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
* improve search
* related should not show up in search
* update threshold
* separate name words
* also consider full icon name match
* better comment
* other approach for full name matches
* full icon name search if query contains a -
* fix test
* remove related code
* updates to related
* make its own package
* revert changes
* update tsconfig
* package-lock
---------
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
* temp mock set
* test getPropertyValue
* Extend document workspace context tests to cover read/write property values
* move context files into context folder
* Add document CRUD tests, mock handler & interceptor
* temp mock error interceptor
* Return 404 when document not found
* Use undefined for entity unique state until initialized
* Fix import paths for document workspace editor
* Add test utils and extend document workspace tests
* Update document-workspace-context.test-utils.ts
* Match invariant variant when variantId missing
* Ensure finishPropertyValueChange runs on exit
Wrap setPropertyValue implementation in a try/finally and move finishPropertyValueChange into the finally block so cleanup always runs even if an error is thrown. No other functional changes — code was re-indented and organized but behavior remains the same except for guaranteed cleanup on error.
* Require variantId for culture/segment-variant props
* fix types
* fix mock modal typescript error
* Distinguish unloaded vs root entity unique
* use the real current user context
* hide mock set in UI
* rename mock set
* Move initiatePropertyValueChange into try
* Use 'satisfies' for UmbMockDataSet assertions
* Preserve requested unique on failed load
* Treat missing variantId as invariant
* Reset update lock on destroy
* remove unused group + user
* Guard _current.unmute and remove destroy override
* Add tests for element data manager
* Guard subject access and add destroy test
* Throw when calling methods after destroy
Introduce UmbVisualEditorPreviewContext to provide UMB_PREVIEW_CONTEXT for
previewApp extensions inside the visual editor. Add a bottom menu bar with
extension slot for preview apps. Consolidate block data update functions into
a single updateBlockDataValues helper and extract removeLayoutEntryFromAreas
to the shared block utils.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Extract duplicated outline/shadow style literals into named constants
- Extract duplicated drag-event guard patterns into helper functions
(isDragOverChildArea, isDragOverNestedBlock)
- Remove dead #save() and #saveAndRefresh() methods and empty else branches
- Remove deprecated findLayoutEntryRecursive re-export (no consumers)
- Remove unused UmbBlockWorkspaceOriginData import, use type-only import
for UmbBlockManagerContext
- Use IBackOfficePathGenerator.BackOfficeAssetsPath instead of hardcoded
"/backoffice" path segment in tag helper
- Extract #getAppearanceDefaults() helper in property settings view to
avoid spread-with-missing-fields across appearance toggle handlers
- Make editableInVisualEditor required (not optional) in appearance model
with false default, fix mock data across document/media/member types
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add starter kit package to Web.UI for visual editor testing.
Includes regenerated OpenAPI spec and SDK types reflecting the
new EditableInVisualEditor property on PropertyTypeAppearance.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Fix guest script path (backoffice path was missing /backoffice segment)
- Use Lucide icons matching backoffice style for edit/delete action bars
- Consistent editable region styling: dashed blue outline with white
inner shadow for visibility on both light and dark backgrounds
- Smooth 120ms transitions on hover/select state changes
- Fix cross-area drag-and-drop in nested block grids:
- Stop dragstart propagation to prevent parent block hijacking drag
- Skip block dragover/drop when cursor is over child areas
- Fix area drop target check to not bail on parent block ancestor
- Fix empty area placeholder not hiding after block drop
- Use visual editor property modal for block editing instead of
standard block workspace (which requires missing entries context)
- Remove auto-save on every edit — workspace state updates only,
user saves when ready via workspace footer
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add a per-property toggle that controls whether a property is editable
in the visual editor. Replaces the hard-coded editor-alias convention
(TextBox, TextArea, RichText, MarkdownEditor) with a configurable setting.
Full stack implementation:
- Core: IPropertyType, PropertyType, IPublishedPropertyType, PublishedPropertyType
- API: PropertyTypeAppearance DTO, mapping, presentation factory
- Infrastructure: DB DTO, mapper, factory, repository, migration (v17.4.0)
- Frontend: TypeScript model, toggle in property type settings (Visual Editor box),
workspace context default, localization keys
- Annotation pipeline: TrackVisualEditorAccess now checks EditableInVisualEditor
instead of hard-coded editor alias list
Uses opt-out model for blocks: if no properties on an element type have the
flag explicitly enabled, all properties are included in the editing modal.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Move shared state and methods from Block Grid, List, and Single manager
contexts into the base UmbBlockManagerContext: inlineEditingMode,
isSortMode, default createWithPresets(), and default insert().
Block List and Single managers are now near-empty subclasses. Block Grid
and RTE keep their overrides for area-aware layout and custom insert logic.
Also extracts shared block layout area utilities and adds index to the
base UmbBlockWorkspaceOriginData interface.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Change VisualEditorScriptTagHelperComponent registration from Transient
to Scoped since it depends on request-scoped state, and update the
remarks XML doc to remove the stale reference to WriteUmbracoContent.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Move the guest script injection from UmbracoViewPage.WriteUmbracoContent()
into a dedicated VisualEditorScriptTagHelperComponent, using the standard
ASP.NET Core ITagHelperComponent extensibility point for body tag injection.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Replace 'Umbraco.BlockList' magic string with
UMB_BLOCK_LIST_PROPERTY_EDITOR_SCHEMA_ALIAS constant
- Remove duplicate #findLayoutRecursive from VisualEditorBlockEntries,
reuse exported findLayoutEntryRecursive from block helper
- Cache #resolveBlockPropertyStructures results to avoid repeated
DocumentTypeService API calls for the same content type
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Wire up the block catalogue modal's clipboard tab so blocks can be
pasted from the clipboard into the visual editor. Uses the paste
translator pipeline and property value cloner to resolve, translate,
and clone clipboard entries into block values with fresh unique keys.
Pasted blocks are exposed as invariant so they render immediately.
Also adds mergeBlockValueInto helper and changes workspace view icon.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Fix CSS selector scoping bug in injected.ts where `:scope >` only
applied to the first part of a comma-separated selector, causing
add-block buttons to be misplaced in nested grid containers
- Add recursive layout search in block bridge so blocks nested inside
grid areas can be found by layoutOf and updated in-place by
setOneLayout without being duplicated to the root level
- Add recursive layout removal in block helper so deleting a block
inside a grid area removes the layout entry from the correct level
- Add confirm modal before block deletion matching the standard
block editor pattern (blockEditor_confirmDeleteBlockTitle)
- Remove debug console.log/console.debug statements
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
The block workspace modal route registration is async (consumes
UMB_ROUTE_CONTEXT), so the workspace path may not be available
immediately after bridge construction. Make openEdit/openCreate async
and wait for the path. Also add missing originData to the modal setup
data so submit() doesn't throw.
https://claude.ai/code/session_01NE6gfQjJYX9LapGFXFY7CU
Two issues preventing the block workspace from rendering properties:
1. The workspace context's #gotManager() observes manager.variantId
and early-returns if it's undefined. Without a variantId, the
workspace never sets its own #variantId, so _workspaceVariantId
stays undefined and the view renders nothing. Fix: always set a
variantId on the manager, defaulting to UmbVariantId.CreateInvariant()
when no variant context is available.
2. The edit path was missing /view/content suffix. The standard block
entry navigates to {path}edit/{key}/view/content so the workspace's
internal router matches the content view. Without this, the
workspace editor's router may not correctly route to the content
view where #setStructureManager is called.
https://claude.ai/code/session_01NE6gfQjJYX9LapGFXFY7CU
Grid area support:
- VisualEditorBlockManager.setOneLayout() now detects parentUnique +
areaKey in origin data and recursively walks the layout tree to
insert into the correct area (mirrors UmbBlockGridManagerContext)
- Uses appendToFrozenArray/pushAtToUniqueArray for immutable frozen
array updates
- Falls back to root-level insertion if parent block not found
Variant context:
- Bridge accepts optional UmbVariantId in config and exposes
setVariantId() for live updates
- Visual editor element consumes UMB_VARIANT_CONTEXT and observes
displayVariantId, forwarding it to the active bridge
- Manager receives the variant ID so new block expose entries get
the correct culture/segment
https://claude.ai/code/session_01NE6gfQjJYX9LapGFXFY7CU
Add VisualEditorBlockBridge — a controller that creates a per-property
block manager + entries context so the visual editor can open the
standard block workspace modal for editing blocks.
The bridge:
- Creates a concrete UmbBlockManagerContext subclass that provides
UMB_BLOCK_MANAGER_CONTEXT on the host element
- Creates a concrete UmbBlockEntriesContext subclass that provides
UMB_BLOCK_ENTRIES_CONTEXT for the workspace to consume
- Initializes both with the property's current block value
- Registers a workspace modal route
- Observes manager state changes and syncs back via callback
The visual editor element now uses the bridge when a block is clicked,
opening the standard block workspace instead of the custom property
modal. This gives blocks full access to the workspace editing
experience including nested blocks, validation, and live sync.
Also includes the contentTypeHasProperties data-passing fix from the
previous commit for the catalogue modal.
https://claude.ai/code/session_01NE6gfQjJYX9LapGFXFY7CU
The block catalogue modal needs to know which block types have editable
properties to show workspace links. Normally this comes from
UMB_BLOCK_MANAGER_CONTEXT, but the visual editor operates outside
the property editor DOM tree where that context lives.
Add an optional contentTypeHasProperties map to UmbBlockCatalogueModalData
so the visual editor can pass this info directly. The modal uses the
manager context when available, falling back to the data map.
https://claude.ai/code/session_01NE6gfQjJYX9LapGFXFY7CU
The catalogue modal gated all rendering on _manager being defined, which
meant it rendered nothing when opened from contexts that don't provide
UMB_BLOCK_MANAGER_CONTEXT (e.g. the visual editor). The manager is only
actually needed for getContentTypeHasProperties() on the block type card
href — make that optional instead of blocking the entire modal.
https://claude.ai/code/session_01NE6gfQjJYX9LapGFXFY7CU
The capture-phase click handler in the guest script was intercepting
clicks on "Add content" buttons — target.closest(ALL_SELECTOR) matched
the parent block element, swallowing the event before the button handler
fired. Added a guard to skip clicks inside [data-umb-add-block] elements.
Replaced non-routed umbOpenModal calls for the block catalogue with a
proper UmbModalRouteRegistrationController so umb-property can resolve
its dependencies through the routing context.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-19 07:15:49 +00:00
607 changed files with 25609 additions and 5568 deletions
file_header_template=Copyright (c) Umbraco.\nSee LICENSE for more details.
# SA1636: File header copyright text should match
# Justification: .editorconfig supports file headers. If this is changed to a value other than "none", a stylecop.json file will need to added to the project.
description:"Please write the *exact* version, example: `10.1.0`. Use the help icon in the Umbraco backoffice to find the version you're using"
description:"Please write the *exact* version, example: `10.1.0`. Click the Umbraco logo in the top left corner of the backoffice to find the version you're using."
@@ -448,6 +448,14 @@ When a PR changes Management API controllers or models, the `OpenApi.json` file
The backoffice is published to npm as `@umbraco-cms/backoffice`. Runtime dependencies are provided via importmap; npm peerDependencies provide types only. For full details on dependency hoisting, version range logic, and plugin development, see `/src/Umbraco.Web.UI.Client/CLAUDE.md` → "npm Package Publishing".
### SQL Server 2100-parameter limit
Any `WHERE IN (@0, @1, ...)` built from a runtime-sized collection risks hitting SQL Server's 2100-parameter ceiling and throwing `SqlException` 8003 in production.
Batch with `IEnumerable<T>.InGroupsOf(Constants.Sql.MaxParameterCount)` or `Database.FetchByGroups(...)` whenever the collection size is driven by user data — not just when it currently fits. Watch for products of two scaling dimensions (documents × languages, properties × versions) and config-tunable batch sizes whose defaults are safe but ceilings aren't.
Full guidance, safe patterns and decision rule: see `/src/Umbraco.Infrastructure/CLAUDE.md` → "Avoiding the SQL Server 2100-parameter limit".
### Known Limitations
1. **Circular Dependencies**: Avoided via `Lazy<T>` or event notifications
@@ -544,6 +552,14 @@ Allowed, but cheap to write and cheaper to leave behind. Keep them short and tra
---
## 9. Testing Practices
### Tests for a bug fix must fail before the fix
Verify any test you add for a bug fix actually catches the bug: either write the failing test first (TDD), or temporarily revert the production change and confirm the test fails before re-applying. A test that passes both ways proves nothing. Watch for coincidental passes — default seed/sort orders can make a buggy path produce the right answer for the test's specific inputs; construct inputs so the broken and fixed behaviours give visibly different results.
**Status**: Implemented (spike passed 2026-06-11; see `2026-06-11-visual-editor-partial-rerender-plan.md`). Built via cache-node override + `IPublishedContentFactory` rather than a decorator — see the plan's "Deliberate deviation" note.
**Date**: 2026-06-11
**Author**: Rick Butterfield + Claude
**Scope**: The "Still to build" items of Phase 3 in `docs/plans/visual-page-builder.md` — server-side partial re-render with unsaved values, and client-side DOM patching. Block manipulation itself is already done.
**Relates to**: `docs/plans/visual-page-builder.md` §4.4 (original endpoint sketch), §2.3 (BlockPreview pattern); supersedes the isolated-region endpoint idea in §4.4 in favour of full-page render + client morph.
---
## Goal
Make partial re-render the **single, universal mechanism** for reflecting edits in the visual editor preview, retiring both the optimistic-text-only path and the save-and-full-reload path. Every edit — plain text, RTE/Markdown/media, block content/settings, and structural block add/delete/move/reorder — is reflected by re-rendering the page server-side with the workspace's unsaved values and morphing the live iframe DOM in place (no reload, scroll/selection preserved).
## Decisions locked
| Decision | Outcome |
|---|---|
| Trigger scope | **All** edit types route through re-render: block content/settings, block add/delete/move/reorder, RTE/Markdown/transformed properties, and plain text. |
| Feedback model | **Optimistic + authoritative**: instant optimistic `textContent` paint for plain text on keystroke; a debounced (~500ms) server re-render then replaces the region with true Razor output. Blocks/RTE show a subtle pending state (no meaningful optimistic paint) until the render returns. |
| Rendering approach | **A — full-page render + client DOM morph.** One endpoint renders the whole page via the existing preview path with unsaved values injected; guest morphs the live DOM. Chosen over isolated-region (B) because only a full-page render covers arbitrary-template property placement with guaranteed fidelity, and over hybrid (C) for single-path simplicity. |
| DOM patch | Bundle **morphdom** in the guest bundle; morph `<body>`, touching only changed nodes; preserves scroll. |
| Failure mode | **Keep last good DOM + quiet notice.** Leave current DOM untouched, log, transient non-blocking indicator; the workspace already holds the edit so the next successful render reconciles. Never silently swallow. |
| Save + SignalR | **Suppress self-reload, keep as multi-user net.** After a local save, a short-lived guard makes the editor ignore its own `refreshed` SignalR event (DOM already authoritative — no flicker). Refreshes not caused by this editor still reload. |
## Architecture & data flow
```
edit (property / block / structural)
→ element updates workspace value (source of truth) [+ optimistic textContent for plain text]
The base is the **draft** content the iframe already renders (preview-mode cache read); the override layer is the workspace's even-newer unsaved edits on top.
## Server components (new)
| Unit | Project | Responsibility |
|---|---|---|
| Override-content builder (conversion) | `Umbraco.PublishedCache.HybridCache` (or a public seam exposed from it) | Produce an `IPublishedContent` representing the draft + unsaved overrides. **Approach proven by the spike** (and mirroring the in-tree `BlockElementService.BuildElementAsync`): for each overridden alias, run the editor-format value through `dataType.Editor.GetValueEditor().FromEditor(new ContentPropertyData(value, dataType.ConfigurationObject), null)` to get the source value; reuse the existing saved source values (`property.GetValue(published)`) for non-overridden aliases; assemble `PropertyData[]` → `ContentData` → `ContentCacheNode` → `IPublishedContentFactory.ToIPublishedContent(node, preview: true).CreateModel(...)`. Threads `Culture`/`Segment` onto `PropertyData` and sets `ContentData.CultureInfos` for variant content. **Not** a `GetProperty` decorator — a cache-node rebuild. (`IPublishedContentFactory` is `internal` to HybridCache, hence this unit lives there or a small public seam is added — resolved in the plan.) |
| `IVisualEditorRenderService` + impl | `Umbraco.Web.Common` | Renders a supplied `IPublishedContent` to an HTML string. Modeled on `TemplateRenderer` (`src/Umbraco.Web.Common/Templates/TemplateRenderer.cs`): build an `IPublishedRequest` via `IPublishedRouter`, `SetPublishedContent(overriddenContent)`, set culture/segment + template, swap onto `UmbracoContext.PublishedRequest`, render the template view to a `StringWriter`, restore. Forces preview mode + enables `VisualEditorPropertyTracker` for the render scope so annotations are emitted. RTE-embedded blocks render via the partial-view block engine, which this render context satisfies. |
| `RenderVisualEditorController` | `Umbraco.Cms.Api.Management` | `POST /umbraco/management/api/v1/visual-editor/render`, `[Authorize(Policy = BackOfficeAccess)]`. Ensures an `UmbracoContext`, resolves the draft content for `unique`, builds the override content from the request `values`, calls the render service, returns `{ html }`. |
**Value conversion — DE-RISKED by the spike (2026-06-11).** All three property kinds convert correctly via `IPublishedContentFactory.ToIPublishedContent`:
- **Rich Text** — `FromEditor` → source JSON → `RteBlockRenderingValueConverter`; all link/url/image parsing happens at value-conversion time (no `IPublishedRequest` needed). RTE-*embedded blocks* additionally use the partial-view block engine at render time (covered by the full-page render context — smoke-test specifically).
- **Block List** — `FromEditor` source IS the block JSON; the converter resolves element types from the published content-type cache (no parent content / `IPublishedRequest` needed). Blocks need an `Expose` entry for the relevant culture/segment to surface.
Recommended primitive: reuse `IPublishedContentFactory` rather than hand-assembling per property. Variant content must populate `PropertyData` per culture/segment + `ContentData.CultureInfos`, and read-time resolution depends on the ambient `IVariationContextAccessor`.
## Client components
| Unit | Responsibility |
|---|---|
| `UmbVisualEditorRenderController` (new sibling, follows the SignalR/router/resolver extraction pattern) | Debounce (~500ms) + latest-wins cancellation via `AbortController`. Collects the active variant's current values from the workspace, calls the endpoint, posts `umb:ve:render` to the guest with the returned HTML. On failure: keep DOM, log, transient notice. Invoked from every mutation site (property submit, block submit, add/move/delete/reorder, and the debounced optimistic text input). |
| guest `injected.ts` | Bundle **morphdom**. Refactor the one-shot init (default outlines, drag-sort setup, add-button insertion, region discovery) into a re-runnable `initRegions()`. On `umb:ve:render`: morph `document.body` to the new HTML, then run `initRegions()` and restore the selection highlight. Delegated document-level listeners (click capture, mouseover) survive the morph; per-node styles/attributes are re-applied by `initRegions()`. |
| element SignalR (`visual-editor-signalr.controller.ts` + element) | Reintroduce a short-lived **suppress-self-reload** guard set when this editor saves, so the `refreshed` event for our own document key is ignored. Refreshes outside the guard window still reload (multi-user / external cache changes). |
## Error handling
- Render failure (network/500/timeout): keep last good DOM, log, show a transient non-blocking "preview out of date" indicator. The edit is already in the workspace; a later successful render reconciles. No silent swallow.
- Latest-wins: a newer edit aborts the in-flight render so stale HTML never overwrites newer DOM.
- Inline (`contenteditable`) editing — that is Phase 4 and now has its server-rendered source of truth from this phase.
## Testing
- **Backend integration test** (the riskiest, and testable C#, unlike the UI surface): the spike's throwaway test at `tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/PropertyEditors/VisualEditorConversionSpikeTests.cs` (uncommitted) is the basis — the plan's first task formalizes it into a real test of the override-content builder for TextBox, RTE, and Block List (assert converted-without-saving == save-then-read). A second test renders a seeded document through the render service and asserts the HTML reflects overridden values and carries `data-umb-*` annotations.
- **Frontend**: `npm run build` + `npm run lint` + manual smoke (no VE test harness exists; consistent with the prior phase).
## Spike outcome (2026-06-11) — PASSED
A throwaway integration test (`VisualEditorConversionSpikeTests`, uncommitted) booted Umbraco on SQLite, seeded a doc with TextBox + Rich Text + Block List, and proved that each property's editor-format value converts to the correct published value **without saving**, via `FromEditor` + `IPublishedContentFactory.ToIPublishedContent`. All 3 assertions passed (convert-without-saving == save-then-read). Findings folded into "Server components" above:
- Conversion primitive: `IPublishedContentFactory` (HybridCache, `internal`) — plan must resolve the access seam.
- Approach is a cache-node rebuild, **not** a `GetProperty` decorator (in-tree precedent: `BlockElementService`).
- Render-to-string is independently de-risked by the existing `TemplateRenderer`; RTE-embedded-block partials are the one spot needing the render context (not the value conversion).
No design fallback required — the approach is viable as chosen.
**Scope**: Tidy-up round on `feature/visual-editor` after merging `main` — no new feature phases.
**Relates to**: `docs/plans/visual-page-builder.md` (the feature plan; updated as part of this round)
---
## Decisions locked in this round
| Decision | Outcome |
|---|---|
| Architecture | **Embedded document-workspace view** is the current direction. The standalone-window evolution (plan doc §10, Open Q11) is **deferred**, not the next step. |
| Round scope | **Tidy-up only** — security, semantics, refactor, docs. No partial re-render API, no inline editing. |
| Editability semantics | **Strict opt-in everywhere** for document properties: a property is annotated/editable only when `appearance.editableInVisualEditor === true`. The frontend opt-out fallback is removed. |
| Block modal properties | **No filter**: the block editing modal shows all of the element type's content/settings properties. The `EditableInVisualEditor` setting governs document property annotation only. |
## Why
The branch is functionally far ahead of its plan doc (Phases 1–2 complete plus most block manipulation), but an audit found:
1.**Security**: the guest script (`src/Umbraco.Web.UI.Client/src/apps/visual-editor/injected.ts:540`) accepts `message` events with no `evt.origin` check, and posts with target `'*'`. The backoffice-side listener also lacks source/origin validation.
2.**Semantic mismatch**: backend tracking is strict opt-in (`PublishedContentExtensions.TrackVisualEditorAccess` checks `EditableInVisualEditor`), while the frontend had a conflicting "if none opt in, include all" fallback — dead code for properties, but confusing and wrong.
3.**Maintainability**: `document-workspace-view-visual-editor.element.ts` is 1,210 lines with ~11 responsibilities.
5.**Stale docs**: `visual-page-builder.md` predates the `EditableInVisualEditor` setting and records "standalone window" as decided.
## Changes
### 1. Security hardening
**Guest script** (`injected.ts`):
- Derive `PARENT_ORIGIN` once: `document.referrer ? new URL(document.referrer).origin : window.location.origin`.
- Incoming handler: drop messages where `evt.origin !== PARENT_ORIGIN`.
- Outgoing: `window.parent.postMessage(msg, PARENT_ORIGIN)` instead of `'*'`.
- Referrer-based derivation keeps cross-origin dev (Vite 5173 → server 44339) working.
**Workspace view element**: the `message` listener accepts only events where `evt.source === iframe.contentWindow`**and**`evt.origin` equals the server origin from `UMB_SERVER_CONTEXT`.
### 2. Strict opt-in semantics
In the element's property-structure resolution:
- Remove the `anyExplicitlyEnabled` hybrid entirely.
- Document property METADATA stays unfiltered (it doubles as block-config lookup for `#getBlocksConfig`); enforcement is at the interaction points instead: `#onPropertyClicked` and the property modal `onSetup` both require `editableInVisualEditor === true` (defense-in-depth on top of server-side annotation gating).
- Remove the filter entirely from block content/settings structure resolution (blocks show all fields).
- Drop the `as { editableInVisualEditor?: boolean }` casts — the generated API types carry `appearance.editableInVisualEditor` natively; the resolver maps it onto `UmbVisualEditorPropertyInfo.editableInVisualEditor`.
Backend is already strict — no backend change.
### 3. Element refactor (extraction-only)
Extract from `document-workspace-view-visual-editor.element.ts` into sibling files; no behavior change:
| `visual-editor-property-structure.resolver.ts` | Document/block/settings property-structure resolution incl. composition-chain fetch and caching; `Map`-indexed by alias (replaces 6× O(n) `find()`); sole home of the opt-in filter |
| `visual-editor-message-router.ts` | Typed message-map routing of guest messages (replaces 7-case switch); performs the origin/source validation from §1 |
The element keeps iframe lifecycle, modal registrations, selection state and preview URL — target ≤ ~600 lines. Also: `Object.keys(pastedBlocks.layout)[0]` → `Object.values(pastedBlocks.layout)[0]` (line 972).
### 4. Root-level empty block lists
-`BlockListTemplateExtensions` passes the property alias to the partial via `ViewData` (alias-aware overloads; empty models no longer short-circuit so the partial can render an annotated empty container in preview mode).
-`Views/Partials/blocklist/default.cshtml` emits `data-umb-block-property="<alias>"` on the list container — a distinct attribute, because `data-umb-property` is the guest script's property-region selector and would turn the whole list into a clickable property region.
-`injected.ts` resolves the alias from the container for empty root-level lists and renders the existing "Add content" button via a new `umb:ve:block-add-to-property` message (closes the `injected.ts:1040` TODO).
### 5. Docs & polish
- XML docs: class-level summary on `VisualEditorPropertyTracker`; `<param>` tags on `VisualEditorGuestScript.GetScriptTag()`.
-`docs/plans/visual-page-builder.md`: refresh status header and phase statuses; close Open Q5 (setting shipped, strict opt-in); mark §10/Q11 standalone window **Deferred** with embedded view as current; update Appendix B attribute table.
## Out of scope
- Partial re-render API (Phase 3 remainder), inline editing (Phase 4), headless rendering, validation surfaced in preview, scroll retention.
- Moving the visual editor to its own package / lifting block-manipulation logic to library level — revisit with Phase 3.
- Automated tests for the visual editor (no harness exists for this surface yet; E2E coverage noted in the plan doc as future work).
## Verification
1.`npm run build` and `npm run lint` in `src/Umbraco.Web.UI.Client`.
2.`dotnet build umbraco.sln` — zero errors, no new warnings.
3. Manual smoke in the visual editor tab: property edit (flagged + unflagged property), block add/edit/settings/move/delete, empty root-level block list "Add content", save → SignalR refresh → selection restore, postMessage still works in dev (Vite) and built modes.
**Scope**: Move the "empty editable block property" visual-editor affordance (the annotated container that lets the guest offer an "Add content" button) out of per-view template code and into the framework block-rendering helpers, so it works automatically for every template — including custom ones — with zero template boilerplate.
**Supersedes**: the per-view empty-state edits to `blockgrid/blocklist/singleblock/default.cshtml` (sample site) and `EmbeddedResources/BlockGrid/default.cshtml`, plus the `PropertyAliasViewDataKey` ViewData plumbing in `BlockListTemplateExtensions`/`BlockGridTemplateExtensions`.
---
## Problem
The visual editor needs a DOM anchor for empty, editable block properties so the guest can render an "Add content" affordance (it has no blocks to attach inter-block "+" buttons to). The current implementation puts this in the Razor templates:
-`GetBlock{List,Grid}HtmlAsync` short-circuits empty models to `HtmlString.Empty`.
- Each `default.cshtml` was patched to read a `PropertyAliasViewDataKey` from ViewData and render an annotated empty `<div ... data-umb-block-property="{alias}">` in visual-editor mode.
This is unfriendly and incomplete:
- Every block template (block list, block grid, single block — default **and** any custom template) must carry framework annotation boilerplate.
- Custom templates that don't include it silently lose the feature.
- It contrasts with regular property annotation, which is fully automatic (`UmbracoViewPage` wraps editable property output in `data-umb-property` spans with no template code).
## Goal
Make the empty-block affordance **fully automatic**: no template code, working for the default templates and any custom template, gated on the property's `EditableInVisualEditor` opt-in and on visual-editor/preview mode. Revert all per-view edits and the ViewData plumbing.
## Why not the obvious alternatives
- **Emit it from `UmbracoViewPage` (like `data-umb-property`)**: the automatic span is only emitted when the property is accessed via the tracked `IPublishedContent.Value()` path; the block helpers read the value via `GetProperty().GetValue()`, which bypasses the tracker. Making block access reliably tracked and anchoring an affordance on an empty span touches the core annotation pipeline — bigger and riskier (this is the deferred "unify all property annotation" direction).
- **Emit HTML from the Core block model**: `BlockListModel`/`BlockGridModel` live in `Umbraco.Core`, which has no web/HTML concern — emitting annotation markup from the model crosses a layer boundary.
## Approach (chosen)
The block-rendering helpers in `Umbraco.Web.Common` are the web-layer choke point essentially all block rendering flows through. Move the empty-state emission there.
### Component 1 — Helpers emit the annotated container
In `BlockListTemplateExtensions`, `BlockGridTemplateExtensions`, and the single-block rendering helper:
- When the model is **empty** AND `VisualEditorPropertyTracker.IsEnabled` AND the property's `PropertyType.EditableInVisualEditor` is `true`, return a minimal annotated container as an `HtmlString`:
- Block grid: `<div class="umb-block-grid" data-umb-block-property="{alias}"></div>` (with the existing `data-grid-columns`/`--umb-block-grid--grid-columns` styling, defaulting columns to `12`)
- Single block: an analogous annotated empty container (see Component 3)
- Otherwise return `HtmlString.Empty` exactly as today. Non-empty models render their partial unchanged.
The helper builds this small fixed container directly (no partial, no ViewData). The `PropertyAliasViewDataKey` constant, the `WithPropertyAlias` helper, and the alias-via-ViewData private overloads are **removed** from both extensions.
Gating predicate (shared intent across all three helpers): `model is empty && VisualEditorPropertyTracker.IsEnabled && propertyType?.EditableInVisualEditor == true`.
### Component 2 — Emission lives in the alias-bearing overloads only (no model metadata)
The empty-state container is emitted **only by the two alias-bearing overloads**, because they carry the alias and editable flag regardless of whether the value is empty.
**Why not "alias on the model" (rejected):** empty block values resolve to a process-wide **singleton** — the value creators return `BlockListModel.Empty` / `BlockGridModel.Empty` (`public static`), and an empty single block converts to `null`. There is no per-property instance to carry an alias for the empty case, and setting a mutable alias on the shared singleton would corrupt every empty block property on the site. The alias is also unavailable where the model is built (the value *creators* don't receive `IPublishedPropertyType` — only the *converters* do). So model metadata is out; **no changes to Core models, value creators, or converters.**
**Consequence for the model-only overload:**`GetBlock*HtmlAsync(Model.BlockProperty)` (model-only, including the bare ModelsBuilder property) keeps its current behaviour — empty renders nothing, no affordance. The alias-bearing overload (`GetBlock*HtmlAsync(Model, "alias")` / `(IPublishedProperty)`) is the documented, default pattern used by all sample templates (and `Home.cshtml` was aligned to it), so "fully automatic" holds for the standard pattern. The model-only gap is in the same class as fully hand-rolled rendering — see Out of scope.
### Component 3 — Single block
The single-block helper is `SingleBlockTemplateExtensions.GetBlockHtmlAsync`; an empty single-block property surfaces as a **null**`BlockListItem` (the helper already returns `HtmlString.Empty` for null). Emit an annotated empty container when the value is null/empty + `VisualEditorPropertyTracker.IsEnabled` + the property is `EditableInVisualEditor`.
Consistent with Component 2: annotation comes only from the **alias-bearing overloads** — `GetBlockHtmlAsync(IPublishedProperty)` and `GetBlockHtmlAsync(IPublishedContent, alias)` — which expose `property.Alias` and `property.PropertyType.EditableInVisualEditor` even when `property.GetValue()` is null. The model-only `GetBlockHtmlAsync(BlockListItem? model)` overload, given a null model, has no alias and cannot annotate (documented gap; the sample/default and documented usage use the alias-bearing overloads).
"Add content" reuses the existing `umb:ve:block-add-to-property` message (single-block semantics: one block, `insertIndex 0`). The guest gains a single-block empty-container branch mirroring the list/grid ones (or a shared selector). Exact container markup + the guest branch are finalized in the plan.
### Component 4 — Guest + element (mostly unchanged)
- The guest already attaches the "Add content" placeholder to empty `.umb-block-list` / `.umb-block-grid` containers carrying `data-umb-block-property`, and the element's grid-aware add (`#resolveBlockSchemaAlias`) already produces the correct list/grid value shape. These are unchanged.
- The only guest addition is the single-block empty-container handling.
- The `data-umb-block-property` attribute and the `umb:ve:block-add-to-property` postMessage protocol are retained — the helper now emits the attribute that the templates previously emitted.
### Component 5 — Revert the per-view changes
Revert to original form (removing the empty-state boilerplate and ViewData reads):
-`src/Umbraco.Web.UI/Views/Partials/singleblock/default.cshtml` (unchanged from original — never modified, but confirm it needs no edit under the new mechanism)
`Home.cshtml`'s switch to the alias-aware overload (`GetBlockGridHtmlAsync(Model, "bodyText")`) may be **kept or reverted** — under Component 2 the model-only overload also works, so reverting it is safe; keeping it is harmless. The plan picks one (default: keep, as the alias-aware overload is the documented norm).
## Data flow (after)
```
template: @await Html.GetBlockGridHtmlAsync(Model, "bodyText") (or Model.BodyText, or an IPublishedProperty)
→ helper resolves model + property alias + EditableInVisualEditor
→ model non-empty? → render partial as today (unchanged)
→ else HtmlString.Empty (production: nothing, as today)
→ guest sees the empty annotated container → renders "Add content" → umb:ve:block-add-to-property
→ element #onBlockAddToProperty → grid/list-aware value creation (unchanged)
```
## Error handling / edge cases
- Not in VE/preview, or property not editable, or model non-empty → byte-for-byte the same output as before this change (no behavioural change to production rendering).
- Property alias unknown on the model-only overload (metadata not populated, e.g. a model constructed outside the value creators) → no annotation (graceful: treated as "alias unknown", returns empty as today). Not silent in a harmful way — it just falls back to current behaviour.
- A custom template that hand-renders blocks without any `GetBlock*HtmlAsync` helper → no affordance. Documented as the one uncovered path (the helper is the documented rendering API).
## Testing
- **Backend (unit/integration)**: the block helpers return an annotated container for an empty editable block property when `VisualEditorPropertyTracker.IsEnabled`, and `HtmlString.Empty` when (a) the tracker is disabled, (b) the property is not `EditableInVisualEditor`, or (c) the model is non-empty. Cover all three overloads (content+alias, property, model-only) — the model-only case asserts the `PropertyAlias` metadata path.
- **Value-creator test**: the produced block model carries the correct `PropertyAlias` / `EditableInVisualEditor` metadata.
- **Frontend/guest**: `npm run build` + `npm run lint` + manual smoke (no VE guest test harness; consistent with the feature's established posture). Manual smoke covers empty list, empty grid, empty single block in the visual editor.
## Out of scope
- Unifying all property annotation under a single `data-umb-property` mechanism (the deferred Approach 2).
- Shipping a default block-list render template (block list intentionally ships none).
- Covering hand-rolled block rendering that bypasses the `GetBlock*HtmlAsync` helpers.
- Covering the **model-only** helper overload (`GetBlock*HtmlAsync(Model.BlockProperty)`): empty values resolve to the shared `.Empty` singleton (or `null` for single block), which has no per-property identity to annotate. Use the alias-bearing overload (`GetBlock*HtmlAsync(Model, "alias")`) — the documented default — to get the empty-state affordance.
## Implementation note
This change **reverts** the prior per-view empty-state commits and the ViewData plumbing in favour of the helper-based mechanism. Those commits remain in history as superseded steps; the revert is part of this work, not a separate cleanup.
# Visual Editor — Framework-Emitted Empty-Block Affordance — Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Make the visual-editor empty-block "Add content" affordance fully automatic via the block-rendering helpers, removing the per-view template boilerplate and the ViewData plumbing.
**Architecture:** The block helpers (`BlockListTemplateExtensions`, `BlockGridTemplateExtensions`, `SingleBlockTemplateExtensions` in `Umbraco.Web.Common`) emit an annotated empty container `<div class="umb-block-{list,grid,single}" data-umb-block-property="{alias}">` themselves — but only from the **alias-bearing overloads** (which carry the alias + `PropertyType.EditableInVisualEditor` even when the value is empty), and only when `VisualEditorPropertyTracker.IsEnabled` and the property is editable-in-VE. A shared `BlockEmptyState` helper DRYs the gating + markup. The default views revert to their plain form, and the ViewData plumbing is deleted. No changes to Core models / value creators / converters.
**Tech Stack:** C# / ASP.NET Core Razor helpers (`Umbraco.Web.Common`), Razor views (`Umbraco.Web.UI`, embedded `Umbraco.Core`), TypeScript guest (`injected.ts`) + Lit element (backoffice client). Working dir for ALL tasks: `D:/CMS/Umbraco-CMS/.worktrees/feature-visual-editor`.
**Standing instruction:** the user asked for **no commits yet**. Implement and verify each task; leave changes in the working tree **uncommitted**. The "Commit" steps below are written for completeness but are GATED — do not run them until the user approves committing. Report each task's diff for review instead.
**Verified facts:**
- Empty block values resolve to the shared singletons `BlockListModel.Empty` / `BlockGridModel.Empty`; an empty single block converts to `null`. Hence the alias can only come from the alias-bearing overloads, not the model. (No model/creator/converter changes.)
-`VisualEditorPropertyTracker.IsEnabled` is a public static in `Umbraco.Cms.Core.Models.PublishedContent`.
-`SingleBlockValue : BlockValue<SingleBlockLayoutItem>` with `PropertyEditorAlias => Constants.PropertyEditors.Aliases.SingleBlock` — so single-block add reuses `addBlockToValue` with the single-block schema alias.
- The guest already has empty-container branches for `.umb-block-list` and `.umb-block-grid` reading `dataset.umbBlockProperty`; there is **no** single-block handling.
thrownewInvalidOperationException("No property type found with alias "+propertyAlias);
}
returnproperty;
}
}
```
This removes `PropertyAliasViewDataKey`, `WithPropertyAlias`, the `Microsoft.AspNetCore.Mvc.ViewFeatures` using, and the old alias-via-ViewData private overloads.
- [ ]**Step 4: Run the test to verify it passes**
Run: `dotnet test tests/Umbraco.Tests.UnitTests --filter "FullyQualifiedName~BlockListTemplateExtensionsTests"`
(Note: `new BlockGridModel(new List<BlockGridItem>(), null)` is used instead of `BlockGridModel.Empty` because `Empty` has `Count == 0` and either works; the explicit list keeps the test independent of the singleton.)
- [ ]**Step 2: Run the test to verify it fails**
Run: `dotnet test tests/Umbraco.Tests.UnitTests --filter "FullyQualifiedName~BlockGridTemplateExtensionsTests"`
Expected: FAIL (no container emitted by current helper).
In `src/Umbraco.Web.Common/Extensions/BlockGridTemplateExtensions.cs`:
(a) Remove the `using Microsoft.AspNetCore.Mvc.ViewFeatures;` line.
(b) Remove the `PropertyAliasViewDataKey` const + its XML doc (lines 20-24).
(c) Replace the async property/content overloads + private method (lines 51-66) — change the property overloads to pass the alias **and** editable flag, and rewrite the private method to emit the empty-state:
Change the alias-bearing overloads to pass the alias + editable flag through to a private method that emits the empty-state. The model-only overloads keep their `model is null → HtmlString.Empty` behaviour.
Replace the async property/content overloads (lines 27-37) with:
These no longer carry empty-state logic — the helper handles it. (The `singleblock/default.cshtml` was never modified and stays as-is: the helper now handles the empty/null case before the partial is invoked, so the partial only ever renders a non-null block.)
(Note: the per-block `data-umb-block-key`/`data-umb-content-type` annotations on populated blocks are retained — they were present before the empty-state work and are needed for selecting existing blocks. Only the empty-state `data-umb-block-property` + ViewData read are removed.)
The guest already handles empty `.umb-block-list` and `.umb-block-grid` containers (unchanged — the helper now emits the same `data-umb-block-property` markup). Add a parallel branch for the single-block container class `umb-single-block`.
- [ ]**Step 1: Add the single-block empty-container branch**
In `insertAddButtons()`, immediately after the existing empty `.umb-block-grid` branch (the block that does `document.querySelectorAll<HTMLElement>('.umb-block-grid').forEach(...)`), add:
```typescript
// Empty single block at root level. The container carries data-umb-block-property
// (emitted by the single block helper in visual-editor mode).
Also update the file-header doc comment line for `data-umb-block-property` to read: `Property alias on a block list, block grid, or single block container (empty-state block creation)`.
- [ ]**Step 2: Build the client**
Run: `cd src/Umbraco.Web.UI.Client && npm run build`
When the guest sends `umb:ve:block-add-to-property` for a single-block property, the element must create a single-block-shaped value (layout key `Umbraco.SingleBlock`). Today `#resolveBlockSchemaAlias` only maps grid vs list; extend it for single block so `addBlockToValue` writes the right layout key.
- [ ]**Step 1: Confirm the single-block client constants**
Expected: find the exported constants for the single block editor — the schema alias (value `Umbraco.SingleBlock`) and the UI alias (value `Umb.PropertyEditorUi.BlockSingle` or similar). Note their exact exported names and the import path (`@umbraco-cms/backoffice/block-single`). If the names differ from those used below, substitute the real names.
(`addBlockToValue` keys its grid-specific layout logic on `UMB_BLOCK_GRID_PROPERTY_EDITOR_SCHEMA_ALIAS`; for the single-block alias it falls through to the plain list-shaped layout item, which matches `SingleBlockValue`'s `BlockValue<SingleBlockLayoutItem>` structure — one block under the `Umbraco.SingleBlock` layout key, no columnSpan/rowSpan.)
- [ ]**Step 3: Build the client**
Run: `cd src/Umbraco.Web.UI.Client && npm run build`
Expected: tsc exits 0. (Allow up to 600000ms.) If the single-block constant names differ, fix the import to the real names found in Step 1.
4. A **non-editable** empty block property → renders nothing, no affordance.
5. A custom template that renders a block property via `@Html.GetBlock*HtmlAsync(Model, "alias")` → affordance appears with **no template code** for the empty state.
6. Non-empty block properties render unchanged.
- [ ]**Step 5: Update the design doc status**
In `docs/plans/2026-06-12-visual-editor-block-empty-state-design.md` replace:
```markdown
**Status**: Approved design, pending implementation plan
@@ -32,6 +32,14 @@ public class SearchMemberTypeItemController : MemberTypeItemControllerBase
_mapper=mapper;
}
/// <summary>
/// Searches for member type items matching the specified query, with support for pagination.
/// </summary>
/// <param name="cancellationToken">A token to monitor for cancellation requests.</param>
/// <param name="query">The search query used to filter member type items.</param>
/// <param name="skip">The number of items to skip before starting to collect the result set (used for pagination).</param>
/// <param name="take">The maximum number of items to return in the result set (used for pagination).</param>
/// <returns>A task representing the asynchronous operation. The task result contains an <see cref="IActionResult"/> with a <see cref="PagedModel{MemberTypeItemResponseModel}"/> containing the search results.</returns>
/// Controller for setting the redirect URL tracking status.
/// Controller for setting the redirect URL tracking status. Retained for backwards compatibility only;
/// the endpoint no longer modifies any configuration.
/// </summary>
[ApiVersion("1.0")]
[Obsolete("This controller is deprecated and no longer modifies the configuration. Set the Umbraco:CMS:WebRouting:DisableRedirectUrlTracking configuration key instead. Scheduled for removal in Umbraco 19.")]
// TODO: Consider if we should even allow this, or only allow using the appsettings
// We generally don't want to edit the appsettings from our code.
// But maybe there is a valid use case for doing it on the fly.
/// <summary>
/// Sets the redirect URL tracking status.
/// Deprecated. Returns an OK response without modifying any configuration. To toggle redirect URL tracking,
/// set the <c>Umbraco:CMS:WebRouting:DisableRedirectUrlTracking</c> configuration key instead.
/// </summary>
/// <param name="cancellationToken">The cancellation token for the HTTP request.</param>
/// <param name="status">The redirect status to set.</param>
/// <returns>An OK result if successful.</returns>
/// <param name="status">The redirect status (ignored).</param>
/// <returns>An OK result.</returns>
[HttpPost("status")]
[EndpointSummary("Sets the redirect URL tracking status.")]
[EndpointDescription("Updates the redirect URL tracking configuration according to the provided status.")]
[EndpointSummary("Deprecated. No longer changes the redirect URL tracking status.")]
[EndpointDescription("This endpoint is deprecated and no longer modifies the configuration. To toggle redirect URL tracking, set the Umbraco:CMS:WebRouting:DisableRedirectUrlTracking configuration key instead.")]
// Taken from the existing implementation in RedirectUrlManagementController
// TODO this is ridiculous, but we need to ensure the configuration is reloaded, before this request is ended.
// otherwise we can read the old value in GetEnableState.
// The value is equal to JsonConfigurationSource.ReloadDelay
Thread.Sleep(250);
returnOk();
}
[Obsolete("This endpoint is deprecated and no longer modifies the configuration. Set the Umbraco:CMS:WebRouting:DisableRedirectUrlTracking configuration key instead. Scheduled for removal in Umbraco 19.")]
@@ -32,6 +32,14 @@ public class SearchTemplateItemController : TemplateItemControllerBase
_mapper=mapper;
}
/// <summary>
/// Searches for template items matching the specified query, with support for pagination.
/// </summary>
/// <param name="cancellationToken">A token to monitor for cancellation requests.</param>
/// <param name="query">The search query used to filter template items.</param>
/// <param name="skip">The number of items to skip before starting to collect the result set (used for pagination).</param>
/// <param name="take">The maximum number of items to return in the result set (used for pagination).</param>
/// <returns>A task representing the asynchronous operation. The task result contains an <see cref="IActionResult"/> with a <see cref="PagedModel{TemplateItemResponseModel}"/> containing the search results.</returns>
/// Initializes a new instance of the <see cref="DataTypePresentationFactory"/> class, which is responsible for creating data type presentation models.
@@ -25,18 +29,46 @@ public class DataTypePresentationFactory : IDataTypePresentationFactory
/// <param name="dataValueEditorFactory">Factory for creating data value editors.</param>
/// <param name="configurationEditorJsonSerializer">Serializer for configuration editor JSON data.</param>
/// <param name="timeProvider">Provides the current time for time-dependent operations.</param>
/// Initializes a new instance of the <see cref="DataTypePresentationFactory"/> class, which is responsible for creating data type presentation models.
/// </summary>
/// <param name="dataTypeContainerService">Service used to manage data type containers.</param>
/// <param name="propertyEditorCollection">A collection containing all available property editors.</param>
/// <param name="dataValueEditorFactory">Factory for creating data value editors.</param>
/// <param name="configurationEditorJsonSerializer">Serializer for configuration editor JSON data.</param>
/// <param name="timeProvider">Provides the current time for time-dependent operations.</param>
[Obsolete("Please use the constructor that takes all parameters. Scheduled for removal in Umbraco 19.")]
// Configuration editors are third-party and can throw anything when the stored configuration
// doesn't deserialize into their configuration type. Fall back to the value editor's value type
// rather than failing the save, but log so the misconfiguration remains observable.
_logger.LogError(
"Could not build the configuration object for editor {EditorAlias} to determine its value storage type; falling back to the value editor's value type.",
"summary":"Sets the redirect URL tracking status.",
"description":"Updates the redirect URL tracking configuration according to the provided status.",
"summary":"Deprecated. No longer changes the redirect URL tracking status.",
"description":"This endpoint is deprecated and no longer modifies the configuration. To toggle redirect URL tracking, set the Umbraco:CMS:WebRouting:DisableRedirectUrlTracking configuration key instead.",
@@ -306,6 +306,8 @@ public class MyEntityCacheRefresher : CacheRefresherBase<MyEntityCacheRefresher>
-`Attempt.Succeed(value)` / `Attempt.Fail<T>()`
-`Attempt<Content, ContentEditingOperationStatus>` - typed result with status
> Writing or reviewing a query with a `WHERE IN` on a runtime-sized collection? See "Avoiding the SQL Server 2100-parameter limit" in `/src/Umbraco.Infrastructure/CLAUDE.md` — that's where the full helper list (`Constants.Sql.MaxParameterCount`, `InGroupsOf`, NPoco's `FetchByGroups`) and the decision rules live.
@@ -36,6 +36,7 @@ public interface IConfigManipulator
/// </summary>
/// <param name="disable">The value to save.</param>
/// <returns></returns>
[Obsolete("This method is no longer used by Umbraco. Set the Umbraco:CMS:WebRouting:DisableRedirectUrlTracking configuration key instead. Scheduled for removal in Umbraco 19.")]
@@ -106,7 +106,7 @@ public interface IHostingEnvironment
/// content root are the same, however
/// in netcore the web root is /www therefore this will Map to a physical path within www.
/// </remarks>
[Obsolete("Please use the MapPathWebRoot extension method on an instance of IWebHostEnvironment instead")]
[Obsolete("Please use the MapPathWebRoot extension method on an instance of IWebHostEnvironment instead. Scheduled for removal in Umbraco 20.")]
stringMapPathWebRoot(stringpath);
/// <summary>
@@ -118,7 +118,7 @@ public interface IHostingEnvironment
/// in netcore the web root is /www therefore this will Map to a physical path within www.
/// </remarks>
[Obsolete(
"Please use the MapPathContentRoot extension method on an instance of IHostEnvironment (or IWebHostEnvironment) instead")]
"Please use the MapPathContentRoot extension method on an instance of IHostEnvironment (or IWebHostEnvironment) instead. Scheduled for removal in Umbraco 20.")]
@@ -55,7 +55,9 @@ public class LuceneIndexDiagnostics : IIndexDiagnostics
DirectoryluceneDir=Index.GetLuceneDirectory();
vard=newDictionary<string,object?>
{
#pragmawarningdisableCS0618// CommitCount is obsolete and reported unused, but retained to avoid any risk of change to existing behaviour. Remove this entry when a future Examine upgrade removes the underlying field.
@@ -384,6 +384,57 @@ using (ICoreScope scope = ScopeProvider.CreateCoreScope())
3.**Lazy loading outside scope** - NPoco relationships must load within scope
4.**Large migrations** - Split into multiple steps if > 1000 lines
5.**Repository logic in services** - Keep repos thin, logic in services
6.**Unbatched `WHERE IN` on user-sized collections** - See "Avoiding the SQL Server 2100-parameter limit" below
### Avoiding the SQL Server 2100-parameter limit
SQL Server caps a single statement at 2100 parameters. When an `IN` clause is built from a collection sized by user data, that cap can be hit — and the symptom is a runtime `SqlException` (error 8003) on customer installs that nobody hit in dev.
**The constant and helpers**:
-`Constants.Sql.MaxParameterCount = 2000` (in `Umbraco.Core`, `Constants-Sql.cs`) — the ceiling we target (2100 minus headroom for joined predicates already in the SQL).
-`IEnumerable<T>.InGroupsOf(groupSize)` (in `Umbraco.Core`, `Extensions/EnumerableExtensions.cs`) — extension method to batch a collection.
-`Database.FetchByGroups<TResult, TSource>(source, groupSize, sqlFactory)` (in `Umbraco.Infrastructure`, `Persistence/NPocoDatabaseExtensions.cs`) — NPoco helper that batches a fetch.
**The safe patterns** (use one of these any time the collection size is user-driven):
```csharp
// Pattern 1: batch a DeleteMany / Execute / Fetch by looping.
// statement uses entityIds + userGroupIds, so subtract the other predicate's parameter count from the budget
}
```
**Decision rule when writing or reviewing a `WHERE IN`-style query**:
Look at what drives the size of the collection feeding the `IN`. Ask: *could this realistically exceed 2000 on a large install?* Risky drivers — batch any query backed by these:
- All content / media / member nodes (or descendants of a deep tree).
- A product of two scaling dimensions, e.g. `documents × languages`, `properties × versions`, `relations × endpoints`.
- Configuration-tunable batch sizes (`CacheSettings.DocumentSeedBatchSize`, `NuCacheSettings.SqlPageSize`, etc.). The default may be safe but the customer can raise it.
- Anything that scans property data, version history, relations, or audit logs across many nodes.
Safe drivers — don't bother batching:
- Languages / content types / member groups / user groups — bounded by install configuration, typically <100.
- "Per single content item" collections — properties on one document, versions of one document, tokens for one external login.
- IDs supplied directly by a user action through the UI (picker selections, bulk actions on a page of results).
If you're not sure, batch — the cost is one loop and an `IEnumerable<T>` allocation per batch; the cost of being wrong is a SqlException on a customer's biggest site.
**For new public APIs** that take an `IEnumerable<int>`/`IEnumerable<Guid>` and feed it into a query, batch internally even if no current caller is large — package authors and future callers will not know about the 2000-limit ceiling.
**Don't** rely on `if (ids.Length > MaxParameterCount) throw` as a substitute for batching. Throwing only moves the problem; the caller has no obvious way to recover and will most likely just fail in production.
@@ -104,6 +104,7 @@ internal sealed class JsonConfigManipulator : IConfigManipulator
}
/// <inheritdoc />
[Obsolete("This method is no longer used by Umbraco. Set the Umbraco:CMS:WebRouting:DisableRedirectUrlTracking configuration key instead. Scheduled for removal in Umbraco 19.")]
// Serilog.Formatting.Compact.Reader uses Newtonsoft.Json internally and surfaces
// its exceptions (Umbraco's own serialization is on System.Text.Json, but that
// doesn't apply here — we have to catch what the reader actually throws).
// JsonException covers parse failures (e.g. an unterminated string in a truncated
// entry); InvalidDataException covers structurally-valid JSON that isn't a valid
// Serilog Compact event. Either way the offending line has been consumed from the
// underlying StreamReader and the next TryRead call advances. Anything else
// (IOException, decoder failures, etc.) is propagated to the file-level catch in
// GetLogs so we don't risk a tight loop or silently swallow a more serious failure.
errorCount++;
firstError??=ex;
continue;
}
// LogEventReader may return true with a null event for a benign skip.
if(evtisnull)
{
continue;
}
if(logFilter.TakeLogEvent(evt))
{
logs.Add(evt);
}
}
if(errorCount>0)
{
_logger.LogWarning(
firstError,
"Encountered {ErrorCount} unreadable line(s) while reading log file {FilePath}. The file may contain partially-written or corrupt entries; affected lines were skipped.",
@@ -256,6 +257,8 @@ ASP.NET Core Identity sign-in manager for members.
### Middleware
**Convention**: middleware lives in `Middleware/` as a class implementing `IMiddleware`, registered as a singleton next to its dependencies' registration (generic middleware in `AddWebComponents`; feature-specific middleware where the feature's services are added, e.g. backoffice middleware in `AddBackOfficeCore`), and wired into the pipeline via `app.UseMiddleware<TMiddleware>()`. Companion `IApplicationBuilder` extension methods are thin one-line `UseMiddleware<T>()` wrappers — inline `builder.Use(async …)` lambdas bypass DI and are harder to test; `CspNonceExtensions` and `Web.UI/WebApplicationExtensions` are tiny pre-existing exceptions, not a precedent for new work.
**BootFailedMiddleware** (lines 17-81):
- Intercepts requests when `RuntimeLevel == BootFailed`
- Debug mode: Rethrows exception for stack trace
@@ -266,6 +269,11 @@ ASP.NET Core Identity sign-in manager for members.
- Sets `Cache-Control: public, max-age=31536000, immutable` on responses under the cache-busted backoffice asset prefix (`/umbraco/backoffice/<hash>/…`); `no-cache` in debug mode
- Runs before `UseUmbracoBackOfficeRewrites` so the original (hash-bearing) path can be matched
- Non-destructive: uses `Response.OnStarting` + `ContainsKey` guard so any consumer override wins
---
## 4. Routing
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.