Repository navigation
Expand file tree
/
Copy pathElementsPanel.btsx
More file actions
209 lines (206 loc) · 14.1 KB
/
Copy pathElementsPanel.btsx
File metadata and controls
209 lines (206 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import { useEffect, useRef, useState } from 'octane'
import { groupAttributes, groupProperties, groupStyles, type ElementSection } from './element-groups.ts'
import { COMMON_STYLES, snapshotKey, type ElementInspection, type ElementPropertyGroup } from './element-inspector.ts'
import SquishSwitch from '../components/squishy.btsx'
import ElementPropertyRow from './ElementPropertyRow.btsx'
import StylesheetsPanel from './StylesheetsPanel.btsx'
import type { ElementStyleTarget } from '../shared/types.ts'
import { cx } from './util.ts'
import { openInEditor } from './api.ts'
module
interface ElementsPanelProps {
inspection: ElementInspection | null
onPick: () => void
}
type ElementPanelGroup = ElementPropertyGroup | 'stylesheets'
const GROUPS: ReadonlyArray<{ id: ElementPanelGroup; label: string }> = [
{ id: 'stylesheets', label: 'Stylesheet rules' },
{ id: 'styles', label: 'Computed styles' },
{ id: 'attributes', label: 'Attributes' },
{ id: 'properties', label: 'DOM properties' },
]
props { inspection, onPick }: ElementsPanelProps
setup
const [snapshot, setSnapshot] = useState(() => inspection?.capture() ?? null);
const [savedSnapshot, setSavedSnapshot] = useState(() => inspection?.capture() ?? null);
const savedKey = useRef<string | null>(null);
const [styleTarget, setStyleTarget] = useState<ElementStyleTarget>(inspection?.styleTarget ?? 'tailwind');
const [cssPath, setCssPath] = useState(inspection?.cssPath ?? '');
const [cssSelector, setCssSelector] = useState(inspection?.cssSelector ?? '');
const chooseStyleTarget = (target: ElementStyleTarget) => { setStyleTarget(target); if (inspection) inspection.styleTarget = target; };
const [group, setGroup] = useState<ElementPanelGroup>('stylesheets');
const [query, setQuery] = useState('');
const [showAll, setShowAll] = useState(false);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const [newName, setNewName] = useState('');
const [newValue, setNewValue] = useState('');
const [undoCount, setUndoCount] = useState(inspection?.undoCount ?? 0);
const lastKey = useRef<string | null>(null);
const refresh = () => {
setSaving(inspection?.saving ?? false);
setUndoCount(inspection?.undoCount ?? 0);
const next = inspection?.capture() ?? null;
const key = snapshotKey(next);
if (!inspection?.saving && !inspection?.error && key !== savedKey.current) {
savedKey.current = key;
setSavedSnapshot(next);
}
// Captures are fresh objects every time; only publish when the content
// actually changed, so idle ticks skip the re-render entirely.
if (key === lastKey.current) return;
lastKey.current = key;
setSnapshot(next);
setUndoCount(inspection?.undoCount ?? 0);
};
useEffect(() => {
// A new inspection starts unmatched, even if its content equals the last one.
lastKey.current = null;
savedKey.current = null;
refresh();
setError(inspection?.error ?? null);
setQuery('');
if (inspection) { setStyleTarget(inspection.styleTarget); setCssPath(inspection.cssPath); setCssSelector(inspection.cssSelector); }
if (!inspection) return;
// Attributes, layout and runtime values can change independently of DevTools.
const timer = window.setInterval(() => { if (!document.hidden) refresh(); }, 1000);
const unsubscribe = inspection.subscribe(() => { setError(inspection.error); refresh(); });
return () => { window.clearInterval(timer); unsubscribe(); };
}, [inspection]);
const edit = async (name: string, value: string | null, editGroup: ElementPropertyGroup = group === 'stylesheets' ? 'styles' : group) => {
if (!inspection) return;
try {
await inspection.edit(editGroup, name, value);
setError(null);
refresh();
} catch (failure) { setError(failure instanceof Error ? failure.message : String(failure)); }
};
const undo = async () => {
if (!inspection) return;
try { await inspection.undo(); setError(null); refresh(); }
catch (failure) { setError(failure instanceof Error ? failure.message : String(failure)); }
};
const chooseGroup = (next: ElementPanelGroup) => { setGroup(next); setQuery(''); setNewName(''); setNewValue(''); setError(null); };
const add = async (event: SubmitEvent) => {
event.preventDefault();
if (!inspection || !newName.trim()) return;
try {
await inspection.edit(group === 'stylesheets' ? 'styles' : group, newName.trim(), newValue);
setNewName(''); setNewValue(''); setError(null); refresh();
} catch (failure) { setError(failure instanceof Error ? failure.message : String(failure)); }
};
const search = query.trim().toLowerCase();
const rows = (group === 'stylesheets' ? [] : snapshot?.[group] ?? []).filter((entry) => {
if (search) return entry.name.toLowerCase().includes(search) || entry.value.toLowerCase().includes(search);
return group !== 'styles' || showAll || entry.inline || COMMON_STYLES.has(entry.name);
});
const sections = group === 'styles' ? groupStyles(rows) : group === 'properties' ? groupProperties(rows) : groupAttributes(rows);
const textProperty = snapshot?.properties.find((property) => property.name === 'textContent' && (property.editable || snapshot.textSource?.kind === 'imported' || snapshot.textSource?.kind === 'unsupported'));
// Explicit open/closed choices per tab and section; a search shows every match.
const [folds, setFolds] = useState<Readonly<Record<string, boolean>>>({});
const isOpen = (section: ElementSection) => search !== '' || (folds[`${group}:${section.id}`] ?? !section.collapsed);
const toggle = (section: ElementSection) => setFolds({ ...folds, [`${group}:${section.id}`]: !isOpen(section) });
section.bdt-pane.bdt-elements-panel(aria-label="Selected element")
if snapshot === null
.bdt-empty
.bdt-empty-card
p.bdt-empty-title Let's take closer look.
p Pick an element to explore its styles, attributes and properties.
button.bdt-button-critical(type="button" onClick={onPick}) Pick an element
else
fragment
.bdt-toolbar.bdt-element-toolbar
.bdt-element-row
strong.bdt-element-identity #{snapshot.label}
if snapshot.classes?.length
span.bdt-element-classes(title={snapshot.classes.join(' ')}) #{snapshot.classes.map((name) => '.' + name).join(' ')}
span.bdt-mono.bdt-dim #{snapshot.component ? ' · ' + snapshot.component : ''}
if textProperty !== undefined
.bdt-element-text-editor
span.bdt-mono.bdt-dim ·
ElementPropertyRow(
~ key={snapshot.source ?? snapshot.label}
~ property={textProperty}
~ disabled={saving || !snapshot.source || !snapshot.connected}
~ removable={false}
~ onCommit={(name, value) => edit(name, value, 'properties')}
~ )
span.bdt-mono.bdt-dim #{`${Number(snapshot.width.toFixed(1))} × ${Number(snapshot.height.toFixed(1))} px`}
.bdt-spacer
span.bdt-element-live #{saving ? 'Saving…' : error ? 'Not saved' : group === 'stylesheets' ? 'Saves to CSS rule' : group !== 'styles' ? 'Saves to source' : styleTarget === 'css' ? 'Saves to CSS file' : styleTarget === 'tailwind' ? 'Saves to className' : 'Saves to inline style'}
button.bdt-button(type="button" disabled={saving || undoCount === 0} onClick={undo}) Undo#{undoCount > 0 ? ' · ' + undoCount : ''}
button.bdt-button(type="button" onClick={() => { refresh(); void inspection?.refreshStylesheets(); }}) Refresh
button.bdt-button-critical(type="button" onClick={onPick}) Pick another
if !snapshot.source
p.bdt-element-notice(role="status") This element has no Beast source location. Enable source tagging to save attributes, DOM properties and inline styles. Project CSS rules can still be edited.
if !snapshot.connected
p.bdt-element-notice(role="status") This element was removed from the page. Pick it again to continue editing.
if snapshot.textSource?.kind === 'array'
p.bdt-element-notice(role="status") Text edits update #{snapshot.textSource.label} in this file.
elseif snapshot.textSource?.kind === 'imported' || snapshot.textSource?.kind === 'unsupported'
.bdt-element-notice.bdt-element-text-source(role="status")
span #{snapshot.textSource.message}
if snapshot.textSource.path
button.bdt-link(type="button" title="Open array source in editor" onClick={() => openInEditor(snapshot.textSource!.path!, snapshot.textSource!.line, snapshot.textSource!.column)}) #{snapshot.textSource.path}:#{snapshot.textSource.line}
if error !== null
p.bdt-element-notice.is-error(role="alert") #{error}
.bdt-element-workspace
aside.bdt-element-nav
each item in GROUPS key item.id
button(type="button" className={cx('bdt-element-group', group === item.id && 'is-active')} aria-pressed={group === item.id} onClick={() => chooseGroup(item.id)})
span #{item.label}
span.bdt-dim #{item.id === 'stylesheets' ? snapshot.cssRules?.length ?? 0 : snapshot[item.id].length}
p.bdt-element-note Style edits and layout drags save to the selected destination. CSS rule edits affect every matching element; inline and Tailwind edits affect every instance rendered by this source element.
.bdt-element-content
if group === 'stylesheets'
StylesheetsPanel(inspection={inspection!} snapshot={snapshot} disabled={saving || !snapshot.connected} onRefresh={refresh} onUseRule={(rule) => { inspection?.useCssRule(rule); setStyleTarget('css'); setCssPath(rule.source!.path); setCssSelector(rule.selector); }})
else
fragment
if group === 'styles'
fragment
.bdt-element-filter
label.bdt-dim(htmlFor="bdt-style-target") Save styles to
select.bdt-input(id="bdt-style-target" value={styleTarget} disabled={saving} onChange={(event) => chooseStyleTarget(event.currentTarget.value as ElementStyleTarget)})
option(value="tailwind") Tailwind className
option(value="inline") Inline style
option(value="css") CSS file
if styleTarget === 'css'
fragment
.bdt-element-filter
input.bdt-input(aria-label="CSS file path" placeholder="src/styles.css" value={cssPath} disabled={saving} onInput={(event) => { setCssPath(event.currentTarget.value); if (inspection) inspection.cssPath = event.currentTarget.value; }})
input.bdt-input(aria-label="CSS rule selector" placeholder=".card" value={cssSelector} disabled={saving} onInput={(event) => { setCssSelector(event.currentTarget.value); if (inspection) inspection.cssSelector = event.currentTarget.value; }})
p.bdt-element-note Enter a project CSS file and an existing, unique selector. Its declarations are replaced in place.
elseif styleTarget === 'tailwind'
p.bdt-element-note Replaces base utilities with Tailwind arbitrary value classes. Responsive and state variants stay in place.
.bdt-element-filter
input.bdt-input(type="search" aria-label="Filter element properties" placeholder="Find a property or value…" value={query} onInput={(event) => setQuery(event.currentTarget.value)})
if group === 'styles'
SquishSwitch(checked={showAll} onChange={setShowAll} label="All computed styles" width={28} height={18} trackColor="var(--bdt-bg-4)" trackOnColor="var(--bdt-ok)" thumbColor="var(--bdt-line-2)" thumbOnColor="#fafafa")
span.bdt-dim.bdt-prop-count #{rows.length}
span.bdt-dim properties
.bdt-element-properties
if rows.length === 0
p.bdt-element-note No matching properties.
div(className={cx(group === 'styles' && 'bdt-style-columns', group === 'properties' && 'bdt-property-columns')})
each category in sections key `${group}:${category.id}`
.bdt-element-section
if category.label !== null
button(
~ type="button"
~ className={cx('bdt-element-section-head', category.id === 'editable' && 'is-editable')}
~ aria-expanded={isOpen(category)}
~ disabled={search !== ''}
~ onClick={() => toggle(category)}
~ )
span.bdt-element-section-chevron(aria-hidden="true") ›
span #{category.label}
span.bdt-dim #{category.properties.length}
if isOpen(category)
div(className={cx('bdt-element-grid', group !== 'properties' && category.columns === 2 && 'is-split')})
each property in category.properties key `${group}:${property.name}`
ElementPropertyRow(originalValue={savedSnapshot?.[group].find((entry) => entry.name === property.name)?.value} styleControl={group === 'styles'} property={property} disabled={saving || !snapshot.source || !snapshot.connected} removable={group === 'attributes' || (group === 'styles' && (!!property.inline || styleTarget !== 'inline'))} onCommit={edit})
if group !== 'properties'
form.bdt-element-add(onSubmit={add})
input.bdt-input(aria-label={group === 'styles' ? 'New CSS property' : 'New attribute'} placeholder={group === 'styles' ? 'CSS property' : 'Attribute name'} value={newName} disabled={saving || !snapshot.source || !snapshot.connected} onInput={(event) => setNewName(event.currentTarget.value)})
input.bdt-input(aria-label="New property value" placeholder="Value" value={newValue} disabled={saving || !snapshot.source || !snapshot.connected} onInput={(event) => setNewValue(event.currentTarget.value)})
button.bdt-button(type="submit" disabled={saving || !snapshot.source || !snapshot.connected || !newName.trim()}) Add