mirror of
https://github.com/nexu-io/openmotion.git
synced 2026-12-02 08:59:26 +08:00
Show scoped block colors before the save completes (#977)
* Preview scoped block CSS colors while the edit saves * Read the confirmed block color after a version conflict * Resolve block colors against the mounted preview entry --------- Co-authored-by: lefarcen <935902669@qq.com>
This commit is contained in:
committed by
GitHub
parent
5aa01a9d57
commit
a7270133a2
@@ -27,15 +27,23 @@ function readDeclarations(html: string) {
|
||||
return owners;
|
||||
}
|
||||
|
||||
export function compositionVariableValues(html: string, parameterKeys: readonly string[] = []): Map<string, string> | null {
|
||||
export function readCompositionParameters(html: string, parameterKeys: readonly string[] = []) {
|
||||
const cssKeys = new Set<string>();
|
||||
const values = new Map<string, string>();
|
||||
for (const [id, owner] of readDeclarations(html)) {
|
||||
values.set(id, String(owner.variable.default ?? ''));
|
||||
}
|
||||
const cssKeys = parameterKeys.filter(key => !declaredParameterId(values.keys(), key));
|
||||
for (const [key, bindings] of cssBindings(html, cssKeys)) {
|
||||
if (bindings.length === 1) values.set(key, bindings[0]!.declaration.value);
|
||||
const undeclared = parameterKeys.filter(key => !declaredParameterId(values.keys(), key));
|
||||
for (const [key, bindings] of cssBindings(html, undeclared)) {
|
||||
if (bindings.length !== 1) continue;
|
||||
values.set(key, bindings[0]!.declaration.value);
|
||||
cssKeys.add(key);
|
||||
}
|
||||
return { values, cssKeys };
|
||||
}
|
||||
|
||||
export function compositionVariableValues(html: string, parameterKeys: readonly string[] = []): Map<string, string> | null {
|
||||
const { values } = readCompositionParameters(html, parameterKeys);
|
||||
return values.size ? values : null;
|
||||
}
|
||||
|
||||
|
||||
61
shared/preview-style-draft.ts
Normal file
61
shared/preview-style-draft.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
// Shared by direct and isolated previews. An older failure cannot roll back a newer draft.
|
||||
export function createStyleDrafts() {
|
||||
type Step = { value: string; saved: boolean };
|
||||
type Chain = { base: string; visible: string; steps: Step[] };
|
||||
const styles = new WeakMap<CSSStyleDeclaration, Map<string, Chain>>();
|
||||
return (style: CSSStyleDeclaration, name: string, value: string) => {
|
||||
if (style.getPropertyPriority(name)) return;
|
||||
let properties = styles.get(style);
|
||||
if (!properties) styles.set(style, properties = new Map());
|
||||
const actual = style.getPropertyValue(name);
|
||||
let chain = properties.get(name);
|
||||
if (!chain || chain.visible !== actual) {
|
||||
chain = { base: actual, visible: actual, steps: [] };
|
||||
properties.set(name, chain);
|
||||
}
|
||||
style.setProperty(name, value);
|
||||
const step = { value: style.getPropertyValue(name), saved: false };
|
||||
chain.visible = step.value;
|
||||
chain.steps.push(step);
|
||||
return (saved: boolean) => {
|
||||
if (properties.get(name) !== chain) return;
|
||||
if (style.getPropertyValue(name) !== chain.visible || style.getPropertyPriority(name)) {
|
||||
properties.delete(name);
|
||||
return;
|
||||
}
|
||||
step.saved = saved;
|
||||
if (!saved) chain.steps.splice(chain.steps.indexOf(step), 1);
|
||||
while (chain.steps[0]?.saved) chain.base = chain.steps.shift()!.value;
|
||||
const next = chain.steps.length ? chain.steps[chain.steps.length - 1]!.value : chain.base;
|
||||
if (next !== chain.visible) style.setProperty(name, next);
|
||||
chain.visible = next;
|
||||
if (!chain.steps.length) properties.delete(name);
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
// Only edit a mounted declaration when its entire selector belongs to the requested file.
|
||||
export function findBlockColorRule(doc: Document, path: string, key: string, value: string, entry?: string) {
|
||||
if (!/^--[a-zA-Z][\w-]{0,62}$/.test(key) || typeof value !== 'string' || value.length > 128 ||
|
||||
!doc.defaultView?.CSS?.supports('color', value) || /(?:url|var|attr|env)\s*\(|[;{}\\]/i.test(value)) return;
|
||||
let found: CSSStyleDeclaration | undefined;
|
||||
for (const sheet of Array.from(doc.styleSheets)) {
|
||||
if (sheet.ownerNode?.nodeName !== 'STYLE' || sheet.disabled || sheet.media?.mediaText) continue;
|
||||
for (const rule of Array.from(sheet.cssRules)) {
|
||||
if (!('selectorText' in rule) || !('style' in rule)) continue;
|
||||
const css = rule as CSSStyleRule;
|
||||
if (!css.style.getPropertyValue(key)) continue;
|
||||
let targets: Element[];
|
||||
try { targets = Array.from(doc.querySelectorAll(css.selectorText)); }
|
||||
catch { continue; } // CSS namespaces can produce selectors unavailable to querySelectorAll.
|
||||
const owned = (el: Element) => {
|
||||
const owner = el.closest('[data-composition-file],[data-composition-src]');
|
||||
return (owner?.getAttribute('data-composition-file') || owner?.getAttribute('data-composition-src') || entry) === path;
|
||||
};
|
||||
if (!targets.some(owned)) continue;
|
||||
if (found || !targets.every(owned)) return;
|
||||
found = css.style;
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
@@ -1,39 +1,17 @@
|
||||
// Visual feedback in the mounted frame while Studio saves an inspector edit.
|
||||
// Pending changes on a single property share its original value, so any order
|
||||
// of success or failure leaves the latest successful edit on screen.
|
||||
import { createStyleDrafts, findBlockColorRule } from '../../../shared/preview-style-draft.ts';
|
||||
|
||||
export const PREVIEW_INSPECTOR_STYLES = `
|
||||
const inspectorStyles = new WeakMap();
|
||||
const showStyleDraft = (${createStyleDrafts.toString()})();
|
||||
const blockColorRule = ${findBlockColorRule.toString()};
|
||||
const pendingInspectorStyles = new Map();
|
||||
const visibleStyleNames = new Set(['color','background-color','font-size','font-weight','text-align','opacity']);
|
||||
function showInspectorStyle(el, name, value) {
|
||||
if (!visibleStyleNames.has(name) || typeof value !== 'string' || value.length > 256 ||
|
||||
(value && !CSS.supports(name, value)) || el.style.getPropertyPriority(name)) return null;
|
||||
let properties = inspectorStyles.get(el);
|
||||
if (!properties) inspectorStyles.set(el, properties = new Map());
|
||||
const actual = el.style.getPropertyValue(name);
|
||||
let chain = properties.get(name);
|
||||
if (!chain || chain.visible !== actual) {
|
||||
chain = {base:actual, visible:actual, steps:[]};
|
||||
properties.set(name, chain);
|
||||
}
|
||||
el.style.setProperty(name, value);
|
||||
const step = {value:el.style.getPropertyValue(name), saved:false};
|
||||
chain.visible = step.value;
|
||||
chain.steps.push(step);
|
||||
return saved => {
|
||||
if (properties.get(name) !== chain) return;
|
||||
if (el.style.getPropertyValue(name) !== chain.visible || el.style.getPropertyPriority(name)) {
|
||||
properties.delete(name);
|
||||
return;
|
||||
}
|
||||
step.saved = saved;
|
||||
if (!saved) chain.steps.splice(chain.steps.indexOf(step), 1);
|
||||
while (chain.steps[0]?.saved) chain.base = chain.steps.shift().value;
|
||||
const next = chain.steps.length ? chain.steps[chain.steps.length - 1].value : chain.base;
|
||||
if (next !== chain.visible) el.style.setProperty(name, next);
|
||||
chain.visible = next;
|
||||
if (!chain.steps.length) properties.delete(name);
|
||||
};
|
||||
return showStyleDraft(el.style, name, value);
|
||||
}
|
||||
function previewInspectorStyles(m) {
|
||||
if (typeof m.editId !== 'string' || m.editId.length > 80) return;
|
||||
@@ -43,9 +21,16 @@ export const PREVIEW_INSPECTOR_STYLES = `
|
||||
if (pending) pending.forEach(finish => finish(m.saved === true));
|
||||
return;
|
||||
}
|
||||
if (m.phase !== 'show' || pendingInspectorStyles.has(m.editId) || !Array.isArray(m.styles) ||
|
||||
m.styles.length > 32 || typeof m.sourceFile !== 'string' ||
|
||||
if (m.phase !== 'show' || pendingInspectorStyles.has(m.editId) || typeof m.sourceFile !== 'string' ||
|
||||
!Object.hasOwn(sourceVersions, m.sourceFile) || sourceIdentity(sourceVersions[m.sourceFile]).fileVersion !== m.fileVersion) return;
|
||||
if (m.blockColor) {
|
||||
const { key, value } = m.blockColor;
|
||||
const rule = blockColorRule(document, m.sourceFile, key, value, compositionPath);
|
||||
const finish = rule && showStyleDraft(rule, key, value);
|
||||
if (finish) pendingInspectorStyles.set(m.editId, [finish]);
|
||||
return;
|
||||
}
|
||||
if (!Array.isArray(m.styles) || m.styles.length > 32) return;
|
||||
const el = inspectorElement(m);
|
||||
if (!el || el.closest('[data-hf-parked-scene]')) return;
|
||||
const pending = m.styles.filter(pair => Array.isArray(pair) && pair.length === 2)
|
||||
|
||||
@@ -282,6 +282,7 @@ export const StudioRightPanels = memo(function StudioRightPanels({
|
||||
designBody = (
|
||||
<BlockParamsPanel
|
||||
key={JSON.stringify([projectId, activeBlockParams.compositionPath])}
|
||||
previewIframeRef={previewIframeRef}
|
||||
blockName={activeBlockParams.blockName}
|
||||
blockTitle={activeBlockParams.blockTitle}
|
||||
params={activeBlockParams.params}
|
||||
|
||||
@@ -7,6 +7,7 @@ import type { BlockParam } from "@hyperframes/core/registry";
|
||||
import { FileManagerProvider } from "../../contexts/FileManagerContext";
|
||||
import type { useFileManager } from "../../hooks/useFileManager";
|
||||
import { StudioPlaybackProvider, type StudioPlaybackValue } from "../../contexts/StudioContext";
|
||||
import { StudioFileConflictError } from "../../utils/studioSaveDiagnostics";
|
||||
import { BlockParamsPanel } from "./BlockParamsPanel";
|
||||
import { I18nProvider, useI18n, type Locale } from "../../i18n/I18n";
|
||||
|
||||
@@ -224,6 +225,21 @@ describe("BlockParamsPanel commit safety", () => {
|
||||
expect(document.body.textContent).toContain("appears 2×");
|
||||
});
|
||||
|
||||
it("restores the other editor's confirmed color after a real version conflict", async () => {
|
||||
const content = { value: "<style>.title { --bg-color: #0c0c0c; }</style>" };
|
||||
const fm = makeFileManager(content);
|
||||
fm.writeProjectFile.mockRejectedValueOnce(new StudioFileConflictError({
|
||||
filePath: "compositions/vfx-demo.html", currentVersion: "new",
|
||||
currentContent: content.value.replace("#0c0c0c", "#778899"), attemptedContent: "", syncLatest: true,
|
||||
}));
|
||||
renderPanel(fm.value);
|
||||
await flushCommit();
|
||||
changeParam("Background", "#123456");
|
||||
await flushCommit();
|
||||
expect(document.querySelector('[aria-label="Pick background color"]')?.textContent).toContain("778899");
|
||||
expect(document.querySelector('[role="alert"]')?.textContent).toContain("changed elsewhere");
|
||||
});
|
||||
|
||||
it("keeps a pending commit for one param when another param is edited", async () => {
|
||||
const content = {
|
||||
value: ".a { background: #0c0c0c; } .b { color: #fafafa; }",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { IconButton } from "open-design-ui/icon-button";
|
||||
import { OverflowText } from "../ui/OverflowText";
|
||||
import { previewBlockColor } from "./blockColorDraft";
|
||||
import { ColorField } from "./propertyPanelColor";
|
||||
import { FieldInput, NativeSelect } from "../ui/FormField";
|
||||
import { RemixIcon } from "../../icons/RemixIcons";
|
||||
@@ -10,6 +11,7 @@ import type { BlockParam } from "@hyperframes/core/registry";
|
||||
import { useFileManagerContextOptional } from "../../contexts/FileManagerContext";
|
||||
import { useStudioPlaybackContext } from "../../contexts/StudioContext";
|
||||
import { trackBlockParamCommit } from "../../telemetry/events";
|
||||
import { StudioFileConflictError } from "../../utils/studioSaveDiagnostics";
|
||||
import { createTypingSave } from "../../utils/typingSave";
|
||||
import { serializeStudioFileMutation } from "../../utils/studioFileMutationCoordinator";
|
||||
const loadParameterEditor = () => import("../../../../packages/edit-core/composition-variable");
|
||||
@@ -19,6 +21,7 @@ interface BlockParamsPanelProps {
|
||||
blockTitle: string;
|
||||
params: BlockParam[];
|
||||
compositionPath: string;
|
||||
previewIframeRef?: React.RefObject<HTMLIFrameElement | null>;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
@@ -29,6 +32,7 @@ export const BlockParamsPanel = memo(function BlockParamsPanel({
|
||||
blockTitle,
|
||||
params,
|
||||
compositionPath,
|
||||
previewIframeRef,
|
||||
onClose,
|
||||
}: BlockParamsPanelProps) {
|
||||
const { t } = useI18n();
|
||||
@@ -49,14 +53,20 @@ export const BlockParamsPanel = memo(function BlockParamsPanel({
|
||||
const [commitState, setCommitState] = useState<CommitState>({ tone: "idle" });
|
||||
const queues = useRef(new Map<string, ReturnType<typeof createTypingSave>>());
|
||||
|
||||
const previewable = useRef(new Set<string>());
|
||||
const needsRefresh = useRef(false);
|
||||
const drafts = useRef(new Map<string, { submitted: boolean; settle?: (saved: boolean) => void }>());
|
||||
const edited = useRef(new Set<string>());
|
||||
const read = fileManager?.readProjectFile;
|
||||
useEffect(() => {
|
||||
if (!read) return;
|
||||
let current = true;
|
||||
void Promise.all([read(compositionPath), loadParameterEditor()]).then(([content, editor]) => {
|
||||
const declared = editor.compositionVariableValues(content, params.map(param => param.key));
|
||||
if (!current || !declared) return;
|
||||
if (!current) return;
|
||||
const { values: declared, cssKeys } = editor.readCompositionParameters(content, params.map(param => param.key));
|
||||
// Canvas and GPU textures may capture colors once during startup. Rebuild these after saving.
|
||||
previewable.current = /<canvas\b/i.test(content) ? new Set() :
|
||||
new Set(params.filter(param => param.type === "color" && cssKeys.has(param.key)).map(param => param.key));
|
||||
const saved: Record<string, string> = {};
|
||||
for (const param of params) {
|
||||
const id = editor.declaredParameterId(declared.keys(), param.key);
|
||||
@@ -69,10 +79,10 @@ export const BlockParamsPanel = memo(function BlockParamsPanel({
|
||||
}, [compositionPath, params, read]);
|
||||
|
||||
const commitParamNow = useCallback(
|
||||
async (key: string, nextValue: string) => {
|
||||
if (!fileManager) return;
|
||||
async (key: string, nextValue: string, isCurrent: () => boolean) => {
|
||||
if (!fileManager) return false;
|
||||
const previous = appliedRef.current[key];
|
||||
if (previous === undefined) return;
|
||||
if (previous === undefined) return false;
|
||||
setCommitState({ tone: "saving" });
|
||||
try {
|
||||
const [content, editor] = await Promise.all([fileManager.readProjectFile(compositionPath), loadParameterEditor()]);
|
||||
@@ -83,24 +93,39 @@ export const BlockParamsPanel = memo(function BlockParamsPanel({
|
||||
});
|
||||
}
|
||||
appliedRef.current[key] = nextValue;
|
||||
setCommitState({ tone: "saved" });
|
||||
if (isCurrent()) setCommitState({ tone: "saved" });
|
||||
trackBlockParamCommit({ tone: "saved", blockName, key });
|
||||
setRefreshKey((k) => k + 1);
|
||||
return true;
|
||||
} catch (error) {
|
||||
setValues(drafts => drafts[key] === nextValue ? { ...drafts, [key]: previous } : drafts);
|
||||
setCommitState({ tone: "error", message: error instanceof Error ? error.message : "Couldn't save the block file. Retry?" });
|
||||
let confirmed = previous;
|
||||
if (error instanceof StudioFileConflictError && error.filePath === compositionPath) {
|
||||
try {
|
||||
const [source, editor] = await Promise.all([
|
||||
error.currentContent ?? fileManager.readProjectFile(compositionPath), loadParameterEditor(),
|
||||
]);
|
||||
const values = editor.compositionVariableValues(source, [key]);
|
||||
const id = values && editor.declaredParameterId(values.keys(), key);
|
||||
if (values && id) confirmed = values.get(id) ?? previous;
|
||||
} catch { /* Keep the last known value if the current file is unavailable. */ }
|
||||
appliedRef.current[key] = confirmed;
|
||||
}
|
||||
if (isCurrent()) {
|
||||
setValues(drafts => ({ ...drafts, [key]: confirmed }));
|
||||
setCommitState({ tone: "error", message: error instanceof Error ? error.message : "Couldn't save the block file. Retry?" });
|
||||
}
|
||||
trackBlockParamCommit({ tone: "error", blockName, key });
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[fileManager, compositionPath, setRefreshKey, blockName],
|
||||
[fileManager, compositionPath, blockName],
|
||||
);
|
||||
|
||||
// Commits join the file's queue: two read-modify-writes of one file must not interleave.
|
||||
const commitParam = useCallback(
|
||||
(key: string, nextValue: string) =>
|
||||
(key: string, nextValue: string, isCurrent: () => boolean) =>
|
||||
fileManager
|
||||
? serializeStudioFileMutation(fileManager.writeProjectFile, compositionPath, () =>
|
||||
commitParamNow(key, nextValue),
|
||||
commitParamNow(key, nextValue, isCurrent),
|
||||
)
|
||||
: Promise.resolve(),
|
||||
[commitParamNow, compositionPath, fileManager],
|
||||
@@ -112,7 +137,23 @@ export const BlockParamsPanel = memo(function BlockParamsPanel({
|
||||
if (composing) return;
|
||||
let queue = queues.current.get(key);
|
||||
if (!queue) queues.current.set(key, queue = createTypingSave(300));
|
||||
queue.schedule(() => commitParam(key, value));
|
||||
const prior = drafts.current.get(key);
|
||||
const draft = { submitted: false, settle: previewable.current.has(key)
|
||||
? previewBlockColor(previewIframeRef?.current, compositionPath, key, value) : undefined };
|
||||
drafts.current.set(key, draft);
|
||||
if (prior && !prior.submitted) prior.settle?.(false);
|
||||
queue.schedule(async () => {
|
||||
draft.submitted = true;
|
||||
const saved = await commitParam(key, value, () => drafts.current.get(key) === draft);
|
||||
draft.settle?.(saved === true);
|
||||
if (saved) needsRefresh.current = true;
|
||||
if (drafts.current.get(key) !== draft) return;
|
||||
drafts.current.delete(key);
|
||||
if (needsRefresh.current && !drafts.current.size) {
|
||||
needsRefresh.current = false;
|
||||
setRefreshKey((k) => k + 1);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => () => {
|
||||
|
||||
21
studio/src/components/editor/blockColorDraft.ts
Normal file
21
studio/src/components/editor/blockColorDraft.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { createStyleDrafts, findBlockColorRule } from '../../../../shared/preview-style-draft';
|
||||
import { createPreviewAdapter } from '../../player/lib/previewAdapter';
|
||||
import { confirmedSource } from '../../utils/confirmedTextSources';
|
||||
import { compositionPathOfPreviewUrl } from '../../utils/projectCompositionPath';
|
||||
|
||||
const showStyleDraft = createStyleDrafts();
|
||||
|
||||
export function previewBlockColor(frame: HTMLIFrameElement | null | undefined, sourceFile: string, key: string, value: string) {
|
||||
if (!frame) return;
|
||||
const adapter = createPreviewAdapter({ iframe: frame });
|
||||
const doc = adapter.document();
|
||||
if (doc) {
|
||||
const style = findBlockColorRule(doc, sourceFile, key, value, compositionPathOfPreviewUrl(doc.URL));
|
||||
return style && showStyleDraft(style, key, value);
|
||||
}
|
||||
const fileVersion = adapter.projectId && confirmedSource(adapter.projectId, sourceFile)?.version;
|
||||
if (!fileVersion) return;
|
||||
const editId = crypto.randomUUID();
|
||||
adapter.send('inspector-styles', { phase: 'show', editId, sourceFile, fileVersion, blockColor: { key, value } });
|
||||
return (saved: boolean) => adapter.send('inspector-styles', { phase: 'settle', editId, saved });
|
||||
}
|
||||
@@ -16,6 +16,8 @@ import {
|
||||
} from "./thumbnailUtils";
|
||||
import { useValueAtRest } from "./timelineMotion";
|
||||
import { getCachedCloudDisklessMode } from "../../utils/cloudRuntime";
|
||||
import { compositionPathOfPreviewUrl } from "../../utils/projectCompositionPath";
|
||||
export { compositionPathOfPreviewUrl } from "../../utils/projectCompositionPath";
|
||||
import {
|
||||
compositionDisplayName,
|
||||
loadCloudCompositionPoster,
|
||||
@@ -114,12 +116,6 @@ export function buildCompositionThumbnailUrl({
|
||||
return thumbnailUrl.toString();
|
||||
}
|
||||
|
||||
/** The composition a preview URL renders: `/preview/comp/<path>`, or the root for `/preview`. */
|
||||
export function compositionPathOfPreviewUrl(previewUrl: string): string {
|
||||
const match = /\/preview\/comp\/([^?#]+)/.exec(previewUrl);
|
||||
return match?.[1] ? decodeURIComponent(match[1]) : "index.html";
|
||||
}
|
||||
|
||||
export function compositionThumbnailRequest(
|
||||
url: string,
|
||||
projectId: string,
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { buildProjectApiPath, parseProjectIdFromHash } from "./projectRouting";
|
||||
|
||||
/** The composition a preview URL renders: `/preview/comp/<path>`, or the root for `/preview`. */
|
||||
export function compositionPathOfPreviewUrl(previewUrl: string): string {
|
||||
const match = /\/preview\/comp\/([^?#]+)/.exec(previewUrl);
|
||||
return match?.[1] ? decodeURIComponent(match[1]) : "index.html";
|
||||
}
|
||||
|
||||
/** Convert runtime preview URLs to the same file identity used by authored paths. */
|
||||
export function projectCompositionPath(
|
||||
source: string,
|
||||
|
||||
@@ -2,6 +2,7 @@ import assert from 'node:assert/strict';
|
||||
import { it } from 'node:test';
|
||||
import { runInNewContext } from 'node:vm';
|
||||
import { PREVIEW_INSPECTOR_STYLES } from '../../src/studio/engine/preview-inspector-styles.ts';
|
||||
import { findBlockColorRule } from '../../shared/preview-style-draft.ts';
|
||||
|
||||
function inspector() {
|
||||
let size = '42px';
|
||||
@@ -51,3 +52,54 @@ it('ignores stale targets and leaves a later runtime style alone on failure', ()
|
||||
view.settle('a', false);
|
||||
assert.equal(view.get(), '54px');
|
||||
});
|
||||
|
||||
it('only paints a CSS color rule whose selector belongs exclusively to the edited file', () => {
|
||||
let color = '#333333';
|
||||
const style = {
|
||||
getPropertyValue: (name: string) => name === '--title' ? color : '',
|
||||
getPropertyPriority: () => '',
|
||||
setProperty: (_name: string, value: string) => { color = value; },
|
||||
};
|
||||
let files = ['intro.html', 'intro.html'];
|
||||
const document = {
|
||||
defaultView: { CSS: { supports: () => true } },
|
||||
styleSheets: [{ ownerNode: { nodeName: 'STYLE' }, cssRules: [{ selectorText: '.intro', style }] }],
|
||||
querySelectorAll: () => files.map(path => ({ closest: () => ({ getAttribute: () => path }) })),
|
||||
};
|
||||
const send = runInNewContext(PREVIEW_INSPECTOR_STYLES + '\npreviewInspectorStyles', {
|
||||
document, sourceVersions: { 'intro.html': 'v1' }, sourceIdentity: (fileVersion: string) => ({ fileVersion }),
|
||||
compositionPath: 'index.html',
|
||||
});
|
||||
const show = (id: string, value: string, fileVersion = 'v1') => send({
|
||||
phase: 'show', editId: id, sourceFile: 'intro.html', fileVersion, blockColor: { key: '--title', value },
|
||||
});
|
||||
show('stale', '#aaaaaa', 'v0');
|
||||
assert.equal(color, '#333333');
|
||||
show('invalid', 'url(https://example.test)');
|
||||
assert.equal(color, '#333333');
|
||||
show('first', '#aaaaaa');
|
||||
show('second', '#bbbbbb');
|
||||
send({ phase: 'settle', editId: 'first', saved: false });
|
||||
assert.equal(color, '#bbbbbb');
|
||||
send({ phase: 'settle', editId: 'second', saved: false });
|
||||
assert.equal(color, '#333333');
|
||||
files = ['intro.html', 'other.html'];
|
||||
show('shared', '#cccccc');
|
||||
assert.equal(color, '#333333');
|
||||
});
|
||||
|
||||
it('recognizes the shipped root color selector when the block is previewed on its own', () => {
|
||||
const path = 'compositions/logo-outro.html';
|
||||
const selector = 'html:has(> body > [data-composition-id="logo-outro"]), [data-composition-id="logo-outro"]';
|
||||
const style = { getPropertyValue: (key: string) => key === '--bg-color' ? '#0a0a0f' : '' };
|
||||
const doc = {
|
||||
defaultView: { CSS: { supports: () => true } },
|
||||
styleSheets: [{ ownerNode: { nodeName: 'STYLE' }, cssRules: [{ selectorText: selector, style }] }],
|
||||
querySelectorAll: (query: string) => {
|
||||
assert.equal(query, selector);
|
||||
return [{ closest: () => null }, { closest: () => ({ getAttribute: () => path }) }];
|
||||
},
|
||||
} as unknown as Document;
|
||||
assert.equal(findBlockColorRule(doc, path, '--bg-color', '#123456', path), style);
|
||||
assert.equal(findBlockColorRule(doc, path, '--bg-color', '#123456', 'index.html'), undefined);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user