Files
webstudio/apps/builder/app/shared/sync/sync-stores.ts
T
Oleg Isonen b0d7cc2e7b fix: Show scoped Tag colors on selected descendants (#6677)
When an H2 gets its color from a Tag selector on its container,
selecting the H2 can show black in the Style panel. The panel now shows
the matching color. A Token or Local style on the H2 can still override
the container's Tag selector.

## Plan and progress

- [x] Reproduce the selected H2 showing the container color instead of
its nested Tag color.
- [x] Give descendant Tag selectors the intended CSS specificity in
Builder and published CSS.
- [x] Include matching ancestor Tag declarations in the Style panel's
color calculation.
- [x] Cover the selected H2 and regular and atomic CSS output with
focused tests.
- [x] Review documentation impact and update the Tag styles and
selectors guides.
- [x] Match the panel's competing ancestor Tag rules to CSS breakpoint
and stylesheet order.
- [x] Match the editing preview's selector specificity to the saved
rule.
- [x] Use the descendant separator directly when detecting nested
selectors.
- [x] Allow the same supported selector forms in Tag, Token, and Local
sources.
- [x] Match global Tag descendant styles in the editing preview and
Style panel.
- [x] Document nested Tag selector examples in the Tag styles guide.
- [x] Explain supported selectors in Add more while its input is
focused.
- [x] Review and simplify nested state matching; preserve the entered
selector text.
- [x] Consolidate cascade declaration lookup and reuse the validated
selector parse result.
- [x] Align Builder and MCP selector entry with one validation rule;
preserve saved selectors.
- [x] Fix nested-selector source badges and preserve valid instance
selection.
- [x] Keep descendant conditions scoped to the matched element during
inheritance.
- [x] Match saved nested selectors regardless of tag casing or leading
whitespace.
- [ ] Verify both fixes, resolve review threads, and review CI.

The panel model needs ancestor matching because it computes styles
without querying the rendered element. The complete PR adds about 195
net non-test lines. The added work covers selector entry, active nested
states, and matching Tag rules in the panel; the saved CSS output
already supported nested tags. CSS generation uses `:where()` around the
container selector so the nested tag can override the global tag style
while the H2's own Token can override the nested tag style. No stored
data changes.

Checks passed locally: focused Builder style source, active state, panel
model, and canvas preview tests; CSS data and runtime tests; Builder,
CSS data, and project-build typechecks; lint, formatting, and `git diff
--check`. The focused Add more menu was checked in Storybook in both
themes. CI passed for commit `838cf4293f`; CI for `224f11e274` is
pending. The full Builder app suite was started but stopped after it
stopped producing results; the two affected suites passed independently.
This follow-up adds 67 net non-test lines to track matching states by
instance and match saved descendant selectors using the shared parser.
No fixture inputs or generated fixture outputs changed.

Ref #5657
2026-11-11 20:52:01 +01:00

457 lines
14 KiB
TypeScript

import { Store, type Change } from "immerhin";
import { enableMapSet, setAutoFreeze } from "immer";
import { useEffect } from "react";
import { batched } from "nanostores";
import { createId } from "@webstudio-is/sdk";
import { $project } from "./data-stores";
import {
$selectedPageHash,
$selectedInstanceSizes,
$authTokenPermissions,
$toastErrors,
$selectedStyleSources,
$selectedStyleState,
$temporaryTagStyleId,
$dataSourceVariables,
$dragAndDropState,
$selectedInstanceStates,
$selectedInstanceStatesByInstanceId,
$canvasIframeState,
$uploadingFilesDataStore,
$memoryProps,
$detectedFontsWeights,
$builderMode,
$selectedBreakpointId,
$textEditingInstanceSelector,
$textEditorContextMenu,
$textEditorContextMenuCommand,
$isResizingCanvas,
$collaborativeInstanceRect,
$collaborativeInstanceSelector,
$blockChildOutline,
$textToolbar,
$gridCellData,
$registeredComponentMetas,
$registeredTemplates,
$modifierKeys,
$instanceContextMenu,
$selectedInstanceRenderState,
$hoveredInstanceSelector,
$selectedInstanceOutline,
$selectedInstanceOutlines,
$hoveredInstanceOutline,
} from "~/shared/nano-states";
import {
$marketplaceProduct,
$projectSettings,
} from "~/shared/sync/data-stores";
import { $ephemeralStyles } from "~/canvas/stores";
import {
ImmerhinSyncObject,
NanostoresSyncObject,
SyncClient,
SyncObjectPool,
} from "../sync-client";
import type {
RevertedTransaction,
SyncEmitter,
Transaction,
} from "@webstudio-is/sync-client";
import { $canvasScrollbarSize } from "~/builder/shared/nano-states";
import {
$pages,
$instances,
$props,
$dataSources,
$breakpoints,
$styles,
$styleSources,
$styleSourceSelections,
$assets,
$assetFolders,
$resources,
} from "~/shared/sync/data-stores";
import { $pointerPosition } from "../awareness";
import { $temporaryInstances } from "../nano-states";
import {
$allSelectedInstanceSelectors,
$instanceSelectionUpdate,
$selectedInstanceSelector,
selectInstance,
selectInstances,
} from "../nano-states/instance-selection";
import { $pageNavigation, $selectedPageId } from "../nano-states/pages";
import { areSelectorListsEqual } from "../instance-utils/selection";
import { $systemDataByPage } from "../system";
import { $resourcesCache, $resourcesState } from "../resources";
import {
areInstanceSelectorsEqual,
type InstanceSelector,
} from "@webstudio-is/project-build/runtime";
import { $externalContentRoots } from "../external-content-mutations";
import { $externalContentHistory } from "../external-content-history";
enableMapSet();
// safari structuredClone fix
setAutoFreeze(false);
export const clientSyncStore = new Store();
export const serverSyncStore = new Store();
export const externalContentSyncStore = new Store();
const serverSyncRevertListeners = new Set<
(changes: readonly Change[]) => void
>();
export const subscribeServerSyncReverts = (
listener: (changes: readonly Change[]) => void
) => {
serverSyncRevertListeners.add(listener);
return () => serverSyncRevertListeners.delete(listener);
};
const serverSyncStores = {
pages: $pages,
breakpoints: $breakpoints,
instances: $instances,
styles: $styles,
styleSources: $styleSources,
styleSourceSelections: $styleSourceSelections,
props: $props,
dataSources: $dataSources,
resources: $resources,
assets: $assets,
assetFolders: $assetFolders,
projectSettings: $projectSettings,
marketplaceProduct: $marketplaceProduct,
} as const;
type ServerSyncStoreName = keyof typeof serverSyncStores;
type ServerSyncStoreValue = {
[Name in ServerSyncStoreName]: ReturnType<
(typeof serverSyncStores)[Name]["get"]
>;
}[ServerSyncStoreName];
export type ServerSyncState = Map<ServerSyncStoreName, ServerSyncStoreValue>;
export const serverSyncStoreNames = Object.keys(
serverSyncStores
) as ReadonlyArray<ServerSyncStoreName>;
export const registerContainers = () => {
// synchronize patches
for (const name of serverSyncStoreNames) {
serverSyncStore.register<ServerSyncStoreValue>(
name,
serverSyncStores[name]
);
externalContentSyncStore.register<ServerSyncStoreValue>(
name,
serverSyncStores[name]
);
}
};
type SelectedPageAndInstance = {
selectedPageId: string | undefined;
selectedInstanceSelector: InstanceSelector | undefined;
allSelectedInstanceSelectors: InstanceSelector[];
};
const isInstanceSelector = (value: unknown): value is InstanceSelector =>
Array.isArray(value) && value.every((id) => typeof id === "string");
const isInstanceSelectorList = (value: unknown): value is InstanceSelector[] =>
Array.isArray(value) && value.every(isInstanceSelector);
const areSelectedPageAndInstanceEqual = (
left: SelectedPageAndInstance,
right: SelectedPageAndInstance
) =>
left.selectedPageId === right.selectedPageId &&
(left.selectedInstanceSelector === undefined
? right.selectedInstanceSelector === undefined
: right.selectedInstanceSelector !== undefined &&
areInstanceSelectorsEqual(
left.selectedInstanceSelector,
right.selectedInstanceSelector
)) &&
areSelectorListsEqual(
left.allSelectedInstanceSelectors,
right.allSelectedInstanceSelectors
);
const $selectedPageAndInstance = batched(
[
$selectedPageId,
$selectedInstanceSelector,
$allSelectedInstanceSelectors,
$instanceSelectionUpdate,
],
(
selectedPageId,
selectedInstanceSelector,
allSelectedInstanceSelectors,
selectionUpdate
) => ({
state: {
selectedPageId,
selectedInstanceSelector,
allSelectedInstanceSelectors,
} satisfies SelectedPageAndInstance,
selectionUpdate,
})
);
class SelectedPageAndInstanceSyncObject {
name = "selectedPageAndInstance";
private operation: "local" | "state" | "add" = "local";
private stateToIgnore: SelectedPageAndInstance | undefined;
private lastSelectionRevision = $instanceSelectionUpdate.get().revision;
private lastSelectedPageId = $selectedPageId.get();
getState() {
return $selectedPageAndInstance.get().state;
}
setState(state: unknown) {
this.applyRemoteState(state, "state");
}
applyTransaction(transaction: Transaction) {
this.applyRemoteState(transaction.payload, "add");
}
revertTransaction(_transaction: RevertedTransaction) {
// @todo store the list of transactions
}
subscribe(
sendTransaction: (transaction: Transaction) => void,
signal: AbortSignal
) {
this.lastSelectionRevision = $instanceSelectionUpdate.get().revision;
this.lastSelectedPageId = $selectedPageId.get();
const unsubscribe = $selectedPageAndInstance.listen(
({ state, selectionUpdate }) => {
const isDerivedPruning =
selectionUpdate.revision !== this.lastSelectionRevision &&
selectionUpdate.origin === "instance-pruning";
const didSelectedPageChange =
state.selectedPageId !== this.lastSelectedPageId;
this.lastSelectionRevision = selectionUpdate.revision;
this.lastSelectedPageId = state.selectedPageId;
if (this.stateToIgnore !== undefined) {
const shouldIgnore = areSelectedPageAndInstanceEqual(
state,
this.stateToIgnore
);
this.stateToIgnore = undefined;
if (shouldIgnore) {
return;
}
}
if (
this.operation !== "local" ||
(isDerivedPruning && didSelectedPageChange === false)
) {
return;
}
sendTransaction({
id: createId("nano"),
object: this.name,
payload: state,
});
}
);
signal.addEventListener("abort", unsubscribe);
}
private applyRemoteState(state: unknown, operation: "state" | "add") {
this.operation = operation;
try {
const appliedState = this.setSelectedPageAndInstance(
operation === "add" ? structuredClone(state) : state
);
if (appliedState !== undefined) {
this.stateToIgnore = appliedState;
}
} catch (error) {
console.error(error);
} finally {
this.operation = "local";
}
}
private setSelectedPageAndInstance(
state: unknown
): SelectedPageAndInstance | undefined {
if (typeof state !== "object" || state === null) {
return;
}
const {
selectedPageId,
selectedInstanceSelector,
allSelectedInstanceSelectors,
} = state as Partial<SelectedPageAndInstance>;
if (selectedPageId !== undefined && typeof selectedPageId !== "string") {
return;
}
if (
selectedInstanceSelector !== undefined &&
isInstanceSelector(selectedInstanceSelector) === false
) {
return;
}
if (
allSelectedInstanceSelectors !== undefined &&
isInstanceSelectorList(allSelectedInstanceSelectors) === false
) {
return;
}
$selectedPageId.set(selectedPageId);
if (allSelectedInstanceSelectors !== undefined) {
selectInstances(allSelectedInstanceSelectors);
} else {
selectInstance(selectedInstanceSelector);
}
return {
selectedPageId: $selectedPageId.get(),
selectedInstanceSelector: $selectedInstanceSelector.get(),
allSelectedInstanceSelectors: $allSelectedInstanceSelectors.get(),
};
}
}
export const __testing__ = {
SelectedPageAndInstanceSyncObject,
};
export const createObjectPool = () => {
return new SyncObjectPool([
new ImmerhinSyncObject("server", serverSyncStore, {
onRevert: (changes) => {
for (const listener of serverSyncRevertListeners) {
listener(changes);
}
},
}),
new ImmerhinSyncObject("externalContent", externalContentSyncStore),
new ImmerhinSyncObject("client", clientSyncStore),
new SelectedPageAndInstanceSyncObject(),
new NanostoresSyncObject("pointerPosition", $pointerPosition),
new NanostoresSyncObject("temporaryInstances", $temporaryInstances),
new NanostoresSyncObject("project", $project),
new NanostoresSyncObject("dataSourceVariables", $dataSourceVariables),
new NanostoresSyncObject("resourcesCache", $resourcesCache),
new NanostoresSyncObject("resourcesState", $resourcesState),
new NanostoresSyncObject("selectedPageHash", $selectedPageHash),
new NanostoresSyncObject("pageNavigation", $pageNavigation),
new NanostoresSyncObject("selectedInstanceSizes", $selectedInstanceSizes),
new NanostoresSyncObject(
"selectedInstanceRenderState",
$selectedInstanceRenderState
),
new NanostoresSyncObject(
"hoveredInstanceSelector",
$hoveredInstanceSelector
),
new NanostoresSyncObject(
"selectedInstanceOutline",
$selectedInstanceOutline
),
new NanostoresSyncObject(
"selectedInstanceOutlines",
$selectedInstanceOutlines
),
new NanostoresSyncObject("hoveredInstanceOutline", $hoveredInstanceOutline),
new NanostoresSyncObject("builderMode", $builderMode),
new NanostoresSyncObject("authTokenPermissions", $authTokenPermissions),
new NanostoresSyncObject("toastErrors", $toastErrors),
new NanostoresSyncObject("selectedStyleSources", $selectedStyleSources),
new NanostoresSyncObject("selectedStyleState", $selectedStyleState),
new NanostoresSyncObject("temporaryTagStyleId", $temporaryTagStyleId),
new NanostoresSyncObject("dragAndDropState", $dragAndDropState),
new NanostoresSyncObject("ephemeralStyles", $ephemeralStyles),
new NanostoresSyncObject("selectedInstanceStates", $selectedInstanceStates),
new NanostoresSyncObject(
"selectedInstanceStatesByInstanceId",
$selectedInstanceStatesByInstanceId
),
new NanostoresSyncObject("canvasIframeState", $canvasIframeState),
new NanostoresSyncObject(
"uploadingFilesDataStore",
$uploadingFilesDataStore
),
new NanostoresSyncObject("memoryProps", $memoryProps),
new NanostoresSyncObject("detectedFontsWeights", $detectedFontsWeights),
new NanostoresSyncObject("selectedBreakpointId", $selectedBreakpointId),
new NanostoresSyncObject(
"textEditingInstanceSelector",
$textEditingInstanceSelector
),
new NanostoresSyncObject("textEditorContextMenu", $textEditorContextMenu),
new NanostoresSyncObject(
"textEditorContextMenuCommand",
$textEditorContextMenuCommand
),
new NanostoresSyncObject("isResizingCanvas", $isResizingCanvas),
new NanostoresSyncObject("textToolbar", $textToolbar),
new NanostoresSyncObject("blockChildOutline", $blockChildOutline),
new NanostoresSyncObject("instanceContextMenu", $instanceContextMenu),
new NanostoresSyncObject("modifierKeys", $modifierKeys),
new NanostoresSyncObject("gridCellData", $gridCellData),
new NanostoresSyncObject(
"collaborativeInstanceSelector",
$collaborativeInstanceSelector
),
new NanostoresSyncObject(
"collaborativeInstanceRect",
$collaborativeInstanceRect
),
new NanostoresSyncObject(
"registeredComponentMetas",
$registeredComponentMetas
),
new NanostoresSyncObject("registeredTemplates", $registeredTemplates),
new NanostoresSyncObject("canvasScrollbarWidth", $canvasScrollbarSize),
new NanostoresSyncObject("systemDataByPage", $systemDataByPage),
new NanostoresSyncObject("externalContentRoots", $externalContentRoots),
new NanostoresSyncObject("externalContentHistory", $externalContentHistory),
]);
};
declare global {
interface Window {
__webstudioSharedSyncEmitter__: SyncEmitter | undefined;
}
}
/**
* prevent syncEmitter interception from embedded scripts on canvas
* i.e., `globalThis.syncEmitter = () => console.log('INTERCEPTED');`,
*/
const sharedSyncEmitter =
typeof window === "undefined"
? undefined
: window.__webstudioSharedSyncEmitter__;
if (typeof window !== "undefined") {
delete window.__webstudioSharedSyncEmitter__;
}
export const useCanvasStore = () => {
useEffect(() => {
const canvasClient = new SyncClient({
role: "follower",
object: createObjectPool(),
emitter: sharedSyncEmitter,
});
const controller = new AbortController();
canvasClient.connect({ signal: controller.signal });
return () => {
controller.abort();
};
}, []);
};