Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/features/style/StylePanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ interface StylePanelProps {
readonly onRemoveClass?: HostState['removeClass'] | undefined;
readonly onRemoveAttribute?: HostState['removeAttribute'] | undefined;
readonly onSpacingHover?: HostState['onSpacingHover'];
readonly onPreviewRule?: HostState['previewRule'];
readonly renderedClasses?: readonly string[] | undefined;
readonly projectClasses?: readonly string[] | undefined;
readonly historyTick?: number;
Expand Down Expand Up @@ -102,6 +103,7 @@ function hostState(props: StylePanelProps, files: StyleFiles, astroFiles: StyleF
removeClass: props.onRemoveClass,
removeAttribute: props.onRemoveAttribute,
onSpacingHover: props.onSpacingHover,
previewRule: props.onPreviewRule,
renderedClasses: [...(props.renderedClasses ?? [])],
projectClasses: [...(props.projectClasses ?? [])],
historyTick: props.historyTick ?? 0,
Expand Down
7 changes: 7 additions & 0 deletions src/features/style/embed/useEditorRuleEdits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ export function usePropEdits(splitForEditHook: ReturnType<typeof useSplitForEdit
// commit would double-add. Update-or-add on set; remove every match on clear.
const onSetProp = useCallback(
(rule: ParsedRule, prop: string, value: string, important: boolean) => {
previewOnCanvas(rule, { prop, value, important });
void applyEdit(rule, () => {
const { rule: editRule } = splitForEdit(rule);
if (isPaddingProperty(prop)) {
Expand Down Expand Up @@ -249,6 +250,7 @@ export function useLiveEdits(
if (!embedDocument) {
continue;
}
previewOnCanvas(rule, { prop, value, important });
const matches = declsFor(rule, prop);
const target = matches[matches.length - 1];
if (!liveOriginRef.current.has(prop)) {
Expand Down Expand Up @@ -448,3 +450,8 @@ export function useElementTokens(scanState: ReturnType<typeof useScanState>) {
const instanceClasses = useMemo(() => selectedInstanceClasses(snapshot?.classList ?? []), [snapshot]);
return { instanceClasses, model, scan, selectorSuggestions, snapshot, tokens };
}

// The canvas shows the edit before the save and re-render land (host.previewRule).
function previewOnCanvas(rule: ParsedRule, declaration: { readonly prop: string; readonly value: string; readonly important: boolean }): void {
getHost().previewRule?.({ selector: rule.selectorText, atContext: rule.atContext, ...declaration });
}
13 changes: 13 additions & 0 deletions src/features/style/model/host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,18 @@ export type HostState = {
* One project-level setting from the scan (shared/properties/lengthUnit.ts),
* read through model/lengthUnit.ts so no control decides it for itself. */
lengthUnit: LengthUnit;
/** Show an edited declaration on the canvas right away, before the source is saved
* and the page re-renders (emdash-stacki's fork). Absent where the host can't. */
previewRule: ((change: LiveRuleChange) => void) | undefined;
};

/** An edited declaration, for a canvas that can show it before the source is saved. */
export type LiveRuleChange = {
readonly selector: string;
readonly atContext: readonly string[];
readonly prop: string;
readonly value: string;
readonly important: boolean;
};

export type PseudoRequest = { readonly nodeId: string; readonly pseudo: 'before' | 'after'; readonly serial: number };
Expand Down Expand Up @@ -182,6 +194,7 @@ const state: HostState = {
pseudoRows: false,
lengthUnit: PX_LENGTHS,
onSpacingHover: undefined,
previewRule: undefined,
};

const listeners = new Set<() => void>();
Expand Down
6 changes: 5 additions & 1 deletion studio/src/features/preview/PreviewCanvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ import { PreviewOverlays } from '../../../vendor/stacki/src/features/preview/Pre
import { GuideOverlay } from '../../../vendor/stacki/src/features/preview/GuideOverlay';
import { useColumnGuide, type ShownGuide } from '../../../vendor/stacki/src/features/preview/guideSettings';
import { outlineInfo, outlineNode } from './outlineInfo';
import { useMemo, useRef, type CSSProperties } from 'react';
import { useEffect, useMemo, useRef, type CSSProperties } from 'react';
import { liveRuleBus } from './liveRuleBus';
import { PreviewToolbar, type PreviewDevice, type PreviewInspectorActions } from '../../../vendor/stacki/src/features/preview/PreviewToolbar';
import CanvasView from '../../../vendor/stacki/src/features/preview/CanvasView';
import { usePreviewSizing } from '../../../vendor/stacki/src/features/preview/usePreviewSizing';
Expand Down Expand Up @@ -65,6 +66,9 @@ export function PreviewCanvas(props: Props) {
pages: props.sitePages,
});
const sizing = usePreviewSizing(props.device, props.dimensions, props.onDevice);
// The style panel's edits reach the canvas before the save does (liveRules.ts).
const send = props.preview.send;
useEffect(() => liveRuleBus.listen((rule) => send({ type: 'studio:live-rule', ...rule })), [send]);
useCursorScale(props.preview, sizing.viewport.scale);
useCursorChatShortcut({
preview: props.preview,
Expand Down
20 changes: 20 additions & 0 deletions studio/src/features/preview/liveRuleBus.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// The style panel's edits on their way to the canvas (liveRules.ts there). The panel
// emits; the preview canvas, which holds the frame, forwards each edit to it.
import type { LiveRule } from './liveRules';

type Listener = (rule: LiveRule) => void;
const listeners = new Set<Listener>();

export const liveRuleBus = {
emit(rule: LiveRule): void {
for (const listener of listeners) {
listener(rule);
}
},
listen(listener: Listener): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
};
157 changes: 157 additions & 0 deletions studio/src/features/preview/liveRules.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
// Style panel edits shown on the canvas at once. An edit used to appear only after the source
// was saved and the page re-rendered on the server, about half a second later. The panel now
// also sends the edited rule here, and the canvas sets the property on the same rule in its
// loaded stylesheets. The real update follows with the same content and replaces these
// sheets, which corrects anything this could not match (it then does nothing: a new rule, a
// nested one, or a selector it does not recognise).

import { record, string } from '../../shared/validation';

export interface LiveRule {
readonly selector: string;
/** Enclosing at-rules, outermost first, as the source writes them (`@media (max-width: 767px)`). */
readonly atContext: readonly string[];
readonly prop: string;
readonly value: string;
readonly important: boolean;
}

const RULES_VISITED_MAX = 20_000;
const AT_CONTEXT_MAX = 8;
const PROPERTY = /^(--[\w-]+|-?[a-z][a-z0-9-]*)$/;

/** Parse a `studio:live-rule` message from Studio; anything else is undefined. */
export function parseLiveRule(input: unknown): LiveRule | undefined {
try {
const data = record(input);
if (data['type'] !== 'studio:live-rule') {
return undefined;
}
const atContext = data['atContext'];
if (!Array.isArray(atContext) || atContext.length > AT_CONTEXT_MAX) {
return undefined;
}
const rule: LiveRule = {
selector: string(data['selector'], 2000),
atContext: atContext.map((entry) => string(entry, 500)),
prop: string(data['prop'], 120),
value: string(data['value'], 2000),
important: data['important'] === true,
};
return PROPERTY.test(rule.prop) && rule.selector.length > 0 ? rule : undefined;
} catch {
return undefined;
}
}

/** A selector without Astro's scoping and with uniform spacing, for comparing source and CSSOM. */
export function normalizeSelector(selector: string): string {
return selector
.replace(/\[data-astro-cid-[\w-]+\]/g, '')
.replace(/:where\(\.astro-[\w-]+\)/g, '')
.replace(/\s*([>+~,])\s*/g, '$1')
.replace(/\s+/g, ' ')
.trim();
}

/** An at-rule prelude with all spacing removed, so `(max-width:767px)` and `( max-width: 767px )` match. */
export function normalizeAtRule(prelude: string): string {
return prelude.replace(/\s+/g, '').toLowerCase();
}

// The rule classes of the document's own window: the canvas frame's, and in tests a jsdom
// window's. A window that lacks a class (an older browser, jsdom) has no such rules either.
interface RuleClasses {
readonly style: typeof CSSStyleRule;
readonly media: typeof CSSMediaRule | undefined;
readonly supports: typeof CSSSupportsRule | undefined;
readonly container: typeof CSSContainerRule | undefined;
readonly layer: typeof CSSLayerBlockRule | undefined;
}

function ruleClassesOf(view: Window & typeof globalThis): RuleClasses {
return {
style: view.CSSStyleRule,
media: view.CSSMediaRule,
supports: view.CSSSupportsRule,
container: view.CSSContainerRule,
layer: view.CSSLayerBlockRule,
};
}

function atRuleOf(rule: CSSRule, classes: RuleClasses): string | undefined {
if (classes.media && rule instanceof classes.media) {
return `@media ${rule.media.mediaText}`;
}
if (classes.supports && rule instanceof classes.supports) {
return `@supports ${rule.conditionText}`;
}
if (classes.container && rule instanceof classes.container) {
return `@container ${rule.containerName} ${rule.containerQuery}`.replace(/\s+/, ' ');
}
if (classes.layer && rule instanceof classes.layer) {
return `@layer ${rule.name}`;
}
return undefined;
}

function isCondition(prelude: string): boolean {
return !prelude.startsWith('@layer');
}

/** Set the edited property on every matching rule in the document's stylesheets; returns how many. */
export function applyLiveRule(document: Document, live: LiveRule): number {
const view = document.defaultView;
if (view === null) {
return 0;
}
const classes = ruleClassesOf(view);
const selector = normalizeSelector(live.selector);
// Layers order the cascade but don't change which elements a rule matches, and the panel's
// context may leave them out, so only the conditions (@media, @supports, @container) compare.
const context = live.atContext.map(normalizeAtRule).filter(isCondition);
let visited = 0;
let applied = 0;
// Iterative: each entry is a rule list and the at-rule chain around it.
const pending: { readonly rules: CSSRuleList; readonly chain: readonly string[] }[] = [];
for (const sheet of document.styleSheets) {
try {
pending.push({ rules: sheet.cssRules, chain: [] });
} catch {
// A cross-origin sheet cannot be read, and holds none of the site's own rules.
}
}
while (pending.length > 0 && visited < RULES_VISITED_MAX) {
const entry = pending.pop();
if (!entry) {
break;
}
for (const rule of entry.rules) {
visited += 1;
if (rule instanceof classes.style) {
const chain = entry.chain.filter(isCondition);
const sameContext = chain.length === context.length && chain.every((prelude, index) => prelude === context[index]);
if (sameContext && normalizeSelector(rule.selectorText) === selector) {
rule.style.setProperty(live.prop, live.value, live.important ? 'important' : '');
applied += 1;
}
continue;
}
const prelude = atRuleOf(rule, classes);
if (prelude !== undefined && 'cssRules' in rule && rule.cssRules instanceof view.CSSRuleList && entry.chain.length < AT_CONTEXT_MAX) {
pending.push({ rules: rule.cssRules, chain: [...entry.chain, normalizeAtRule(prelude)] });
}
}
}
return applied;
}

/** Apply a live rule message, if this is one. */
export function receiveLiveRule(input: unknown): boolean {
const live = parseLiveRule(input);
if (live === undefined) {
return false;
}
applyLiveRule(document, live);
return true;
}
4 changes: 4 additions & 0 deletions studio/src/features/preview/previewClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
} from '../../../vendor/stacki/electron/preload/frameInteraction';
import { freezeViewportHeight, report as reportPageHeight } from '../../../vendor/stacki/electron/preload/frameViewport';
import { receiveLiveNumericStyles, applyLiveNumericStyles } from './liveNumericStyles';
import { receiveLiveRule } from './liveRules';
import { receiveLiveText, applyLiveText } from './liveTextClient';
import { installCursorPresence } from '../collaboration/cursorClient';
import { receiveRenderPush } from './renderPushClient';
Expand Down Expand Up @@ -235,6 +236,9 @@ window.addEventListener('message', (event) => {
}
receiveLiveText(data);
receiveLiveNumericStyles(data);
if (receiveLiveRule(data)) {
return;
}
cursorPresence.receive(data);
columnGuide.receive(data);
if (data.type === 'studio:collaborators' && 'paths' in data && Array.isArray(data.paths)) {
Expand Down
2 changes: 2 additions & 0 deletions studio/src/features/settings/StyleSettings.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { spacingHover } from '../preview/spacingHover';
import { liveRuleBus } from '../preview/liveRuleBus';
import { LockedSettings } from './LockedSettings';
import { useEffect, useMemo } from 'react';
import StylePanel from '../../../vendor/stacki/src/features/style/StylePanel';
Expand Down Expand Up @@ -79,6 +80,7 @@ export function StyleSettings({
}
}}
onSpacingHover={spacingHover.set}
onPreviewRule={liveRuleBus.emit}
onRecordUndo={(command) => document.recordCommand(command)}
/>
</PanelBoundary>
Expand Down
Loading
Loading