diff --git a/GitVersion.yml b/GitVersion.yml
index 54430ca..8526202 100644
--- a/GitVersion.yml
+++ b/GitVersion.yml
@@ -1,3 +1,4 @@
+next-version: 2.0.0
branches:
main:
increment: Patch
diff --git a/Paramood/Paramood.py b/Paramood/Paramood.py
index 281e118..415ca19 100644
--- a/Paramood/Paramood.py
+++ b/Paramood/Paramood.py
@@ -134,7 +134,7 @@ def notify(self, args):
'parameters.delete',
'parameters.rename',
'parameters.favorite',
- 'variants.save',
+ 'variants.table.save',
'variants.apply',
'variants.delete',
'variants.free',
@@ -366,6 +366,16 @@ def notify(self, args):
_broadcast('state.changed', {})
+class TimelineSelectionChanged(adsk.core.ActiveSelectionEventHandler):
+ def notify(self, args):
+ try:
+ if _adapter and 'parameters' in _ready_modes and _ui.activeCommand == 'SelectCommand':
+ _send('parameters', 'variants.selection', _adapter._variant_timeline_selection())
+ except Exception:
+ if _app:
+ _app.log(traceback.format_exc())
+
+
def _definition(identifier, name, handler):
existing = _ui.commandDefinitions.itemById(identifier)
if existing:
@@ -400,6 +410,7 @@ def run(context):
for event in (_app.documentClosed, _app.documentOpened):
_listen(event, DocumentChanged())
_listen(_ui.commandTerminated, ExternalCommandEnded())
+ _listen(_ui.activeSelectionChanged, TimelineSelectionChanged())
_listen(_ui.workspaceActivated, WorkspaceChanged())
if _adapter._design():
_show_palette('parameters')
diff --git a/Paramood/bridge/protocol.py b/Paramood/bridge/protocol.py
index 37f3727..af8bfe0 100644
--- a/Paramood/bridge/protocol.py
+++ b/Paramood/bridge/protocol.py
@@ -28,7 +28,9 @@ def dispatch(adapter, message):
'parameters.delete',
'parameters.rename',
'parameters.favorite',
- 'variants.save',
+ 'variants.table.save',
+ 'variants.selection.get',
+ 'variants.cell.preview',
'variants.apply',
'variants.delete',
'variants.free',
diff --git a/Paramood/core/variants.py b/Paramood/core/variants.py
index e292676..46ef382 100644
--- a/Paramood/core/variants.py
+++ b/Paramood/core/variants.py
@@ -9,7 +9,7 @@ def decode_variants(raw):
if not raw:
return []
data = json.loads(raw)
- if not isinstance(data, dict) or data.get('version') != 1:
+ if not isinstance(data, dict) or data.get('version') != 2:
raise ValueError('Unsupported variants format.')
variants = data.get('variants')
if not isinstance(variants, list):
@@ -26,7 +26,7 @@ def decode_variants(raw):
ids.add(identity)
names.add(name.casefold())
entries = variant.get('parameters')
- if not isinstance(entries, list) or not entries:
+ if not isinstance(entries, list):
raise ValueError('A variant needs at least one parameter.')
tokens = set()
for entry in entries:
@@ -46,12 +46,51 @@ def decode_variants(raw):
raise ValueError('Invalid text variant value.')
elif type(value) not in (float, int) or not math.isfinite(value):
raise ValueError('Invalid variant parameter value.')
+ features = variant.get('features', [])
+ if not isinstance(features, list):
+ raise ValueError('Invalid variant features.')
+ feature_tokens = set()
+ for entry in features:
+ if (
+ not isinstance(entry, dict)
+ or any(
+ not isinstance(entry.get(k), str) or not entry[k]
+ for k in ('name', 'entityToken')
+ )
+ or type(entry.get('enabled')) is not bool
+ or entry['entityToken'] in feature_tokens
+ ):
+ raise ValueError('Invalid variant feature.')
+ feature_tokens.add(entry['entityToken'])
+ columns = data.get('columns')
+ if not isinstance(columns, list) or (variants and not columns):
+ raise ValueError('Select at least one parameter or feature.')
+ keys = set()
+ for column in columns:
+ if (
+ not isinstance(column, dict)
+ or column.get('kind') not in ('parameter', 'feature')
+ or any(
+ not isinstance(column.get(k), str) or not column[k] for k in ('name', 'entityToken')
+ )
+ or (column['kind'], column['entityToken']) in keys
+ or (column['kind'] == 'parameter' and not isinstance(column.get('unit'), str))
+ ):
+ raise ValueError('Invalid or duplicate table column.')
+ keys.add((column['kind'], column['entityToken']))
+ parameter_tokens = [c['entityToken'] for c in columns if c['kind'] == 'parameter']
+ feature_tokens = [c['entityToken'] for c in columns if c['kind'] == 'feature']
+ for variant in variants:
+ if [p['entityToken'] for p in variant['parameters']] != parameter_tokens or [
+ f['entityToken'] for f in variant.get('features', [])
+ ] != feature_tokens:
+ raise ValueError('All variants must use the same ordered parameters and features.')
return variants
-def encode_variants(variants):
+def encode_variants(variants, columns):
raw = json.dumps(
- {'version': 1, 'variants': variants},
+ {'version': 2, 'columns': columns, 'variants': variants},
ensure_ascii=False,
allow_nan=False,
separators=(',', ':'),
@@ -62,6 +101,13 @@ def encode_variants(variants):
return raw
+def decode_variant_table(raw):
+ """Only the major-version-2 table format is supported."""
+ variants = decode_variants(raw)
+ data = json.loads(raw) if raw else {'version': 2, 'columns': []}
+ return {'version': 2, 'columns': data['columns'], 'variants': variants}
+
+
def variants_token(raw):
return hashlib.sha256(raw.encode('utf-8')).hexdigest()
diff --git a/Paramood/fusion/adapter.py b/Paramood/fusion/adapter.py
index f09df43..0cd5417 100644
--- a/Paramood/fusion/adapter.py
+++ b/Paramood/fusion/adapter.py
@@ -357,6 +357,13 @@ def state(self):
}
)
variant_state = self._variants_state(design)
+ controlled = {
+ column['name']
+ for column in variant_state.get('variantColumns', [])
+ if column['kind'] == 'parameter' and not column.get('missing')
+ }
+ for parameter in parameters:
+ parameter['configured'] = parameter['name'] in controlled
return {
'documentId': self._document_id,
'draftId': self._draft_id,
@@ -391,6 +398,10 @@ def _snapshot_token(self, design, text):
sorted(parameters),
self._variant_sessions.get(self._draft_id),
self._read_variants(design)[1],
+ self._variant_feature_snapshot(design)
+ if text == 'variants'
+ or any(c['kind'] == 'feature' for c in self._read_variant_table(design)[0]['columns'])
+ else [],
]
return hashlib.sha256(
json.dumps(payload, ensure_ascii=True, allow_nan=False).encode('utf-8')
@@ -649,6 +660,10 @@ def _execute_direct_batch(self, design, ops):
return {'created': [], 'updated': [op.name for op in ops]}
def request(self, action, payload):
+ if action == 'variants.cell.preview':
+ return self._preview_variant_cell(payload)
+ if action == 'variants.selection.get':
+ return self._variant_timeline_selection()
if action.startswith('variants.'):
return self._request_variant(action, payload)
if action == 'document.units':
diff --git a/Paramood/fusion/variant_table.py b/Paramood/fusion/variant_table.py
new file mode 100644
index 0000000..9e1f72a
--- /dev/null
+++ b/Paramood/fusion/variant_table.py
@@ -0,0 +1,383 @@
+"""Model-wide variant columns and feature states; no native Configuration API."""
+
+import copy
+import re
+import uuid
+
+import adsk.fusion
+
+from ..bridge.protocol import BridgeError
+from ..core.expressions import TextValue, _fold_assignments
+from ..core.inline_equation import solve_inline_equation
+from .expression_engine import NativeExpressionEngine
+from ..core.variants import decode_variant_table, encode_variants, variants_token
+
+GROUP = '4FusionLab.Paramood'
+ATTRIBUTE = 'variants.v2'
+
+
+class VariantTableMixin:
+ def _new_variant_parameters(self, design, payload):
+ entries = payload.get('newParameters', [])
+ if not isinstance(entries, list):
+ raise BridgeError('BAD_REQUEST', 'Invalid pending parameters.')
+ definitions = {}
+ for entry in entries:
+ if not isinstance(entry, dict) or any(
+ not isinstance(entry.get(k), str) or not entry[k].strip()
+ for k in ('name', 'expression')
+ ):
+ raise BridgeError('BAD_REQUEST', 'A pending parameter needs a name and expression.')
+ name = entry['name']
+ if name in definitions or design.allParameters.itemByName(name):
+ raise BridgeError('CONFLICT', 'A pending parameter already exists: ' + name)
+ definitions[name] = entry['expression']
+ if not definitions:
+ return {}, []
+ _, operations = self._plan(
+ ';'.join(name + '=' + expression for name, expression in definitions.items())
+ )
+ if {op.name for op in operations} != set(definitions) or any(
+ op.status != 'New' for op in operations
+ ):
+ raise BridgeError('BAD_REQUEST', 'Pending definitions must create new parameters only.')
+ return definitions, operations
+
+ def _preview_variant_cell(self, payload):
+ design = self._design()
+ if payload.get('variantsToken') != self._read_variant_table(design)[1] or payload.get(
+ 'snapshotToken'
+ ) != self._snapshot_token(design, 'variants'):
+ raise BridgeError('CONFLICT', 'The model changed. Refresh the variant table.')
+ target = payload.get('target')
+ cells = payload.get('parameters')
+ if not isinstance(target, str) or not isinstance(cells, list):
+ raise BridgeError('BAD_REQUEST', 'A cell target and row parameters are required.')
+ expressions, units, entities = {}, {}, []
+ for cell in cells:
+ if not isinstance(cell, dict) or any(
+ not isinstance(cell.get(k), str) for k in ('entityToken', 'expression', 'unit')
+ ):
+ raise BridgeError('BAD_REQUEST', 'Invalid row parameter.')
+ parameter = self._resolve_variant_parameter(design, cell)
+ if not parameter or any(parameter == p for p in entities):
+ raise BridgeError('CONFLICT', 'A row parameter changed or is duplicated.')
+ entities.append(parameter)
+ expressions[parameter.name] = cell['expression']
+ units[parameter.name] = parameter.unit
+ if target not in expressions:
+ raise BridgeError('BAD_REQUEST', 'The edited parameter is not in this row.')
+ pending, _ = self._new_variant_parameters(design, payload)
+ _, baseline = self._plan(
+ ';'.join(
+ name + '=' + expression for name, expression in {**pending, **expressions}.items()
+ )
+ )
+ quantities = self._quantities(design)
+ quantities.update({op.name: op.quantity for op in baseline})
+ text = payload.get('text')
+ if payload.get('inlineEquation') is not None:
+ equation = payload['inlineEquation']
+ if not isinstance(equation, str):
+ raise BridgeError('BAD_REQUEST', 'Invalid inline equation.')
+ text = solve_inline_equation(
+ equation, target, units[target], quantities, quantities.keys()
+ )
+ if not isinstance(text, str) or not text.strip() or len(text) > 10000:
+ raise BridgeError('BAD_REQUEST', 'Enter one expression.')
+ original = {p.name: p.expression for p in design.allParameters}
+ original.update({**pending, **expressions})
+ display_units = {p.name: p.unit for p in design.allParameters}
+ display_units.update({op.name: op.unit for op in baseline})
+ folded = _fold_assignments(
+ text,
+ quantities,
+ original,
+ display_units,
+ design.fusionUnitsManager.defaultLengthUnits,
+ self._native_function(design),
+ )
+ created = [name for name in folded if name not in quantities]
+ if target not in folded or len(created) > 1 or set(folded) != {target, *created}:
+ raise BridgeError(
+ 'BAD_REQUEST', 'A cell may update only its parameter and create one new parameter.'
+ )
+ if payload.get('sourceName') == target and created:
+ folded[created[0]] = NativeExpressionEngine.literal(quantities[target])
+ expressions[target] = folded[target]
+ _, operations = self._plan(
+ ';'.join(
+ name + '=' + expression
+ for name, expression in {
+ **pending,
+ **{name: folded[name] for name in created},
+ **expressions,
+ }.items()
+ )
+ )
+ planned = {op.name: op for op in operations}
+ if set(planned) != {*pending, *expressions, *created}:
+ raise BridgeError('BAD_REQUEST', 'Unexpected parameter assignments in a cell.')
+ return {
+ 'expression': planned[target].expression,
+ 'newParameters': [
+ {
+ 'name': name,
+ 'expression': planned[name].expression,
+ 'unit': planned[name].unit,
+ 'value': planned[name].quantity.value,
+ 'valueExpression': NativeExpressionEngine.literal(planned[name].quantity),
+ }
+ for name in created
+ ],
+ }
+
+ def _read_variant_table(self, design):
+ attributes = getattr(design, 'attributes', None)
+ attribute = attributes.itemByName(GROUP, ATTRIBUTE) if attributes else None
+ raw = attribute.value if attribute else ''
+ try:
+ return decode_variant_table(raw), variants_token(raw)
+ except (ValueError, TypeError, KeyError) as exc:
+ raise BridgeError(
+ 'VARIANTS_UNREADABLE',
+ 'Cannot read saved variants. Existing data has been preserved. ' + str(exc),
+ ) from exc
+
+ @staticmethod
+ def _timeline_features(design):
+ timeline = getattr(design, 'timeline', None)
+ if not timeline:
+ return []
+ features = []
+
+ def visit(item):
+ if item.isGroup:
+ for child_index in range(item.count):
+ visit(item.item(child_index))
+ return
+ entity = item.entity
+ feature = adsk.fusion.Feature.cast(entity) if entity else None
+ if (
+ feature
+ and feature.isValid
+ and feature.isParametric
+ and not any(feature == previous for previous in features)
+ ):
+ features.append(feature)
+
+ for index in range(timeline.count):
+ visit(timeline.item(index))
+ return features
+
+ @staticmethod
+ def _feature_entry(feature):
+ return {
+ 'name': feature.name,
+ 'entityToken': feature.entityToken,
+ 'enabled': not feature.isSuppressed,
+ }
+
+ def _resolve_variant_feature(self, design, entry):
+ try:
+ matches = design.findEntityByToken(entry['entityToken'])
+ feature = adsk.fusion.Feature.cast(matches[0]) if len(matches) == 1 else None
+ return feature if feature and feature.isValid and feature.isParametric else None
+ except RuntimeError:
+ return None
+
+ def _variant_feature_snapshot(self, design):
+ # Include all candidates so newly selected features cannot bypass stale-request checks.
+ return [(f.name, f.entityToken, f.isSuppressed) for f in self._timeline_features(design)]
+
+ def _variant_timeline_selection(self):
+ design = self._design()
+ if not design:
+ raise BridgeError('NO_DESIGN', 'Open a Fusion design first.')
+ ui = self.app.userInterface
+ if ui.activeCommand != 'SelectCommand':
+ raise BridgeError(
+ 'BAD_CONTEXT', 'Finish the active Fusion command before picking timeline features.'
+ )
+ table, _ = self._read_variant_table(design)
+ configured = [c for c in table['columns'] if c['kind'] == 'feature']
+ features, seen = [], []
+ for index in range(ui.activeSelections.count):
+ entity = ui.activeSelections.item(index).entity
+ feature = adsk.fusion.Feature.cast(entity)
+ if not feature or not feature.isValid or not feature.isParametric:
+ continue
+ # Reject foreign-document entities and compare resolved objects, not token strings.
+ matches = design.findEntityByToken(feature.entityToken)
+ if len(matches) != 1 or matches[0] != feature or any(feature == f for f in seen):
+ continue
+ seen.append(feature)
+ entry = self._feature_entry(feature)
+ for column in configured:
+ if self._resolve_variant_feature(design, column) == feature:
+ entry['entityToken'] = column['entityToken']
+ break
+ features.append(entry)
+ return {'documentId': self.document_id, 'features': features}
+
+ def _save_variant_table(self, design, payload):
+ columns, rows = payload.get('columns'), payload.get('variants')
+ if not isinstance(columns, list) or not isinstance(rows, list):
+ raise BridgeError('BAD_REQUEST', 'A table needs columns and variants.')
+ old, _ = self._read_variant_table(design)
+ pending, new_operations = self._new_variant_parameters(design, payload)
+ if new_operations and not self.in_command:
+ raise BridgeError(
+ 'TRANSACTION_REQUIRED',
+ 'Finish the active Fusion command or sketch before creating and linking parameters.',
+ )
+ active = self._active_variant(design, old['variants'])
+ old_ids = {v['id'] for v in old['variants']}
+ columns = copy.deepcopy(columns)
+ seen = []
+ for column in columns:
+ if not isinstance(column, dict) or column.get('kind') not in ('parameter', 'feature'):
+ raise BridgeError('BAD_REQUEST', 'Invalid table column.')
+ if not isinstance(column.get('entityToken'), str):
+ raise BridgeError('BAD_REQUEST', 'Missing column identity.')
+ if column['kind'] == 'parameter':
+ if not isinstance(column.get('unit'), str):
+ raise BridgeError('BAD_REQUEST', 'Missing parameter unit.')
+ entity = self._resolve_variant_parameter(design, column)
+ else:
+ entity = self._resolve_variant_feature(design, column)
+ if not entity or any(entity == previous for previous in seen):
+ raise BridgeError('CONFLICT', 'A column is missing, unsupported, or duplicated.')
+ seen.append(entity)
+ column['name'] = entity.name
+ if column['kind'] == 'parameter':
+ column['unit'] = entity.unit
+ prepared, identities = [], set()
+ for row in rows:
+ if not isinstance(row, dict):
+ raise BridgeError('BAD_REQUEST', 'Invalid variant row.')
+ identity = row.get('id')
+ if identity is not None and (identity not in old_ids or identity in identities):
+ raise BridgeError('CONFLICT', 'A variant identity changed or is duplicated.')
+ if identity:
+ identities.add(identity)
+ name = row.get('name')
+ if not isinstance(name, str) or not name.strip() or len(name.strip()) > 120:
+ raise BridgeError('BAD_REQUEST', 'Enter a variant name (up to 120 characters).')
+ parameters, features = row.get('parameters'), row.get('features', [])
+ if not isinstance(parameters, list) or not isinstance(features, list):
+ raise BridgeError('BAD_REQUEST', 'Invalid variant cells.')
+ expected_parameters = [c for c in columns if c['kind'] == 'parameter']
+ expected_features = [c for c in columns if c['kind'] == 'feature']
+ if len(parameters) != len(expected_parameters) or len(features) != len(
+ expected_features
+ ):
+ raise BridgeError('BAD_REQUEST', 'Fill every cell in every variant.')
+ entries = []
+ for cell, column in zip(parameters, expected_parameters):
+ if (
+ not isinstance(cell, dict)
+ or cell.get('entityToken') != column['entityToken']
+ or not isinstance(cell.get('expression'), str)
+ or not cell['expression'].strip()
+ or len(cell['expression']) > 10000
+ ):
+ raise BridgeError('BAD_REQUEST', 'A parameter cell is missing or out of order.')
+ expression = cell['expression'].strip()
+ if (
+ column['unit']
+ and column['unit'] != 'Text'
+ and re.fullmatch(r'[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?', expression)
+ ):
+ expression += ' ' + column['unit']
+ entries.append({**column, 'expression': expression})
+ # Plan all assignments together against Fusion's dependency snapshot. This is read-only:
+ # do not cycle through variants or temporarily modify the user's model to validate cells.
+ planned = {}
+ if entries:
+ _, operations = self._plan(
+ ';'.join(
+ [name + '=' + expression for name, expression in pending.items()]
+ + [entry['name'] + '=' + entry['expression'] for entry in entries]
+ )
+ )
+ planned = {op.name: op for op in operations}
+ if set(planned) != {entry['name'] for entry in entries} | set(pending):
+ raise BridgeError(
+ 'BAD_REQUEST', 'A cell must contain one expression, not assignments.'
+ )
+ saved_parameters = []
+ for entry in entries:
+ op = planned[entry['name']]
+ value = op.quantity.value
+ if not isinstance(op.quantity, TextValue):
+ value /= 10.0 ** op.quantity.dimension[0]
+ saved_parameters.append(
+ {k: entry[k] for k in ('name', 'entityToken', 'unit')}
+ | {'expression': op.expression, 'value': value}
+ )
+ saved_features = []
+ for cell, column in zip(features, expected_features):
+ if (
+ not isinstance(cell, dict)
+ or cell.get('entityToken') != column['entityToken']
+ or type(cell.get('enabled')) is not bool
+ ):
+ raise BridgeError('BAD_REQUEST', 'A feature cell is missing or out of order.')
+ saved_features.append(
+ {k: column[k] for k in ('name', 'entityToken')} | {'enabled': cell['enabled']}
+ )
+ prepared.append(
+ {
+ 'id': identity or uuid.uuid4().hex,
+ 'name': name.strip(),
+ 'parameters': saved_parameters,
+ 'features': saved_features,
+ }
+ )
+ raw = encode_variants(prepared, columns)
+ if self._design() != design:
+ raise BridgeError(
+ 'STALE_DOCUMENT', 'The active document changed. Refresh and try again.'
+ )
+ # The Fusion command transaction owns creation rollback if applying/storing later fails.
+ # No global parameter is created during cell preview or before the complete table validates.
+ if new_operations:
+ self._execute_new_batch(design, new_operations)
+ replacement = next((row for row in prepared if active and row['id'] == active['id']), None)
+
+ def cells(row):
+ return (
+ {p['entityToken']: p['expression'] for p in row['parameters']},
+ {f['entityToken']: f['enabled'] for f in row.get('features', [])},
+ )
+
+ if replacement and cells(replacement) != cells(active):
+ # The complete table is validated first. Apply only the active row and persist last;
+ # a metadata failure restores its CAD expressions and feature states in _apply_variant.
+ self._apply_variant(design, replacement, lambda: self._store_variant_raw(design, raw))
+ else:
+ self._store_variant_raw(design, raw)
+ return {'saved': len(prepared)}
+
+ def _set_feature_states(self, states):
+ # Enable parents before children, suppress children before parents. User table ordering
+ # is presentation only and must never determine the order of CAD operations.
+ if not states:
+ return
+ features = self._timeline_features(self._design())
+
+ def position(pair):
+ return next(i for i, feature in enumerate(features) if feature == pair[0])
+
+ ordered = sorted(states, key=position)
+ for feature, enabled in ordered:
+ if enabled and feature.isSuppressed:
+ feature.isSuppressed = False
+ if feature.isSuppressed:
+ raise BridgeError('FEATURE_UPDATE_FAILED', 'Could not enable ' + feature.name)
+ for feature, enabled in reversed(ordered):
+ if not enabled and not feature.isSuppressed:
+ feature.isSuppressed = True
+ if not feature.isSuppressed:
+ raise BridgeError('FEATURE_UPDATE_FAILED', 'Could not suppress ' + feature.name)
diff --git a/Paramood/fusion/variants.py b/Paramood/fusion/variants.py
index 5528d08..e5209a6 100644
--- a/Paramood/fusion/variants.py
+++ b/Paramood/fusion/variants.py
@@ -2,35 +2,31 @@
import copy
import re
-import uuid
import adsk.core
from ..bridge.protocol import BridgeError
from ..core.text import map_code, normalize_literals
-from ..core.variants import decode_variants, encode_variants, values_match, variants_token
+from ..core.variants import encode_variants, values_match
+from .variant_table import VariantTableMixin
GROUP = '4FusionLab.Paramood'
-ATTRIBUTE = 'variants.v1'
+ATTRIBUTE = 'variants.v2'
-class VariantsMixin:
+class VariantsMixin(VariantTableMixin):
def _read_variants(self, design):
- # Older offline adapter fixtures have no attribute collection.
- attributes = getattr(design, 'attributes', None)
- attribute = attributes.itemByName(GROUP, ATTRIBUTE) if attributes else None
- raw = attribute.value if attribute else ''
- try:
- return decode_variants(raw), variants_token(raw)
- except (ValueError, TypeError, KeyError) as exc:
- raise BridgeError(
- 'VARIANTS_UNREADABLE',
- 'Cannot read saved variants. Existing data has been preserved. ' + str(exc),
- ) from exc
+ table, token = self._read_variant_table(design)
+ return table['variants'], token
def _write_variants(self, design, variants):
+ table, _ = self._read_variant_table(design)
+ columns = table['columns']
+ self._store_variant_raw(design, encode_variants(variants, columns))
+
+ @staticmethod
+ def _store_variant_raw(design, raw):
try:
- raw = encode_variants(variants)
attribute = design.attributes.add(GROUP, ATTRIBUTE, raw)
if not attribute or attribute.value != raw:
raise ValueError('Fusion did not retain variant data.')
@@ -77,6 +73,10 @@ def _variant_matches(self, design, variant):
parameter.textValue if parameter.unit == 'Text' else parameter.value, entry['value']
):
return False
+ for entry in variant.get('features', []):
+ feature = self._resolve_variant_feature(design, entry)
+ if not feature or (not feature.isSuppressed) != entry['enabled']:
+ return False
return True
def _active_variant(self, design, variants):
@@ -98,17 +98,38 @@ def _variants_state(self, design):
variants, token = self._read_variants(design)
active = self._active_variant(design, variants)
public = copy.deepcopy(variants)
+ table, _ = self._read_variant_table(design)
+ columns = copy.deepcopy(table['columns'])
+ for column in columns:
+ entity = (
+ self._resolve_variant_parameter(design, column)
+ if column['kind'] == 'parameter'
+ else self._resolve_variant_feature(design, column)
+ )
+ column['missing'] = entity is None
+ if entity:
+ column['name'] = entity.name
for variant in public:
for entry in variant['parameters']:
parameter = self._resolve_variant_parameter(design, entry)
entry['missing'] = parameter is None
if parameter:
entry['name'] = parameter.name
+ for entry in variant.get('features', []):
+ feature = self._resolve_variant_feature(design, entry)
+ entry['missing'] = feature is None
+ if feature:
+ entry['name'] = feature.name
return {
'variants': public,
'activeVariantId': active['id'] if active else None,
'variantsToken': token,
'variantSnapshotToken': self._snapshot_token(design, 'variants'),
+ 'variantColumns': columns,
+ 'variantTableVersion': table['version'],
+ 'timelineFeatures': [
+ self._feature_entry(f) for f in self._timeline_features(design)
+ ],
}
except Exception as exc:
return {'variants': [], 'activeVariantId': None, 'variantsError': str(exc)}
@@ -177,11 +198,12 @@ def _capture_variant_edits(self, design, context, names):
if not parameter:
raise BridgeError('CONFLICT', 'A variant parameter is no longer available.')
parameters.append(parameter)
- for name in names:
- parameter = self._editable_parameter(design, name)
- if parameter and not any(parameter == existing for existing in parameters):
- parameters.append(parameter)
- active['parameters'] = [self._variant_entry(p) for p in parameters]
+ if not set(names).intersection(parameter.name for parameter in parameters):
+ return
+ active['parameters'] = [
+ {**self._variant_entry(p), 'entityToken': entry['entityToken']}
+ for p, entry in zip(parameters, active['parameters'])
+ ]
self._write_variants(design, variants)
@staticmethod
@@ -208,59 +230,18 @@ def _request_variant(self, action, payload):
if action == 'variants.free':
self._variant_sessions[self._draft_id] = None
return {'activeVariantId': None}
- if action != 'variants.save' and not variant:
+ if action == 'variants.table.save':
+ return self._save_variant_table(design, payload)
+ if not variant:
raise BridgeError('CONFLICT', 'This variant no longer exists.')
if action == 'variants.delete':
self._write_variants(design, [v for v in variants if v['id'] != identity])
if self._variant_sessions.get(self._draft_id) == identity:
self._variant_sessions[self._draft_id] = None
return {'deleted': identity}
- if action == 'variants.save':
- name, entries = payload.get('name'), payload.get('parameters')
- if not isinstance(name, str) or not name.strip() or len(name.strip()) > 120:
- raise BridgeError('BAD_REQUEST', 'Enter a variant name (up to 120 characters).')
- name = name.strip()
- if any(
- v['id'] != identity and v['name'].casefold() == name.casefold() for v in variants
- ):
- raise BridgeError('CONFLICT', 'A variant with this name already exists.')
- if identity is not None and not variant:
- raise BridgeError('CONFLICT', 'This variant no longer exists.')
- if not isinstance(entries, list) or not entries:
- raise BridgeError('BAD_REQUEST', 'Select at least one parameter.')
- prepared, seen = [], []
- for entry in entries:
- if (
- not isinstance(entry, dict)
- or any(
- not isinstance(entry.get(k), str)
- for k in ('name', 'entityToken', 'expression', 'unit')
- )
- or not entry['expression'].strip()
- or len(entry['expression']) > 10000
- ):
- raise BridgeError(
- 'BAD_REQUEST', 'A parameter expression or identity is missing.'
- )
- parameter = self._resolve_variant_parameter(design, entry)
- if (
- not parameter
- or parameter.name != entry['name']
- or any(parameter == p for p in seen)
- ):
- raise BridgeError(
- 'CONFLICT', 'A selected parameter changed. Refresh and try again.'
- )
- seen.append(parameter)
- prepared.append(self._variant_entry(parameter, entry['expression'].strip()))
- replacement = {'id': identity or uuid.uuid4().hex, 'name': name, 'parameters': prepared}
- if variant:
- variants[variants.index(variant)] = replacement
- else:
- variants.append(replacement)
- variant = replacement
- # Validate storage capacity before making any CAD changes.
- encode_variants(variants)
+ return self._apply_variant(design, variant)
+
+ def _apply_variant(self, design, variant, after_apply=None):
parameters, expressions = [], []
renames = {}
for entry in variant['parameters']:
@@ -291,26 +272,41 @@ def _request_variant(self, action, payload):
)
planned = {op.name: op for op in operations}
expressions = [planned[p.name].expression for p in parameters]
+ feature_states = []
+ for entry in variant.get('features', []):
+ feature = self._resolve_variant_feature(design, entry)
+ if not feature:
+ raise BridgeError('MISSING_FEATURE', 'Feature unavailable: ' + entry['name'])
+ feature_states.append((feature, entry['enabled']))
+ old_states = [(feature, not feature.isSuppressed) for feature, _ in feature_states]
old_expressions = [p.expression for p in parameters]
values = [adsk.core.ValueInput.createByString(e) for e in expressions]
- if not design.modifyParameters(parameters, values):
- raise BridgeError('UPDATE_FAILED', 'Fusion could not apply the variant parameters.')
try:
+ # Unsuppress first so parameters belonging to enabled features become writable.
+ self._set_feature_states([(f, True) for f, enabled in feature_states if enabled])
+ if parameters and not design.modifyParameters(parameters, values):
+ raise BridgeError('UPDATE_FAILED', 'Fusion could not apply the variant parameters.')
+ self._set_feature_states(feature_states)
if any(p.unit == 'Text' for p in parameters):
for p in parameters:
self._verify_value(p, planned[p.name])
- if action == 'variants.save':
- variant['parameters'] = [self._variant_entry(p) for p in parameters]
- self._write_variants(design, variants)
+ if after_apply:
+ after_apply()
except Exception as exc:
# Direct callbacks have no command transaction to abort. Restore only
# these expressions; never undo unrelated user work.
- if self.in_direct_apply and not design.modifyParameters(
- parameters, [adsk.core.ValueInput.createByString(e) for e in old_expressions]
- ):
+ try:
+ self._set_feature_states([(f, True) for f, enabled in old_states if enabled])
+ restored = not parameters or design.modifyParameters(
+ parameters, [adsk.core.ValueInput.createByString(e) for e in old_expressions]
+ )
+ self._set_feature_states(old_states)
+ except Exception:
+ restored = False
+ if not restored:
raise BridgeError(
'VARIANT_PARTIAL',
- 'Variant storage failed and parameters could not be restored.',
+ 'Variant apply failed and the original state could not be restored. Review the model.',
) from exc
raise
self._variant_sessions[self._draft_id] = variant['id']
diff --git a/README.md b/README.md
index f6a8dd7..81c9a09 100644
--- a/README.md
+++ b/README.md
@@ -24,7 +24,7 @@ Paramood is an add-in for **Autodesk Fusion**, formerly Fusion 360, that puts a
The idea is simple: **use the precision of parametric CAD with the speed of an IDE**. Paramood is an interface over real Fusion parameters, not a separate parameter storage system.
-**Before editing:** Paramood changes update the active variant automatically, including newly changed parameters. Choose **Free** to leave saved variants unchanged. Applied values are kept even if a downstream Fusion feature fails; inspect geometry and the timeline before saving or sharing a configuration.
+**Before editing:** Paramood changes to configured parameters update the active variant automatically; parameters outside the configured set remain global. Choose **Free** to leave saved variants unchanged. Applied values are kept even if a downstream Fusion feature fails; inspect geometry and the timeline before saving or sharing a configuration.
## One palette for the parameter list and input
@@ -32,19 +32,36 @@ The default **Hybrid** view keeps the parameter list visible and the shared inpu
The header shows the current design, its length units, and the active variant. Synchronization with Fusion is automatic.
-## In Autodesk Fusion
+## The palette in Fusion
-The supplied Cedar & Sage F3D opened in the installed add-in, with **Classic** selected. These are real Fusion screenshots on macOS.
+The Hybrid palette keeps the parameter tree and expression input together. IntelliSense suggests model parameters as you type, while the calculator evaluates expressions using their current values:
-
+
-The palette keeps input below the list and opens results above it. The variant menu switches between the three configurations stored in the example.
+In a wide palette, the calculator view places the input and result next to the parameter tree:
-
+
-## Paramood 1.5.0 capabilities
+Enter several assignments to review their current and proposed values before applying them. This preview proposes changes to the Compact variant; no values have been applied:
-This overview describes the v1.5.0 source. The [Releases page](https://github.com/4FusionLab/Paramood/releases) lists published builds; check the installed version’s release notes when comparing features.
+
+
+Switch saved variants from the header, or open the table to compare and edit configured parameter expressions and supported feature states. **Compact** has a tray width of 120 mm; scroll horizontally to reach further columns:
+
+
+
+
+
+
+The Compact configuration of the Cedar & Sage review model:
+
+
+
+Screenshots show the 2.0 review build running in Fusion on macOS.
+
+## Paramood 2.0 capabilities — review draft
+
+This page describes the unreleased 2.0 development branch. The [Releases page](https://github.com/4FusionLab/Paramood/releases) lists published builds; features and screenshots may differ from the installed release.
| Area | Capability |
| --- | --- |
@@ -59,7 +76,7 @@ This overview describes the v1.5.0 source. The [Releases page](https://github.co
| **Model awareness** | Refresh on document changes; show indicators for known sketch, feature, or other parameter links. |
| **Native expressions** | Physical and compound units, lazy conditionals, native unit aliases, and `random()` in Preview/Apply. Sampled previews are marked `≈`. |
| **Calculator** | Evaluate expressions against the current design, see formatted results, reuse recent calculations, and copy results or expressions. |
-| **Saved variants** | Named sets of existing parameter expressions, stored in the design and carried with an F3D export. Switch sizes or configurations from the header. |
+| **Saved variants** | A model-wide table of parameter expressions and supported feature states, stored in the design. Switch variants from the header. |
| **Text parameters** | Quoted text, references, concatenation, and supported conditional expressions; the list shows the computed text while editing preserves the formula. |
| **Model units** | Select `mm`, `cm`, `m`, `in`, or `ft` beside the design name without changing physical sizes. |
@@ -108,16 +125,23 @@ Creation and linking are validated together. Equation solving supports one new n
## Save and switch variants
-Download the [Cedar & Sage F3D](examples/cedar-sage/Cedar-Sage-Paramood.f3d) and follow the [walkthrough](docs/DEMO.md). It includes Classic, Compact, and Garden, with geometry controls and text parameters. See its [model information and SHA-256](examples/cedar-sage/model-info.json). Use Paramood 1.5.0 for the variants and text workflows described here.
+The 2.0 variant editor is awaiting the owner's personal review; release is not yet authorized.
-1. Open **Free → Create variant** in the header.
-2. Name the variant and select at least one existing editable parameter. The editor uses the same name hierarchy as the parameter list, with `dN` dimensions under **Model parameters**.
-3. Change the selected expressions, or enter an assignment in the parameter search, such as `box.width=30`. This edits the draft; **Save & apply** writes it to the model.
-4. Create another variant and select either name from the header to apply it.
+1. Open the variant menu and choose **Create variant** or the shared **Edit variants** button in the menu header.
+2. Use **Configure** to choose the model-wide set of parameters and timeline features.
+3. Variants are always rows; parameters and features are always columns. Click a value to
+ edit that variant's expression. A checked feature is **Enabled**; unchecked is **Suppressed**.
+ Drag handles reorder parameters and variants. Mouse gestures and saved-order round-trip were checked in Fusion on macOS.
+4. **Save** stores the complete table and applies the edited active variant. Other variants are
+ saved without switching. **Cancel** lets you discard the draft without changing the model.
-While a variant is active, successful edits through Paramood update it and add any changed parameters to it. Choose **Free** before experimenting without updating a saved variant; choosing Free keeps the current model values. Removing a member or deleting a variant keeps the CAD parameters.
+Controlled parameters have a small table icon in the common list. Parameters outside the set
+remain global and are never enrolled automatically. **Free** keeps the current geometry and lets
+parameter edits leave saved variants unchanged. The switcher keeps its existing interaction.
-Save the design or export it as F3D to carry the variants with it. On reopening, Paramood selects the first created variant whose saved values all match the model; otherwise it shows Free. External changes that no longer match the active variant switch to Free without overwriting it. Variants are partial parameter sets: switching changes their members, leaving other parameters as they are.
+Format 2 is stored separately in the model: old 1.x variants are not read or migrated.
+The original Cedar & Sage 1.x example retains the old format; use the separate 2.0 review file or recreate its variants.
+See [Variants 2.0](docs/VARIANTS_V2.md) for workflow, verification and limitations.
## Create text parameters
@@ -170,7 +194,7 @@ The package declares support for both platforms, and automated checks run on bot
- [User guide](docs/USER_GUIDE.md): input, units, variants, text, and boundaries.
- [Cedar & Sage walkthrough](docs/DEMO.md): a feeder model and parameter-group examples.
-- [Published releases](https://github.com/4FusionLab/Paramood/releases) and [1.5.0 release notes](docs/releases/1.5.0.md): published builds and the source version described here.
+- [Published releases](https://github.com/4FusionLab/Paramood/releases) and [2.0 review notes](docs/releases/2.0.0-draft.md): published builds and the draft for this branch.
- [Product concept](docs/PRODUCT_CONCEPT.md) and [IntelliSense details](docs/INTELLISENSE.md).
## Build from source
diff --git a/README.ru.md b/README.ru.md
index aaa7307..16855a3 100644
--- a/README.ru.md
+++ b/README.ru.md
@@ -24,7 +24,7 @@ Paramood — надстройка для **Autodesk Fusion**, ранее Fusion
Идея проекта — **скорость работы IDE при точности параметрического CAD**. Paramood не создаёт собственную систему параметров, а работает с реальными параметрами Fusion.
-**Перед изменением:** правки через Paramood автоматически обновляют активный вариант и включают в него изменённые параметры. Выбери **Free**, чтобы оставить сохранённые варианты прежними. Применённые значения сохраняются и при ошибке зависимой операции Fusion; перед сохранением или передачей конфигурации проверь геометрию и timeline.
+**Перед изменением:** правки управляемых параметров через Paramood обновляют активный вариант. Параметры вне набора остаются глобальными и не включаются в варианты автоматически. Выбери **Free**, чтобы оставить сохранённые варианты прежними. Применённые значения сохраняются и при ошибке зависимой операции Fusion; перед сохранением или передачей конфигурации проверь геометрию и timeline.
## Список параметров и ввод в одной палитре
@@ -32,19 +32,36 @@ Paramood — надстройка для **Autodesk Fusion**, ранее Fusion
В шапке видны текущая модель, единицы длины и активный вариант. Синхронизация с Fusion выполняется автоматически.
-## В Autodesk Fusion
+## Палитра во Fusion
-F3D Cedar & Sage открыт в установленном аддоне с выбранным **Classic**. Это настоящие скриншоты Fusion на macOS.
+Палитра Hybrid объединяет дерево параметров и поле выражений. IntelliSense подсказывает параметры модели при вводе, а калькулятор использует их текущие значения:
-
+
-Ввод закреплён под списком, результаты открываются над ним. Меню переключает три конфигурации, сохранённые в примере.
+В широкой палитре вид Calculator располагает поле и результат рядом с деревом параметров:
-
+
-## Возможности Paramood 1.5.0
+Введи несколько присваиваний, чтобы увидеть текущие и предлагаемые значения до применения. В этом примере показан предпросмотр изменений варианта Compact; значения ещё не применены:
-Обзор описывает исходный код v1.5.0. На [странице Releases](https://github.com/4FusionLab/Paramood/releases) перечислены опубликованные сборки; доступные в установленной версии функции сверяй с примечаниями к её релизу.
+
+
+Переключай сохранённые варианты в шапке или открывай таблицу, чтобы сравнивать и редактировать выражения параметров и состояния поддерживаемых фич. Ширина лотка **Compact** — 120 мм; остальные столбцы доступны горизонтальной прокруткой:
+
+
+
+
+
+
+Вариант Compact проверочной модели Cedar & Sage:
+
+
+
+Снимки сделаны в проверочной сборке 2.0 во Fusion на macOS.
+
+## Возможности Paramood 2.0 — черновик для проверки
+
+Страница описывает неопубликованную ветку 2.0. На [странице Releases](https://github.com/4FusionLab/Paramood/releases) перечислены опубликованные сборки; их функции и интерфейс могут отличаться.
| Функция | Возможности |
| --- | --- |
@@ -58,7 +75,7 @@ F3D Cedar & Sage открыт в установленном аддоне с вы
| **Удаление** | По одному параметру из списка, если Fusion разрешает удаление; при отказе отображается ошибка. |
| **Связи с моделью** | Обновление при смене документа и индикаторы обнаруженных связей с эскизами, операциями и другими элементами. |
| **Калькулятор** | Вычисления с параметрами текущей модели, история последних выражений, копирование результата и формулы. |
-| **Варианты** | Именованные наборы выражений существующих параметров хранятся в модели и переносятся с F3D. Размер или конфигурация переключаются в шапке. |
+| **Варианты** | Общая таблица выражений параметров и состояний поддерживаемых фич хранится в модели. Варианты переключаются в шапке. |
| **Строковые параметры** | Текст в кавычках, ссылки, конкатенация и поддерживаемые условия; список показывает вычисленный текст, редактор сохраняет формулу. |
| **Единицы модели** | Выбор `mm`, `cm`, `m`, `in` или `ft` рядом с названием без изменения физических размеров. |
@@ -105,16 +122,23 @@ height = width / 2 # сохранение зависимости от width
## Сохранение и переключение вариантов
-Скачай [F3D Cedar & Sage](examples/cedar-sage/Cedar-Sage-Paramood.f3d) и пройди [упражнение](docs/DEMO.ru.md). Внутри — Classic, Compact и Garden с геометрическими и строковыми параметрами. См. [данные модели и SHA-256](examples/cedar-sage/model-info.json). Для описанных сценариев с вариантами и строками используй Paramood 1.5.0.
+Редактор вариантов 2.0 находится на личной проверке владельцем; релиз ещё не разрешён.
-1. В шапке открой **Free → Create variant**.
-2. Задай имя и выбери хотя бы один существующий доступный для редактирования параметр. Иерархия совпадает с основным списком; размеры `dN` находятся в **Model parameters**.
-3. Измени выбранные выражения или введи присваивание в поиске, например `box.width=30`. Меняется только черновик; **Save & apply** записывает его в модель.
-4. Создай второй вариант и переключай их по именам в шапке.
+1. Открой меню вариантов и выбери **Create variant** или общую кнопку **Edit variants** в шапке меню.
+2. Через **Configure** выбери общий для модели набор параметров и фич timeline.
+3. При любой ширине варианты показаны строками, параметры и фичи — столбцами. Кликни по значению,
+ чтобы изменить выражение для нужного варианта. Галочка фичи означает **Enabled**, снятая —
+ **Suppressed**. Ручки меняют порядок параметров и вариантов. Жесты мышью и сохранение порядка после повторного открытия проверены во Fusion на macOS.
+4. **Save** сохраняет всю таблицу и применяет изменённый активный вариант. Остальные варианты
+ сохраняются без переключения. **Cancel** позволяет отбросить черновик без изменения модели.
-При активном варианте успешные изменения через Paramood обновляют его; изменённые параметры автоматически включаются в набор. Для экспериментов без перезаписи варианта сначала выбери **Free**: текущие значения модели сохранятся. Удаление участника или самого варианта не удаляет CAD-параметры.
+Параметры набора отмечены иконкой таблицы в общем списке. Параметры вне набора остаются
+глобальными и не включаются в варианты автоматически. **Free** сохраняет текущую геометрию
+и позволяет изменять параметры без обновления вариантов. Сам переключатель работает как прежде.
-Сохрани модель или экспортируй F3D, чтобы передать варианты вместе с ней. При открытии Paramood выбирает первый созданный вариант, все сохранённые значения которого совпадают с моделью; иначе отображается Free. Внешние несовпадающие изменения переводят в Free без перезаписи варианта. Вариант содержит часть параметров: переключение меняет его участников, остальные остаются в текущем состоянии.
+Формат 2 хранится в модели отдельно: старые варианты 1.x не читаются и не мигрируются.
+Исходный пример Cedar & Sage для 1.x использует старый формат; для 2.0 используй отдельный проверочный файл или создай варианты заново.
+Подробности и границы проверки: [Варианты 2.0](docs/VARIANTS_V2.ru.md).
## Создание строковых параметров
@@ -167,7 +191,7 @@ label = caption + ' / ' + 'Compact'
- [Руководство пользователя](docs/USER_GUIDE.ru.md): ввод, единицы, варианты, строки и ограничения.
- [Пример Cedar & Sage](docs/DEMO.ru.md): модель кормушки и одноимённые параметры и группы.
-- [Опубликованные релизы](https://github.com/4FusionLab/Paramood/releases) и [примечания к 1.5.0](docs/releases/1.5.0.md): опубликованные сборки и описанная здесь версия исходного кода.
+- [Опубликованные релизы](https://github.com/4FusionLab/Paramood/releases) и [черновик примечаний 2.0](docs/releases/2.0.0-draft.ru.md): выпущенные сборки и описание этой ветки.
- [Продуктовая концепция](docs/PRODUCT_CONCEPT.ru.md) и [подробности IntelliSense](docs/INTELLISENSE.ru.md).
## Разработка
diff --git a/assets/screenshots/v2-review/classic.png b/assets/screenshots/v2-review/classic.png
new file mode 100644
index 0000000..9e8b8c0
Binary files /dev/null and b/assets/screenshots/v2-review/classic.png differ
diff --git a/assets/screenshots/v2-review/compact.png b/assets/screenshots/v2-review/compact.png
new file mode 100644
index 0000000..c0f593a
Binary files /dev/null and b/assets/screenshots/v2-review/compact.png differ
diff --git a/assets/screenshots/v2-review/fusion-menu.jpg b/assets/screenshots/v2-review/fusion-menu.jpg
new file mode 100644
index 0000000..4e85bde
Binary files /dev/null and b/assets/screenshots/v2-review/fusion-menu.jpg differ
diff --git a/assets/screenshots/v2-review/fusion-palette.jpg b/assets/screenshots/v2-review/fusion-palette.jpg
new file mode 100644
index 0000000..db16679
Binary files /dev/null and b/assets/screenshots/v2-review/fusion-palette.jpg differ
diff --git a/assets/screenshots/v2-review/fusion-table.jpg b/assets/screenshots/v2-review/fusion-table.jpg
new file mode 100644
index 0000000..b5fc214
Binary files /dev/null and b/assets/screenshots/v2-review/fusion-table.jpg differ
diff --git a/assets/screenshots/v2-review/garden.png b/assets/screenshots/v2-review/garden.png
new file mode 100644
index 0000000..d60fe84
Binary files /dev/null and b/assets/screenshots/v2-review/garden.png differ
diff --git a/assets/screenshots/v2-review/palette-intellisense.jpg b/assets/screenshots/v2-review/palette-intellisense.jpg
new file mode 100644
index 0000000..467b660
Binary files /dev/null and b/assets/screenshots/v2-review/palette-intellisense.jpg differ
diff --git a/assets/screenshots/v2-review/palette-preview.jpg b/assets/screenshots/v2-review/palette-preview.jpg
new file mode 100644
index 0000000..aeb808d
Binary files /dev/null and b/assets/screenshots/v2-review/palette-preview.jpg differ
diff --git a/assets/screenshots/v2-review/palette-variant-table.jpg b/assets/screenshots/v2-review/palette-variant-table.jpg
new file mode 100644
index 0000000..33a73cc
Binary files /dev/null and b/assets/screenshots/v2-review/palette-variant-table.jpg differ
diff --git a/assets/screenshots/v2-review/palette-variants.jpg b/assets/screenshots/v2-review/palette-variants.jpg
new file mode 100644
index 0000000..26d3d9e
Binary files /dev/null and b/assets/screenshots/v2-review/palette-variants.jpg differ
diff --git a/assets/screenshots/v2-review/palette-wide.jpg b/assets/screenshots/v2-review/palette-wide.jpg
new file mode 100644
index 0000000..3a63fd0
Binary files /dev/null and b/assets/screenshots/v2-review/palette-wide.jpg differ
diff --git a/docs/DEMO.md b/docs/DEMO.md
index 2f7b8eb..e73a703 100644
--- a/docs/DEMO.md
+++ b/docs/DEMO.md
@@ -2,6 +2,8 @@
[Русский](DEMO.ru.md) · [User guide](USER_GUIDE.md)
+> **Legacy 1.x walkthrough.** The supplied F3D and screenshots use the 1.x variant format and interface. Paramood 2.0 does not read or migrate these saved variants. A 2.0 demo export and updated walkthrough are pending; do not use the variant-editing steps below with 2.0.
+
The [Cedar & Sage F3D](../examples/cedar-sage/Cedar-Sage-Paramood.f3d) includes three variants with eight parameter entries each. It was exported in healthy Classic, reopened from that exact file, and switched through Compact and Garden using the installed palette. All 24 member identities resolved; each configuration retained 14 healthy bodies in Fusion 2706.1.17 on macOS. The model was returned to Classic. See [model information and SHA-256](../examples/cedar-sage/model-info.json). Native Windows validation remains outstanding.
## Open the example
diff --git a/docs/DEMO.ru.md b/docs/DEMO.ru.md
index 8fd1c57..41c24c4 100644
--- a/docs/DEMO.ru.md
+++ b/docs/DEMO.ru.md
@@ -2,6 +2,8 @@
[English](DEMO.md) · [Руководство](USER_GUIDE.ru.md)
+> **Пример для 1.x.** Приложенный F3D и снимки относятся к формату и интерфейсу вариантов 1.x. Paramood 2.0 не читает и не переносит эти варианты. Экспорт примера 2.0 и обновлённое руководство ещё готовятся; приведённые ниже действия с редактором вариантов не подходят для 2.0.
+
[F3D Cedar & Sage](../examples/cedar-sage/Cedar-Sage-Paramood.f3d) содержит три варианта по восемь параметров. Модель экспортирована в исправном Classic, повторно открыта именно из этого файла и переключена через установленную палитру на Compact и Garden. Все 24 участника разрешились в параметры; каждая конфигурация сохранила 14 исправных тел в Fusion 2706.1.17 на macOS. После проверки восстановлен Classic. См. [данные модели и SHA-256](../examples/cedar-sage/model-info.json). Нативная проверка Windows не завершена.
## Открытие примера
diff --git a/docs/DEMO_V2_DRAFT.md b/docs/DEMO_V2_DRAFT.md
new file mode 100644
index 0000000..b2251cb
--- /dev/null
+++ b/docs/DEMO_V2_DRAFT.md
@@ -0,0 +1,37 @@
+# Cedar & Sage — Paramood 2.0 demo draft
+
+[Русский](DEMO_V2_DRAFT.ru.md) · [Variant workflow](VARIANTS_V2.md)
+
+**Review draft:** the [2.0 demo export](../examples/cedar-sage-v2/Cedar-Sage-Paramood-2-review.f3d) was reopened and its three variants applied through the source-loaded palette in Fusion 2706.1.17 on macOS. All 11 columns resolved. It remains subject to owner review. The repository's existing [Cedar & Sage file](../examples/cedar-sage/Cedar-Sage-Paramood.f3d) is a 1.x example; its saved variants do not appear in 2.0. Do not treat it as the 2.0 demo.
+
+## Explore the variant table
+
+Open the verified 2.0 demo in Fusion with Paramood running. Open the variant switcher and choose **Edit variants** in its header. The table uses one configured set for the model: each variant is a row, each selected parameter or timeline feature a column. A checked feature is **Enabled**; unchecked means **Suppressed**.
+
+The current review model contains the following saved expressions and states. The Compact width is 120 mm, as confirmed by the owner.
+
+| Variant | Tray width | Tray depth | Post height | Roof pitch | Perch features |
+| --- | --- | --- | --- | --- | --- |
+| Classic | 180 mm | 130 mm | 120 mm | 25 deg | Enabled |
+| Compact | 120 mm | 100 mm | 100 mm | 30 deg | Suppressed |
+| Garden | 220 mm | 160 mm | 150 mm | 20 deg | Enabled |
+
+Each row also contains `caption_variant` with its variant name. Six configured Perch features represent the two supports, landing rail and their softened edges. Other model parameters are global. The `post=4` parameter is not configured; its role in the demo is undecided.
+
+Select a different variant from the header to apply it. Inspect the geometry, caption and timeline. To make a private experiment, open **Edit variants**, click a cell and edit its expression. The table is a draft until **Save**; **Cancel** discards edits after confirmation. Save validates all rows and applies a changed active row; other rows are stored without switching. **Free** keeps the current model state without applying a row. Editing an outside-set parameter does not add it to the table.
+
+The cell editor supports IntelliSense, `this`, relative edits and supported creation/linking expressions. New CAD parameters are created only on Save. A table icon in the main parameter list marks configured parameters.
+
+## Share a copy
+
+After the final export is reviewed, download the actual F3D and open it in Fusion with Paramood 2.0. Save your own copy for experiments. A valid expression can still result in a Fusion timeline warning or error; inspect the model before sharing. Paramood stores its own variant data in the design and does not use Autodesk Configuration API. This workflow does not claim full Fusion Configurations parity.
+
+**Release work remaining:** review the Fusion interface screenshots, decide the `post` role, and update this guide and the example links to the accepted artifact. The review export SHA-256 is `853d7084c86c46380adfdaa9f442d410e5b262df4caea0eb4b75cf79bd37e639`. The installed package has had a scoped macOS UI check; complete acceptance and native Windows validation remain outstanding.
+
+
+
+
+
+
+
+These are Fusion graphics-view captures of the reopened review copy, not palette screenshots.
diff --git a/docs/DEMO_V2_DRAFT.ru.md b/docs/DEMO_V2_DRAFT.ru.md
new file mode 100644
index 0000000..197b5d7
--- /dev/null
+++ b/docs/DEMO_V2_DRAFT.ru.md
@@ -0,0 +1,37 @@
+# Cedar & Sage — черновик примера Paramood 2.0
+
+[English](DEMO_V2_DRAFT.md) · [Работа с вариантами](VARIANTS_V2.ru.md)
+
+**Черновик для проверки:** [экспорт примера 2.0](../examples/cedar-sage-v2/Cedar-Sage-Paramood-2-review.f3d) повторно открыт и три варианта применены через палитру, загруженную из исходного кода, в Fusion 2706.1.17 на macOS. Все 11 столбцов найдены. Файл ожидает просмотра владельца. Существующий [файл Cedar & Sage](../examples/cedar-sage/Cedar-Sage-Paramood.f3d) относится к 1.x; его сохранённые варианты не отображаются в 2.0. Не используй его как пример 2.0.
+
+## Таблица вариантов
+
+Открой проверенный пример 2.0 во Fusion с запущенным Paramood. В меню переключателя выбери **Edit variants** в шапке. Таблица использует один набор для модели: варианты представлены строками, выбранные параметры и фичи timeline — столбцами. Галочка фичи означает **Enabled**, снятая — **Suppressed**.
+
+В текущей проверочной модели сохранены следующие выражения и состояния. Ширина Compact — 120 мм, как подтвердил владелец.
+
+| Вариант | Ширина лотка | Глубина лотка | Высота стоек | Угол крыши | Фичи Perch |
+| --- | --- | --- | --- | --- | --- |
+| Classic | 180 mm | 130 mm | 120 mm | 25 deg | Enabled |
+| Compact | 120 mm | 100 mm | 100 mm | 30 deg | Suppressed |
+| Garden | 220 mm | 160 mm | 150 mm | 20 deg | Enabled |
+
+Каждая строка также содержит `caption_variant` с названием варианта. Шесть фич Perch представляют две опоры, жердочку и скругления их краёв. Остальные параметры модели глобальны. Параметр `post=4` не входит в таблицу; его роль в примере ещё не определена.
+
+Выбери другой вариант в шапке, чтобы применить его. Проверь геометрию, подпись и timeline. Для эксперимента открой **Edit variants**, нажми ячейку и измени выражение. До **Save** таблица остаётся черновиком; **Cancel** отбрасывает правки после подтверждения. Save проверяет все строки и применяет изменённую активную строку; остальные сохраняются без переключения. **Free** сохраняет текущее состояние модели, не применяя строку. Правка параметра вне набора не добавляет его в таблицу.
+
+Редактор ячеек поддерживает IntelliSense, `this`, относительные правки и поддерживаемые выражения создания и связывания. Новые CAD-параметры создаются только при Save. Иконка таблицы в основном списке отмечает параметры набора.
+
+## Передача копии
+
+После проверки итогового экспорта скачай сам F3D и открой его во Fusion с Paramood 2.0. Для экспериментов сохрани собственную копию. Корректное выражение всё же может вызвать предупреждение или ошибку timeline Fusion; перед передачей проверь модель. Paramood хранит собственные данные вариантов в модели и не использует Autodesk Configuration API. Полная эквивалентность Fusion Configurations не заявляется.
+
+**До релиза остаётся:** просмотреть скриншоты интерфейса Fusion, определить роль `post`, затем обновить руководство и ссылки на принятый пример. SHA-256 проверочного экспорта: `853d7084c86c46380adfdaa9f442d410e5b262df4caea0eb4b75cf79bd37e639`. Установленный пакет прошёл ограниченную проверку интерфейса на macOS; полная приёмка и нативная проверка Windows ещё не завершены.
+
+
+
+
+
+
+
+Это снимки области модели Fusion после открытия проверочной копии, не скриншоты палитры.
diff --git a/docs/REQUIREMENTS.md b/docs/REQUIREMENTS.md
index cc3ffda..e53cfcf 100644
--- a/docs/REQUIREMENTS.md
+++ b/docs/REQUIREMENTS.md
@@ -1213,16 +1213,25 @@ The main chat should remain the orchestrator throughout the project.
**Goal: to get a real, high-quality implemented and expandable Autodesk Fusion Add-In Paramood, and not a set of disparate files.**
-## Variants — clarification of 7 November 2026
-
-- The model header switches between `Free` and saved variants. The interface imposes no limit on the number of variants. If none exist, the menu offers `Create variant`.
-- A variant contains selected existing parameters and their expressions. Selection uses the same name hierarchy and model-parameter section as the main list; search and group expansion are available.
-- The variant search field supports IntelliSense. Entering `box.width=30` immediately adds `box_width` to the variant draft and sets it to 30 in that parameter's unit. Expressions with dotted references are converted to Fusion names. **Save & apply** writes to the model.
-- Search by variant name appears only when there are more than five variants.
-- The menu is anchored to the selector, including in a two-column layout, and does not cause page scrolling. With many entries, only the list inside the menu scrolls.
-- Parameter changes made through Paramood while a variant is active are saved to it; changed parameters not yet included are added. The settings allow adding or removing variant members without deleting the model parameters themselves.
-- Variants are stored in the Design file attributes and read on reopening. A variant is selected when its numeric values fully match; otherwise `Free` is selected. If several match, the first created is used. Explicitly choosing `Free` does not reset values.
-- Timeline operation warnings and errors do not prevent a variant from being applied and do not cause rollback. Expression errors, write errors and stale requests are handled separately.
+## Variants 2.0 — clarification of 8 November 2026
+
+- Do not use Autodesk's Configuration API; implement the agreed workflows independently.
+- Choose one model-wide set of parameters and supported timeline features, never per-row sets.
+- The switcher menu header has shared counts and one Edit variants action; individual rows have no edit action or counts.
+- At every width: variants are rows and parameters/features are columns. Do not transpose.
+- Drag-and-drop reorders both axes; their stored orders are independent of orientation.
+- Headings remain horizontal with word wrapping; horizontal scrolling starts only when the
+ value columns cannot fit readably. Do not include a Go to control.
+- Click a value to edit its expression. Feature checked means Enabled; unchecked means Suppressed.
+- All table edits are a draft until Save. Cancellation never changes the model; confirm discarding.
+- Save validates the whole table, applies only the changed active variant and stores all rows.
+ Free applies none. Preserve the header's existing switching interaction.
+- Editing an outside-set parameter is global and never enrolls it. Mark controlled parameters in
+ the common list with a table icon and the tooltip Controlled by variants.
+- Use only variants.v2. Older records are neither read nor migrated nor deleted.
+- Release 2.0.0 only after the owner's personal review and explicit authorization. A review build
+ is not a release.
+- Contracts, API sources, evidence and limits: [Variants 2.0](VARIANTS_V2.md).
## Model units and Hybrid view — 7 November 2026
diff --git a/docs/REQUIREMENTS.ru.md b/docs/REQUIREMENTS.ru.md
index 1c6eec7..86cd6b1 100644
--- a/docs/REQUIREMENTS.ru.md
+++ b/docs/REQUIREMENTS.ru.md
@@ -1213,27 +1213,25 @@ Paramood считается готовым к первой полноценно
**Цель: получить реальный, качественно реализованный и расширяемый Autodesk Fusion Add-In Paramood, а не набор разрозненных файлов.**
-## Варианты — уточнение от 7 ноября 2026
-
-- В шапке модели расположен переключатель `Free` / сохранённые варианты. Число вариантов не
- ограничивается интерфейсом. При отсутствии вариантов меню предлагает `Create variant`.
-- Вариант содержит выбранные существующие параметры и их выражения. Выбор использует ту же
- иерархию имён и раздел модельных параметров, что и основной список; доступны поиск и раскрытие групп.
-- Поле поиска параметров поддерживает IntelliSense. Ввод `box.width=30` сразу добавляет `box_width`
- в черновик варианта и задаёт ему 30 в единицах этого параметра. Выражения с dotted-ссылками
- преобразуются в имена Fusion. Запись в модель происходит по `Save & apply`.
-- Поиск по именам самих вариантов появляется только при количестве вариантов больше пяти.
-- Меню привязано к переключателю, включая двухколоночную компоновку, и не создаёт прокрутку
- страницы. При большом количестве элементов прокручивается только список внутри меню.
-- Общая кнопка Refresh из палитры удалена; синхронизация выполняется автоматически.
-- Изменения параметров через Paramood в активном варианте сохраняются в нём; изменённые параметры,
- ещё не входящие в вариант, добавляются. Настройки позволяют добавлять и удалять участников
- варианта, не удаляя параметры самой модели.
-- Варианты сохраняются в атрибутах файла Design и читаются при повторном открытии. При открытии
- выбирается вариант с полным совпадением числовых значений; иначе `Free`. При нескольких совпадениях
- используется первый вариант в порядке создания. Явный выбор `Free` не сбрасывает значения.
-- Предупреждения и ошибки операций в timeline не блокируют применение варианта и не вызывают
- откат. Ошибки выражений, записи и устаревшие запросы обрабатываются отдельно.
+## Варианты 2.0 — уточнение от 8 ноября 2026
+
+- Configuration API Autodesk не используется: собственная замена согласованных сценариев.
+- Общий набор параметров и поддерживаемых фич задаётся для модели, а не для каждого варианта.
+- В шапке меню переключателя находятся общие счётчики и одна кнопка Edit variants; у отдельных строк нет кнопок редактирования и счётчиков.
+- При любой ширине варианты — строки, параметры/фичи — столбцы. Транспонирование не используется.
+- Порядки вариантов и участников меняются drag-and-drop; сохраняются независимо от ориентации.
+- Заголовки горизонтальные с переносом по словам; горизонтальная прокрутка
+ появляется только при нехватке места для значений. Go to отсутствует.
+- Клик по ячейке редактирует выражение. Галочка фичи означает Enabled, снятая — Suppressed.
+- До Save все правки — черновик. Отмена не меняет модель; отбрасывание правок подтверждается.
+- Save проверяет всю таблицу, применяет только изменённый активный вариант и сохраняет все строки.
+ В Free ничего не применяется. Способ переключения в шапке не меняется.
+- Изменение параметра вне общего набора глобально и не включает его в варианты. В общем списке
+ участники отмечены иконкой таблицы с подсказкой Controlled by variants.
+- Используется только variants.v2. Старые записи не читаются, не мигрируются и не удаляются.
+- Мажорный релиз 2.0.0 разрешается только после личного просмотра результата владельцем и его
+ явного разрешения. Проверочная сборка не является релизом.
+- Контракты, источники API, проверки и ограничения: [Варианты 2.0](VARIANTS_V2.ru.md).
## Единицы модели и гибридный вид — 7 ноября 2026
diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md
index 3a1a637..2a1306e 100644
--- a/docs/USER_GUIDE.md
+++ b/docs/USER_GUIDE.md
@@ -16,37 +16,31 @@ IntelliSense offers model dimensions such as `d1` only when the current token is
In an inline numeric edit, use `+=5`, `-=5`, `*=2`, or `/=2` to update the existing expression. Addition and subtraction use the parameter's unit for a bare number; multiplication and division use a dimensionless number. Existing formula dependencies are preserved.
-The unit selector beside the design name changes the design's display units to `mm`, `cm`, `m`, `in`, or `ft`. It preserves physical sizes. In an inline numeric edit or a variant search assignment, a bare number uses that parameter's unit; explicit units make examples easier to share.
+The unit selector beside the design name changes the design's display units to `mm`, `cm`, `m`, `in`, or `ft`. It preserves physical sizes. In an inline numeric edit or a variant table cell, a bare number uses that parameter's unit; explicit units make examples easier to share.
Use the copy icon beside a calculator result to copy its value with units. **Copy expression** copies the input expression. A success notification disappears after 3.5 seconds; errors remain until dismissed.
-## Create a variant
+## Variant table 2.0
-A variant stores expressions and values for a selected set of existing editable parameters. It can include user parameters, model parameters, and text parameters. It does not capture the entire design or suppress features.
+Open the common table through **Create variant** or **Edit variants** in the variant menu header. Configure selects one model-wide set
+of parameters and supported features. Click a cell to edit that variant's expression; a checked
+feature is enabled, and an unchecked feature is suppressed. Drag handles reorder either axis. Mouse gestures and saved-order round-trip were checked in Fusion on macOS.
+Variants are always rows; parameters/features are always columns, at every width. Names wrap at word boundaries;
+scrolling begins only when readable value columns no longer fit.
-1. Open the variant menu in the header and choose **Create variant**.
-2. Enter a unique name, such as `Compact`.
-3. Select the existing parameters whose expressions should belong to this variant. Expand the same groups used in the main parameter tree, or search by name with IntelliSense. The selected-count button filters to selected parameters.
-4. Edit their expressions. An assignment in the search, such as `box.width=30`, selects the existing `box_width` parameter and sets its draft expression. It does not create a CAD parameter. Press **Enter** to clear the search.
-5. Choose **Save & apply**. This both saves the variant and applies its expressions to the current model. At least one parameter is required.
+The table remains a draft until Save. Cancel/close lets you confirm discarding changes without
+changing the model. Save validates every row, applies only the edited active variant, and stores
+the table. In Free it only stores values. Parameters outside the configured set stay global and
+are never enrolled automatically. A table icon in the common parameter list marks configured items.
-Select a variant name in the header to apply it. Parameters outside the selected variant retain their current state; use the same member set across variants when you want directly comparable configurations. There is no fixed variant-count limit in Paramood, but Fusion's attribute storage has a size limit. **Find variant** appears when more than five variants exist, and long lists scroll inside the menu.
-
-## Edit, leave, or delete a variant
-
-While a variant is active, a successful parameter change through Paramood updates that variant. Changed parameters that were not members are added automatically. This includes text parameters.
-
-Choose **Free** before making changes that should leave saved variants unchanged. Free keeps the current model values. External Fusion edits that make the active variant no longer match also switch Paramood to Free; saved variants are not rewritten.
-
-Use the pencil beside a variant to change its name, members, or expressions. Removing a member keeps its CAD parameter. Deleting the variant also keeps the model's parameters and current values. A missing parameter is marked **Needs attention**; a newly created parameter with the same name is not silently substituted for the original.
-
-If the document changes while an editor is open, the stale save is rejected. Review the error and use **Reload from model** to reset the draft to the current state before trying again.
+Old 1.x variants are neither read nor migrated; 2.0 uses a separate storage format.
+See [Variants 2.0](VARIANTS_V2.md). Release awaits the owner's personal acceptance.
## Save and share with F3D
Variants are stored in the Fusion design's attributes. Use Fusion's ordinary save or F3D export to retain them; Paramood does not initiate a cloud save. Share the F3D, then open it in Fusion with Paramood running to read its variants.
-On reopening, Paramood compares saved member values with the model. Numeric comparisons use a tolerance in Fusion's internal units; text comparisons are exact, including spaces and empty text. A complete match selects that variant. If several match, the first created is selected; if none matches, the header shows **Free**. A previous explicit Free choice is not a persistent reset instruction for a later reopen.
+On reopening, Paramood compares saved member values with the model. Numeric comparisons use a tolerance in Fusion's internal units; text comparisons are exact, including spaces and empty text. A complete match selects that variant. If several match, the first row in the saved order is selected; if none matches, the header shows **Free**. A previous explicit Free choice is not a persistent reset instruction for a later reopen.
Applying a valid parameter expression can still produce a failed feature in Fusion's timeline. Timeline warnings and errors do not trigger a rollback of the applied variant. Inspect geometry and choose a healthy configuration before saving a model for others. Expression errors, stale requests, and incomplete writes are reported separately.
diff --git a/docs/USER_GUIDE.ru.md b/docs/USER_GUIDE.ru.md
index 2048c38..f1a6c0e 100644
--- a/docs/USER_GUIDE.ru.md
+++ b/docs/USER_GUIDE.ru.md
@@ -20,33 +20,26 @@ IntelliSense предлагает модельные размеры вроде `
Иконка возле результата калькулятора копирует значение с единицами. **Copy expression** копирует введённое выражение. Успешное уведомление исчезает через 3,5 секунды; ошибка остаётся до закрытия.
-## Создание варианта
+## Таблица вариантов 2.0
-Вариант хранит выражения и значения выбранных существующих редактируемых параметров: пользовательских, модельных и строковых. Он не является снимком всей модели и не управляет подавлением операций.
+Открой общую таблицу через **Create variant** или **Edit variants** в шапке меню вариантов. Configure выбирает единый набор
+параметров и поддерживаемых фич модели. Клик по ячейке редактирует выражение варианта;
+галочка включает фичу, снятая галочка подавляет её. Ручки меняют порядок. Жесты мышью и сохранение порядка после повторного открытия проверены во Fusion на macOS.
+При любой ширине варианты — строки, параметры и фичи — столбцы. Названия переносятся по словам; скролл появляется только когда не помещаются сами значения.
-1. В меню вариантов в шапке выбери **Create variant**.
-2. Введи уникальное имя, например `Compact`.
-3. Отметь параметры, выражения которых должны войти в вариант. Группы совпадают с основным деревом; поиск поддерживает IntelliSense. Кнопка с количеством выбранных оставляет в списке только участников.
-4. Измени их выражения. Присваивание в поиске, например `box.width=30`, выбирает существующий `box_width` и задаёт выражение в черновике. CAD-параметр при этом не создаётся. **Enter** очищает поиск.
-5. Нажми **Save & apply**: вариант сохраняется, а выражения применяются к модели. Нужен хотя бы один участник.
+До Save таблица — черновик. Cancel/закрытие позволяет подтвердить отбрасывание правок без
+изменения модели. Save сначала проверяет все строки, затем применяет только изменённый активный
+вариант и сохраняет таблицу. В Free значения только сохраняются. Параметры вне общего набора
+глобальны и не добавляются автоматически. Иконка таблицы в основном списке отмечает участников.
-Для применения выбери имя варианта в шапке. Остальные параметры сохраняют текущее состояние; для прямо сравнимых конфигураций используй одинаковый набор участников. Искусственного ограничения количества вариантов нет, но размер атрибутов Fusion ограничен. **Find variant** появляется при количестве больше пяти; длинный список прокручивается внутри меню.
-
-## Изменение, выход и удаление
-
-Когда вариант активен, успешное изменение параметров через Paramood обновляет его. Изменённые параметры, ещё не входящие в набор, добавляются автоматически. Это относится и к строкам.
-
-Выбери **Free** перед правками, которые не должны перезаписывать сохранённые варианты. Текущие значения модели останутся. Внешние изменения через Fusion, после которых активный вариант перестаёт совпадать с моделью, тоже переводят Paramood в Free; варианты не перезаписываются.
-
-Карандаш рядом с вариантом открывает изменение имени, участников и выражений. Исключение участника сохраняет CAD-параметр. Удаление варианта тоже сохраняет параметры и текущие значения модели. Отсутствующий параметр помечается **Needs attention**; новый одноимённый параметр не подставляется вместо исходного автоматически.
-
-Если модель изменилась при открытом редакторе, устаревшее сохранение отклоняется. Проверь ошибку и используй **Reload from model**, чтобы сбросить черновик к актуальному состоянию перед новой попыткой.
+Старые варианты 1.x не читаются и не мигрируются; используется отдельный формат 2.0.
+Подробности: [Варианты 2.0](VARIANTS_V2.ru.md). Релиз ожидает личной приёмки владельцем.
## Сохранение и передача F3D
Варианты записаны в атрибутах модели Fusion. Обычное сохранение или экспорт F3D сохраняет их; Paramood сам не запускает облачное сохранение. Передай F3D и открой его в Fusion с включённым Paramood для чтения вариантов.
-При повторном открытии Paramood сравнивает значения участников с моделью. Числа сравниваются с допуском во внутренних единицах Fusion; строки — точно, включая пробелы и пустоту. Полное совпадение выбирает вариант. Если совпало несколько, выбирается первый созданный; если ни одного — **Free**. Явный выбор Free до закрытия не задаёт постоянный сброс выбора при следующем открытии.
+При повторном открытии Paramood сравнивает значения участников с моделью. Числа сравниваются с допуском во внутренних единицах Fusion; строки — точно, включая пробелы и пустоту. Полное совпадение выбирает вариант. Если совпало несколько, выбирается первый по сохранённому порядку; если ни одного — **Free**. Явный выбор Free до закрытия не задаёт постоянный сброс выбора при следующем открытии.
Допустимое выражение может привести к ошибке операции в timeline Fusion. Ошибки и предупреждения timeline не откатывают применённый вариант. Проверяй геометрию и выбирай исправную конфигурацию перед передачей модели. Ошибки выражений, устаревшие запросы и неполная запись сообщаются отдельно.
diff --git a/docs/VARIANTS_V2.md b/docs/VARIANTS_V2.md
new file mode 100644
index 0000000..87da0cf
--- /dev/null
+++ b/docs/VARIANTS_V2.md
@@ -0,0 +1,116 @@
+# Model-wide variant table (2.0 review build)
+
+[Русская версия](VARIANTS_V2.ru.md)
+
+This development branch is awaiting the owner's personal review. Do not publish, push to main,
+create tags, or invoke the automatic release workflow until the owner explicitly authorizes release.
+`GitVersion.yml` establishes 2.0.0 as the next major version; it does not publish a release.
+
+## Workflow
+
+The header's Free/variant switcher keeps its existing switching interaction. Its menu header shows
+the shared parameter/feature counts and one Edit variants button. Individual entries only switch
+variants; they have no edit button or per-row count. Edit variants and Create variant open the same
+summary table for the model. Configure selects a single ordered set of editable user/model/text
+parameters and supported parametric timeline features. Every variant has a cell for every selected
+item. Parameters outside this set are global: editing them never enrolls them in variants, including
+when a variant is active. A small table icon in the parameter list marks controlled parameters;
+its tooltip is **Controlled by variants**, also in Free mode.
+
+- At every palette width: variants are rows; configured parameters/features are columns.
+- All headings stay horizontal and wrap at word boundaries. A single word that cannot
+ fit breaks as a fallback. Horizontal scrolling begins only when readable value columns no longer fit.
+- Drag handles reorder either axis. Both orders are stored in the model. Alt + arrow keys on a handle provide a keyboard alternative. External drag data is
+ not accepted as a new item or identity.
+- Click a parameter value to edit its expression. The shared CodeMirror editor selects its contents on focus and provides the same IntelliSense,
+ dotted/Cyrillic names, functions, units, signatures, highlighting and editing history as the main
+ palette. Completion and signature popups are attached outside the scrolling table. Enter/blur
+ validates the cell into the draft through a read-only, row-aware native preview; neither writes
+ CAD data. This includes `this`, relative edits, creating/linking a new name or `x=25`, and supported
+ scaled-variable equations. The preview resolves these against that variant's values, not the
+ currently displayed model values.
+- A checked feature is **Enabled**; an unchecked feature is **Suppressed**.
+- A new variant captures current model values for the configured set. Duplicate copies the row.
+ Adding a configured item initializes its cell in every variant from the current model state.
+- Click a variant name to rename it in place. Duplicate and Delete buttons are beside the name;
+ deletion requires confirmation in that row. The final row is always **+ Add variant**. Removing a configured item or deleting a variant never
+ deletes the underlying CAD parameter/feature.
+
+All table edits remain a draft until **Save**. Cancel/close asks before discarding a changed draft.
+Saving validates every row first. If the current active variant's cells changed, Save also applies
+that row to the model. Other rows are stored without switching. In Free mode no row is applied.
+If the active row was deleted, the current geometry is retained and the selection becomes Free.
+Storage failure after an active-row apply attempts to restore its expressions and suppression;
+failed restoration is reported as a partial operation requiring model inspection.
+
+When Fusion state changes externally, the draft remains visible, Save is disabled, and reloading
+requires confirmation before replacing nonempty edits. Requests retain the captured document,
+storage and model snapshot identities. No live CAD entities are kept in the frontend.
+
+**Pick from timeline** in Configure starts a draft-only selection mode. Click supported features
+in Fusion's timeline; each selected feature becomes a column, with its current Enabled state in
+every row. Done picking stops listening. Repeated selections do not duplicate a column. The mode
+requires the normal Select command; other active commands are neither interrupted nor terminated.
+Selection events carry the document identity and cannot add items to a different document's draft.
+The searchable feature list remains an alternative.
+
+New parameters created from a cell remain pending global definitions until Save. They do not
+become configured columns automatically. Save validates every row and creates/links the pending
+parameters in a native Fusion command transaction. Creating parameters while another command is
+active is rejected before any writes; finish that command first. Cancellation discards all pending
+creations. Source/preview identities are rechecked before persistence.
+
+The branch includes origin/main commit `5cb1e55` (native expressions, extended units and stochastic
+Preview/Apply). Database-unit conversion covers derived dimensions; random samples are not used
+to decide whether an unchanged active row needs reapplying.
+
+## Storage and boundaries
+
+Only format 2 in Design attribute `4FusionLab.Paramood / variants.v2` is used. The older
+`variants.v1` attribute is neither read nor migrated nor deleted. Existing 1.x example files retain
+their geometry, but their old saved variants do not appear in 2.0. Recreate them using the table.
+No Autodesk Configuration API or Configured Design conversion is used.
+
+The attribute holds one ordered column list and ordered variant rows. Each row's parameter and
+feature cells must exactly match their respective configured lists. CAD entities are resolved by
+`Design.findEntityByToken` and compared as entities when checking duplicates. Names alone are not
+used to replace deleted identities. Nonempty unique names, cell types, expressions, dependency
+snapshots, payload identities, and the 2 MiB storage bound are validated before persistence.
+
+Feature discovery traverses timeline groups and includes valid parametric `Feature` objects.
+Direct features, sketches, groups as a whole and operations without a public Feature entity are not
+selectable. Individual features within groups are supported. Enables follow timeline order;
+suppression follows reverse timeline order, regardless of table sorting. Existing downstream
+timeline warnings/errors remain distinct from failed expression/state writes.
+
+This is a replacement for the agreed parameter/suppression workflows, not full feature parity with
+Fusion Configurations. Visibility, materials/appearances, part properties, theme tables, rules,
+configured inserts and other downstream workflows are not implemented in this build.
+
+## Verification
+
+- Offline: core format and ordering, all-row validation, parameter-set boundaries, active-row Save,
+ failed-write restoration, stale requests, feature identity/order and collapsed-group traversal.
+- Frontend: global membership, Enabled semantics, draft retention/cancellation, both reorder axes,
+ foreign-drop rejection, switcher actions and parameter markers.
+- Browser: the real frontend in `frontend/variants-preview.html` with a clearly simulated bridge;
+ one consistent orientation at all widths, word-wrapped headings, late overflow, dragging and saved cell order.
+- Fusion on macOS, 2706.1.17: `tests/fusion_variants_v2_smoke.py` (`run`, then `finish` after the event loop) ran on a disposable document;
+ save in Free did not apply, extrusion suppression/unsuppression worked, physical heights of 35
+ and 45 mm were checked, active-row Save applied only that row, outside-set edits stayed global,
+ controlled markers were present in state, native feature selection and its event were received,
+ legacy data remained untouched, and Free kept geometry.
+ A separate native UI test clicked the extrusion icon in the temporary model timeline and
+ confirmed the selected ExtrudeFeature and activeSelectionChanged event. The temporary documents
+ were discarded and the original document restored. Cell creation preview left the new parameter
+ absent; a real command transaction then created `draft_beam` and linked the 27 mm target without
+ adding it to the configured set.
+- This source-adapter smoke test does not prove the installed palette UI, F3D round-trip, all
+ feature types, Windows operation, or the owner's acceptance. No release has been authorized.
+
+API sources: [Feature.isSuppressed](https://help.autodesk.com/cloudhelp/ENU/Fusion-360-API/files/fusion_Feature_isSuppressed.htm),
+[Feature.isParametric](https://help.autodesk.com/cloudhelp/ENU/Fusion-360-API/files/fusion_Feature_isParametric.htm),
+[TimelineObject.entity](https://help.autodesk.com/cloudhelp/ENU/Fusion-360-API/files/fusion_TimelineObject_entity.htm),
+[Feature.entityToken](https://help.autodesk.com/cloudhelp/ENU/Fusion-360-API/files/fusion_Feature_entityToken.htm).
+
+Selection API: [UserInterface.activeSelectionChanged](https://help.autodesk.com/cloudhelp/ENU/Fusion-360-API/files/core_UserInterface_activeSelectionChanged.htm).
diff --git a/docs/VARIANTS_V2.ru.md b/docs/VARIANTS_V2.ru.md
new file mode 100644
index 0000000..eedf544
--- /dev/null
+++ b/docs/VARIANTS_V2.ru.md
@@ -0,0 +1,107 @@
+# Общая таблица вариантов — проверочная сборка 2.0
+
+[English version](VARIANTS_V2.md)
+
+Ветка ожидает личного просмотра владельцем. До явного разрешения на релиз нельзя публиковать
+сборку, отправлять её в main, создавать теги или запускать автоматический выпуск.
+`GitVersion.yml` задаёт следующую мажорную версию 2.0.0, но сам ничего не публикует.
+
+## Работа с таблицей
+
+Переключатель Free/варианты в шапке сохраняет прежний способ работы. Карандаш или Create variant
+открывает общую таблицу модели. Configure выбирает единый упорядоченный набор редактируемых
+пользовательских, модельных и строковых параметров, а также поддерживаемых параметрических фич
+timeline. Каждый вариант имеет ячейку для каждого участника. Параметры вне набора глобальны:
+их изменение не включает их в варианты даже при активном варианте. Иконка таблицы в общем списке
+отмечает управляемые параметры; подсказка **Controlled by variants** доступна и в режиме Free.
+
+- При любой ширине палитры варианты — строки, параметры и фичи — столбцы.
+- Все заголовки горизонтальные и переносятся по словам; слишком длинное отдельное слово
+ разбивается только при необходимости. Горизонтальная прокрутка появляется лишь при нехватке места для читаемых значений.
+- Ручки позволяют перетаскивать оба порядка. Они сохраняются в модели. Alt + стрелки на ручке служат клавиатурной альтернативой. Внешние данные перетаскивания
+ не создают новые элементы и не подменяют идентичность объектов.
+- Клик открывает общий редактор CodeMirror с IntelliSense, dotted- и кириллическими именами,
+ функциями, единицами, сигнатурами, подсветкой и историей редактирования. Подсказки не обрезаются
+ прокручиваемой таблицей. Enter/выход проверяет ячейку в read-only preview для строки варианта,
+ без CAD-записи. Поддержаны `this`, относительные правки, создание/связывание нового имени,
+ `x=25` и поддерживаемые уравнения с одной новой переменной. Используются значения выбранной
+ строки, а не текущие значения модели.
+- Галочка фичи означает **Enabled**, снятая галочка — **Suppressed**.
+- Новый вариант получает текущие значения модели для выбранного набора. Duplicate копирует строку.
+ Добавление участника заполняет его ячейки во всех вариантах текущим состоянием модели.
+- Клик по имени переименовывает вариант на месте. Кнопки Duplicate и Delete расположены рядом;
+ удаление требует подтверждения в той же строке. Последняя строка — **+ Add variant**. Исключение участника или удаление варианта не удаляет
+ соответствующий CAD-параметр или фичу.
+
+Все изменения таблицы остаются черновиком до **Save**. При закрытии изменённой таблицы требуется
+подтвердить отбрасывание черновика. Save сначала проверяет все строки. Если изменились ячейки
+активного варианта, Save также применяет именно его к модели. Остальные строки сохраняются без
+переключения. В Free ничего не применяется. При удалении активной строки геометрия сохраняется,
+а выбор становится Free. Если после применения не удалось записать таблицу, выполняется попытка
+восстановить выражения и suppression; неудачное восстановление сообщается как частичная операция.
+
+Внешнее изменение Fusion не стирает черновик: Save блокируется, а замена введённых данных при
+Reload from model требует подтверждения. Запросы содержат идентичность документа, хранилища
+и снимка модели. Фронтенд не хранит живые CAD-объекты.
+
+**Pick from timeline** в Configure включает выбор только для черновика. Кликни поддерживаемую
+фичу на таймлайне Fusion: она станет столбцом с текущим состоянием Enabled во всех вариантах.
+Done picking завершает режим. Повторный выбор не дублирует столбец. Требуется обычный Select;
+другие команды не прерываются и не завершаются автоматически. События содержат идентичность
+документа и не могут добавить участника в чужой черновик. Поиск по списку остаётся альтернативой.
+
+Созданные из ячеек параметры остаются отложенными глобальными определениями до Save и не
+добавляются в набор автоматически. Save проверяет все строки, затем создаёт и связывает параметры
+в нативной транзакции Fusion. Если другая команда активна, создание отклоняется до записи;
+сначала заверши эту команду. Отмена отбрасывает и новые определения.
+
+В ветку включён origin/main `5cb1e55`: нативные выражения, расширенные единицы и random в
+Preview/Apply. Перевод во внутренние единицы учитывает производные размерности; случайная
+оценка не вызывает лишнее применение неизменённой активной строки.
+
+## Хранение и ограничения
+
+Используется только формат 2 в атрибуте Design `4FusionLab.Paramood / variants.v2`. Прежний атрибут
+`variants.v1` не читается, не мигрируется и не удаляется. Геометрия примеров 1.x сохраняется,
+но старые варианты в 2.0 не отображаются: их нужно создать заново в таблице.
+Configuration API Autodesk и преобразование модели в Configured Design не используются.
+
+Атрибут содержит общий порядок колонок и порядок вариантов. Ячейки каждой строки обязаны точно
+соответствовать выбранным параметрам и фичам. Объекты разрешаются через Design.findEntityByToken;
+при проверке дубликатов сравниваются объекты, а не строки токенов. Новый одноимённый объект не
+подставляется вместо удалённого. До записи проверяются имена, типы ячеек, выражения, зависимости,
+идентичность запроса и ограничение 2 MiB.
+
+Обход timeline учитывает группы и включает валидные параметрические Feature. Прямые операции,
+эскизы, группы целиком и элементы без публичного Feature не выбираются. Отдельные фичи внутри
+групп поддерживаются. Включение идёт в порядке timeline, подавление — в обратном, независимо
+от порядка таблицы. Предупреждения и ошибки последующих операций отделены от ошибок записи.
+
+Сборка заменяет согласованные сценарии параметров и suppression. Полного соответствия Fusion
+Configurations пока нет: видимость, материалы, внешний вид, свойства деталей, тематические
+подтаблицы, правила, вставки конфигураций и связанные дальнейшие сценарии не реализованы.
+
+## Проверки
+
+- Офлайн: формат, порядок, проверка всех строк, границы общего набора, Save активной строки,
+ восстановление при ошибке записи, устаревшие запросы, идентичность фич и обход свёрнутых групп.
+- Фронтенд: общий набор, смысл Enabled, сохранность и отмена черновика, оба порядка, отклонение
+ внешнего drop, действия переключателя и метки параметров.
+- Браузер: настоящий фронтенд с имитацией моста в `frontend/variants-preview.html`, единая ориентация при любой ширине,
+ переносы заголовков, позднее появление скролла, перетаскивание и сохранение порядка ячеек.
+- Fusion на macOS, 2706.1.17: `tests/fusion_variants_v2_smoke.py` (`run`, затем `finish` после возврата в event loop) прошёл на временной модели.
+ Save в Free не применял значения; extrusion подавлялся и включался; проверены реальные высоты
+ 35 и 45 мм; Save применял только активную строку; внешний параметр оставался глобальным;
+ состояние содержало метки управляемых параметров; получены нативный выбор фичи и событие выбора; старый атрибут не менялся; Free сохранял
+ геометрию. Отдельно выполнен настоящий клик мышью по extrusion на таймлайне временной модели;
+ подтверждены выбранная ExtrudeFeature и событие activeSelectionChanged. Временные документы
+ закрыты без сохранения, исходный документ восстановлен. Preview создания не добавил параметр
+ в модель; затем настоящая транзакция создала draft_beam и связала целевой параметр 27 мм,
+ не включая новый параметр в управляемый набор.
+- Проверка исходного адаптера не подтверждает UI установленной палитры, F3D round-trip, все типы
+ фич, Windows или личную приёмку владельцем. Разрешения на релиз нет.
+
+Первичные источники API перечислены в [английской версии](VARIANTS_V2.md).
+
+В шапке списка вариантов показано общее количество параметров и фич и одна кнопка Edit variants.
+У отдельных вариантов нет карандашей и счётчиков. Всё редактирование выполняется в сводной таблице.
diff --git a/docs/releases/2.0.0-draft.md b/docs/releases/2.0.0-draft.md
new file mode 100644
index 0000000..80b802f
--- /dev/null
+++ b/docs/releases/2.0.0-draft.md
@@ -0,0 +1,21 @@
+# Paramood 2.0.0 — release notes draft
+
+[Русский](2.0.0-draft.ru.md)
+
+**Review draft, not a release.** Publication requires the owner's personal review and explicit authorization. Owner review of the screenshots, final package approval and release authorization remain outstanding.
+
+## Model-wide variant table
+
+- Configure one shared set of editable parameters and supported timeline features. Variants are rows; configured items are columns. The menu header contains the shared counts and **Edit variants**.
+- Edit expressions with IntelliSense, `this`, relative operations and supported new-parameter and equation syntax. New CAD parameters are created only on **Save**.
+- A checked feature is **Enabled**, and an unchecked feature is **Suppressed**. Changes remain a draft until **Save**; **Cancel** discards them after confirmation.
+- Save validates every row and applies the changed active variant; other rows are stored without switching. Outside-set parameters remain global. A table icon identifies controlled parameters.
+- Row and column ordering is designed to be editable. Native Fusion drag gestures and saved-order round-trip have been checked on both axes on macOS.
+
+## Compatibility
+
+2.0 stores its own `variants.v2` data. It does not read, migrate or delete older `variants.v1` records. Recreate 1.x variants in the new table. This is an independent implementation and does not use Autodesk's Configuration API; it does not offer full Fusion Configurations parity. See [the workflow and limits](../VARIANTS_V2.md).
+
+## Validation still required
+
+On macOS, the review ZIP was registered and loaded in Fusion 2706.1.17. A disposable F3D was reopened, all three variants applied, and row and column order persisted after drag, Save and F3D reopen. This is a scoped installed-palette check, not complete acceptance. Screenshot and final package review and native Windows validation remain outstanding; see [review checklist](2.0.0-review-checklist.md).
diff --git a/docs/releases/2.0.0-draft.ru.md b/docs/releases/2.0.0-draft.ru.md
new file mode 100644
index 0000000..08b0322
--- /dev/null
+++ b/docs/releases/2.0.0-draft.ru.md
@@ -0,0 +1,21 @@
+# Paramood 2.0.0 — черновик примечаний к выпуску
+
+[English](2.0.0-draft.md)
+
+**Черновик для проверки, не релиз.** Публикация требует личного просмотра владельца и его явного разрешения. Просмотр снимков владельцем и утверждение итогового пакета ещё не завершены.
+
+## Общая таблица вариантов модели
+
+- Выбирается единый набор редактируемых параметров и поддерживаемых фич timeline. Варианты — строки, выбранные элементы — столбцы. Общие счётчики и **Edit variants** находятся в шапке меню.
+- Выражения редактируются с IntelliSense, `this`, относительными операциями и поддерживаемым синтаксисом новых параметров и уравнений. Новые CAD-параметры создаются только при **Save**.
+- Галочка фичи означает **Enabled**, снятая галочка — **Suppressed**. До **Save** изменения остаются черновиком; **Cancel** отбрасывает их после подтверждения.
+- Save проверяет все строки и применяет изменённый активный вариант; остальные сохраняются без переключения. Параметры вне набора остаются глобальными. Участники отмечены иконкой таблицы.
+- Предусмотрено изменение порядка строк и столбцов. Перетаскивание строк и столбцов и сохранение порядка после повторного открытия проверены во Fusion на macOS.
+
+## Совместимость
+
+2.0 хранит собственные данные `variants.v2`. Старые записи `variants.v1` не читаются, не переносятся и не удаляются. Варианты 1.x необходимо создать заново в новой таблице. Реализация самостоятельная и не использует Autodesk Configuration API; полной функциональной эквивалентности Fusion Configurations нет. См. [порядок работы и ограничения](../VARIANTS_V2.ru.md).
+
+## Оставшиеся проверки
+
+На macOS проверочный ZIP зарегистрирован и запущен во Fusion 2706.1.17. Одноразовая копия F3D открыта повторно, три варианта применены, порядок строк и столбцов сохранился после перетаскивания, Save и повторного открытия. Это ограниченная проверка установленной палитры, а не полная приёмка. Ещё нужны просмотр снимков, проверка итогового пакета и нативная проверка Windows; см. [список проверок](2.0.0-review-checklist.md).
diff --git a/docs/releases/2.0.0-review-checklist.md b/docs/releases/2.0.0-review-checklist.md
new file mode 100644
index 0000000..b8dd990
--- /dev/null
+++ b/docs/releases/2.0.0-review-checklist.md
@@ -0,0 +1,18 @@
+# Paramood 2.0 review checklist
+
+This is a review build. Merging runtime changes to `main` can trigger an automatic release; the owner must review and explicitly authorize that step.
+
+## Evidence
+
+- Offline: Python 511 tests and 22 subtests, frontend 168 tests, and 48 IntelliSense tests passed; Ruff, Prettier, ESLint and frontend build passed on product revision `319c6c4`.
+- Browser: pointer gestures reorder both axes and preserve order after Save and reopening the table. Horizontal scrolling keeps **Add variant** visible.
+- Fusion 2706.1.17 on macOS: the ZIP was registered and its module and palette loaded from the extracted package. On a disposable design, row and column drag, Save, F3D export and reimport preserved both orders. This is a scoped installed-palette check, not complete acceptance or a Windows result.
+- The [review F3D](../../examples/cedar-sage-v2/Cedar-Sage-Paramood-2-review.f3d) was reopened; all 11 configured items resolved. Classic, Compact and Garden were switched through the palette. Classic and Garden had 14 bodies and no nonhealthy timeline items; Compact had 11 bodies and six suppressed Perch features. Compact's width is 120 mm.
+- The three [Fusion UI screenshots](../../assets/screenshots/v2-review/) show the installed review build and await owner review. The 1.x example remains available separately.
+
+## Remaining review
+
+- [ ] Owner reviews the interface, screenshots, model and release notes, including the role of `post=4`.
+- [ ] Review the final packaged artifact and repeat checks if product sources change.
+- [ ] Record any additional acceptance separately, including native Windows; current evidence does not establish full platform coverage.
+- [ ] Obtain explicit owner authorization before merging to `main` or publishing. Do not create tags manually.
diff --git a/examples/cedar-sage-v2/Cedar-Sage-Paramood-2-review.f3d b/examples/cedar-sage-v2/Cedar-Sage-Paramood-2-review.f3d
new file mode 100644
index 0000000..0d326e4
Binary files /dev/null and b/examples/cedar-sage-v2/Cedar-Sage-Paramood-2-review.f3d differ
diff --git a/examples/cedar-sage/README.md b/examples/cedar-sage/README.md
index 24d025b..2af3ac4 100644
--- a/examples/cedar-sage/README.md
+++ b/examples/cedar-sage/README.md
@@ -2,6 +2,8 @@
[Русский](README.ru.md) · [Step-by-step walkthrough](../../docs/DEMO.md)
+> **Legacy 1.x example:** Paramood 2.0 does not read or migrate the variants in this file. A separate 2.0 demo export is pending.
+
Download [Cedar-Sage-Paramood.f3d](Cedar-Sage-Paramood.f3d) to try saved model variants in Autodesk Fusion. The file contains the feeder geometry and all three Paramood variants; no separate variant settings file is required. Use Paramood 1.5.0 for the variants and text workflows described in the repository’s main README.
1. Save the actual F3D file from GitHub to your computer.
diff --git a/examples/cedar-sage/README.ru.md b/examples/cedar-sage/README.ru.md
index 1e09d6e..74f5566 100644
--- a/examples/cedar-sage/README.ru.md
+++ b/examples/cedar-sage/README.ru.md
@@ -1,6 +1,8 @@
# Cedar & Sage — пример Paramood
-[English](README.md) · [Пошаговая инструкция](../../docs/DEMO.ru.md)
+[English](README.md)
+
+> **Пример для 1.x:** Paramood 2.0 не читает и не переносит варианты из этого файла. Отдельный экспорт примера 2.0 ещё готовится. · [Пошаговая инструкция](../../docs/DEMO.ru.md)
Скачай [Cedar-Sage-Paramood.f3d](Cedar-Sage-Paramood.f3d), чтобы попробовать варианты модели в Autodesk Fusion. Файл содержит геометрию кормушки и все три варианта Paramood; отдельный файл настроек не нужен. Для описанных в основном README вариантов и строк используй Paramood 1.5.0.
diff --git a/frontend/src/bridge.ts b/frontend/src/bridge.ts
index db30a04..1f6c14e 100644
--- a/frontend/src/bridge.ts
+++ b/frontend/src/bridge.ts
@@ -12,6 +12,7 @@ export interface Parameter {
driven?: boolean;
favorite?: boolean;
valueExpression?: string | null;
+ configured?: boolean;
}
export interface ModelState {
draftId?: string;
@@ -25,6 +26,9 @@ export interface ModelState {
variantsToken?: string;
variantSnapshotToken?: string;
variantsError?: string;
+ variantColumns?: VariantColumn[];
+ variantTableVersion?: number;
+ timelineFeatures?: VariantFeature[];
}
export interface VariantParameter {
name: string;
@@ -38,6 +42,20 @@ export interface Variant {
id: string;
name: string;
parameters: VariantParameter[];
+ features?: VariantFeature[];
+}
+export interface VariantFeature {
+ name: string;
+ entityToken: string;
+ enabled: boolean;
+ missing?: boolean;
+}
+export interface VariantColumn {
+ kind: 'parameter' | 'feature';
+ name: string;
+ entityToken: string;
+ unit?: string;
+ missing?: boolean;
}
export interface PreviewItem {
name: string;
@@ -95,8 +113,33 @@ export interface Prefill {
prefillId: string;
}
let prefillListener: ((payload: Prefill) => void) | undefined;
+export interface TimelineSelection {
+ documentId: string;
+ features: VariantFeature[];
+}
+let timelineSelectionListener: ((payload: TimelineSelection) => void) | undefined;
window.fusionJavaScriptHandler = {
handle(action, raw) {
+ if (action === 'variants.selection') {
+ try {
+ const payload = JSON.parse(raw) as TimelineSelection;
+ if (
+ typeof payload.documentId !== 'string' ||
+ !Array.isArray(payload.features) ||
+ !payload.features.every(
+ (f) =>
+ typeof f.name === 'string' &&
+ typeof f.entityToken === 'string' &&
+ typeof f.enabled === 'boolean',
+ )
+ )
+ return 'Invalid payload';
+ timelineSelectionListener?.(payload);
+ return 'OK';
+ } catch {
+ return 'Invalid payload';
+ }
+ }
if (action === 'state.changed') {
eventListener?.();
return 'OK';
@@ -140,6 +183,12 @@ export function onStateChanged(listener: () => void): () => void {
if (eventListener === listener) eventListener = undefined;
};
}
+export function onTimelineSelection(listener: (payload: TimelineSelection) => void): () => void {
+ timelineSelectionListener = listener;
+ return () => {
+ if (timelineSelectionListener === listener) timelineSelectionListener = undefined;
+ };
+}
export function onParametersPrefill(listener: (payload: Prefill) => void): () => void {
prefillListener = listener;
return () => {
diff --git a/frontend/src/editor.tsx b/frontend/src/editor.tsx
index 900fbe0..600d709 100644
--- a/frontend/src/editor.tsx
+++ b/frontend/src/editor.tsx
@@ -4,6 +4,7 @@ import {
EditorView,
keymap,
placeholder,
+ tooltips,
hoverTooltip,
Decoration,
ViewPlugin,
@@ -169,6 +170,8 @@ interface Props {
disabled?: boolean;
label: string;
hint: string;
+ floatingTooltips?: boolean;
+ onBlur?: () => void;
}
function highlighting(
parameters: () => Parameter[],
@@ -257,6 +260,9 @@ export function ExpressionEditor(props: Props) {
]
: []),
history(),
+ ...(props.floatingTooltips
+ ? [tooltips({ parent: document.body, position: 'fixed' })]
+ : []),
expressionSignatureHelp,
highlighting(
() => latest.current.parameters,
@@ -267,6 +273,7 @@ export function ExpressionEditor(props: Props) {
EditorView.lineWrapping,
EditorView.domEventObservers({
focus: () => latest.current.onFocus?.(),
+ blur: () => latest.current.onBlur?.(),
}),
readOnly.current.of([
EditorState.readOnly.of(!!props.disabled),
diff --git a/frontend/src/parameter-list.tsx b/frontend/src/parameter-list.tsx
index ee3162c..5852518 100644
--- a/frontend/src/parameter-list.tsx
+++ b/frontend/src/parameter-list.tsx
@@ -12,6 +12,7 @@ import {
Star,
ChevronsDownUp,
ChevronsUpDown,
+ Table2,
} from 'lucide-preact';
import type { Parameter } from './bridge';
@@ -132,6 +133,15 @@ function Branch({
{name}
)}
+ {parameter?.configured && (
+
+
+
+ )}
{parameter?.linked && (
span {
+ margin-left: auto;
+ color: var(--muted);
+}
+.variant-table-picker {
+ padding: 10px 12px;
+ background: var(--subtle);
+ border-block: 1px solid var(--border);
+}
+.variant-table-picker > input {
+ display: block;
+ width: 100%;
+ margin-block: 8px;
+ padding: 6px;
+ color: var(--text);
+ background: var(--surface);
+ border: 1px solid var(--border);
+ border-radius: 3px;
+}
+.table-feature-heading {
+ display: block;
+ margin-top: 10px;
+}
+.table-feature-option {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 5px 0;
+}
+.variant-table-scroll {
+ overflow: auto;
+ flex-shrink: 0;
+ border-block: 1px solid var(--border);
+}
+.variant-config-table {
+ table-layout: fixed;
+ border-collapse: separate;
+ border-spacing: 0;
+ width: 100%;
+}
+.variant-config-table th,
+.variant-config-table td {
+ border-right: 1px solid var(--border);
+ border-bottom: 1px solid var(--border);
+ padding: 6px;
+ overflow-wrap: anywhere;
+ text-align: left;
+}
+.variant-config-table th {
+ background: var(--subtle);
+ font-weight: 500;
+}
+.variant-config-table tr:last-child > * {
+ border-bottom: 0;
+}
+.variant-config-table tr > :first-child {
+ position: sticky;
+ left: 0;
+ width: var(--variant-name-width);
+ z-index: 1;
+ background: var(--surface);
+ border-right: 2px solid var(--border);
+}
+.variant-config-table thead th:first-child {
+ background: var(--subtle);
+}
+.variant-table-heading {
+ display: flex;
+ align-items: center;
+ gap: 3px;
+ min-width: 0;
+}
+.variant-table-heading small {
+ display: block;
+ color: var(--muted);
+ font-weight: 400;
+}
+.table-drag-handle {
+ touch-action: none;
+ user-select: none;
+ padding: 2px;
+ border: 0;
+ background: transparent;
+ cursor: grab;
+ flex-shrink: 0;
+}
+.table-drag-handle:active {
+ cursor: grabbing;
+}
+.table-drop-target {
+ outline: 2px solid var(--accent);
+ outline-offset: -2px;
+}
+.variant-table-name {
+ border: 0;
+ background: transparent;
+ padding: 3px;
+ text-align: left;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ max-width: 100%;
+}
+.variant-config-table input:not([type='checkbox']) {
+ min-width: 0;
+ width: 100%;
+ padding: 5px 2px;
+ border: 1px solid transparent;
+ background: var(--surface);
+ color: var(--text);
+ border-radius: 2px;
+}
+.variant-config-table input:not([type='checkbox']):hover {
+ border-color: var(--border);
+}
+.variant-cell-value {
+ display: block;
+ width: 100%;
+ padding: 5px 2px;
+ text-align: left;
+ border: 0;
+ background: transparent;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.variant-config-table .parameter-edit {
+ width: 100%;
+ min-width: 0;
+ flex: initial;
+}
+body > .cm-tooltip {
+ z-index: 100;
+}
+.variant-config-table td.variant-feature-cell {
+ text-align: center;
+}
+.variant-feature-cell input {
+ width: 16px;
+ height: 16px;
+ accent-color: var(--accent);
+}
+.variant-row-heading {
+ display: flex;
+ flex-direction: column;
+ align-items: stretch;
+ gap: 2px;
+}
+.variant-row-heading .variant-table-name {
+ white-space: normal;
+ overflow-wrap: anywhere;
+ padding: 2px;
+}
+.variant-row-actions {
+ display: flex;
+ align-items: center;
+ gap: 2px;
+}
+.variant-row-actions .icon {
+ padding: 3px;
+}
+.variant-active-label {
+ color: var(--accent);
+}
+.variant-add-row button {
+ position: sticky;
+ left: 6px;
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ border: 0;
+ color: var(--accent);
+}
+.variant-add-row > td {
+ position: static !important;
+}
+.variant-delete-row > td {
+ position: static !important;
+ background: var(--subtle);
+}
+.variant-inline-confirm {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ flex-wrap: wrap;
+}
+.variant-table-dialog .variant-dialog-footer > span {
+ margin-right: auto;
+ color: var(--muted);
+}
+.table-fill {
+ color: var(--accent);
+ padding: 3px;
+}
+.configured-parameter {
+ display: inline-flex;
+ flex-shrink: 0;
+ color: var(--accent);
+}
+.variant-table-dialog .sr-only {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ overflow: hidden;
+ clip-path: inset(50%);
+}
.variant-dialog-header {
display: flex;
align-items: center;
diff --git a/frontend/src/variant-parameter-tree.tsx b/frontend/src/variant-parameter-tree.tsx
index c839b8b..6a9253a 100644
--- a/frontend/src/variant-parameter-tree.tsx
+++ b/frontend/src/variant-parameter-tree.tsx
@@ -10,6 +10,7 @@ type Props = {
disabled: boolean;
filtered: boolean;
onChange: (parameters: VariantParameter[]) => void;
+ selectionOnly?: boolean;
};
export function VariantParameterTree({
@@ -18,6 +19,7 @@ export function VariantParameterTree({
disabled,
filtered,
onChange,
+ selectionOnly = false,
}: Props) {
const [expanded, setExpanded] = useState>({});
const [allOpen, setAllOpen] = useState(undefined);
@@ -83,7 +85,7 @@ export function VariantParameterTree({
{parameter &&
(parameter.missing ? (
Missing from model
- ) : entry ? (
+ ) : entry && !selectionOnly ? (
& { id?: string; key: string };
+export type TableDraft = {
+ columns: VariantColumn[];
+ rows: TableRow[];
+ newParameters?: Parameter[];
+};
+export const columnKey = (column: VariantColumn) => `${column.kind}:${column.entityToken}`;
+
+export function tableDraft(model: ModelState): TableDraft {
+ const columns = model.variantColumns?.map((c) => ({ ...c })) ?? [];
+ const rows = (model.variants ?? []).map((row) => ({
+ ...row,
+ key: row.id,
+ parameters: row.parameters.map((p) => ({ ...p })),
+ features: (row.features ?? []).map((f) => ({ ...f })),
+ }));
+ return { columns, rows };
+}
+
+export function newRow(model: ModelState, columns: VariantColumn[], name: string): TableRow {
+ return {
+ key: crypto.randomUUID(),
+ name,
+ parameters: columns.flatMap((c) => {
+ if (c.kind !== 'parameter') return [];
+ const p = model.parameters.find((p) => p.name === c.name && !p.driven && p.entityToken);
+ return p && !c.missing
+ ? [{ ...p, entityToken: c.entityToken, value: p.value, missing: false }]
+ : [];
+ }),
+ features: columns.flatMap((c) => {
+ if (c.kind !== 'feature') return [];
+ const f = model.timelineFeatures?.find((f) => f.entityToken === c.entityToken);
+ return f ? [{ ...f }] : [];
+ }),
+ };
+}
+
+/** A drop moves an existing member, never accepts data or identities from another window. */
+export function moveItem(items: T[], from: number, to: number): T[] {
+ if (from < 0 || to < 0 || from >= items.length || to >= items.length || from === to) return items;
+ const result = [...items];
+ result.splice(to, 0, result.splice(from, 1)[0]);
+ return result;
+}
+
+export function tableProblem(draft: TableDraft): string | undefined {
+ if (draft.rows.length && !draft.columns.length)
+ return 'Select at least one parameter or feature.';
+ const names = new Set();
+ for (const row of draft.rows) {
+ const name = row.name.trim().toLocaleLowerCase();
+ if (!name || row.name.trim().length > 120)
+ return 'Enter a name for every variant (up to 120 characters).';
+ if (names.has(name)) return 'Variant names must be unique.';
+ names.add(name);
+ for (const c of draft.columns) {
+ if (c.missing)
+ return `Missing from model: ${c.name}. Remove it from the configured set to continue.`;
+ if (c.kind === 'parameter') {
+ const p = row.parameters.find((p) => p.entityToken === c.entityToken);
+ if (!p || !p.expression.trim() || p.missing) return `Fill ${row.name} / ${c.name}.`;
+ } else {
+ const f = row.features?.find((f) => f.entityToken === c.entityToken);
+ if (!f || f.missing) return `Fill ${row.name} / ${c.name}.`;
+ }
+ }
+ }
+}
+
+export function tablePayload(draft: TableDraft) {
+ return {
+ newParameters: draft.newParameters?.map(({ name, expression, unit }) => ({
+ name,
+ expression,
+ unit,
+ })),
+ columns: draft.columns.map(({ kind, name, entityToken, unit }) => ({
+ kind,
+ name,
+ entityToken,
+ unit,
+ })),
+ variants: draft.rows.map((row) => ({
+ id: row.id,
+ name: row.name.trim(),
+ parameters: draft.columns.flatMap((c) =>
+ c.kind === 'parameter' ? row.parameters.filter((p) => p.entityToken === c.entityToken) : [],
+ ),
+ features: draft.columns.flatMap((c) =>
+ c.kind === 'feature'
+ ? (row.features ?? []).filter((f) => f.entityToken === c.entityToken)
+ : [],
+ ),
+ })),
+ };
+}
diff --git a/frontend/src/variant-table.tsx b/frontend/src/variant-table.tsx
new file mode 100644
index 0000000..3324710
--- /dev/null
+++ b/frontend/src/variant-table.tsx
@@ -0,0 +1,1011 @@
+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'preact/hooks';
+import { Fragment } from 'preact';
+import { GripVertical, Plus, X, Copy, Trash2 } from 'lucide-preact';
+import {
+ onTimelineSelection,
+ request,
+ type TimelineSelection,
+ type ModelState,
+ type VariantColumn,
+} from './bridge';
+import { VariantParameterTree } from './variant-parameter-tree';
+import { ExpressionEditor } from './editor';
+import { prepareInlineEdit } from './inline-edit';
+import { hasAssignment } from './expression-syntax';
+import type { Parameter } from './bridge';
+import {
+ columnKey,
+ moveItem,
+ newRow,
+ tableDraft,
+ tablePayload,
+ tableProblem,
+ type TableDraft,
+ type TableRow,
+} from './variant-table-state';
+
+type Props = {
+ model: ModelState;
+ create: boolean;
+ disabled: boolean;
+ error?: string;
+ onSave: (payload: Record) => Promise;
+ onClose: () => void;
+};
+type Axis = 'rows' | 'columns';
+type CellEdit = {
+ rowKey: string;
+ token: string;
+ value: string;
+ original: string;
+ wasDirty: boolean;
+};
+type CellPreview = { expression: string; newParameters: Parameter[] };
+
+function unusedName(rows: TableRow[], base = 'Variant') {
+ let name = base,
+ n = 2;
+ while (rows.some((r) => r.name.trim().toLocaleLowerCase() === name.toLocaleLowerCase()))
+ name = `${base} ${n++}`;
+ return name;
+}
+
+export function VariantTable({ model, create, disabled, error, onSave, onClose }: Props) {
+ const [draft, setDraft] = useState(() => {
+ const result = tableDraft(model);
+ if (create) result.rows.push(newRow(model, result.columns, unusedName(result.rows)));
+ return result;
+ });
+ const [dirty, setDirty] = useState(create);
+ const [picker, setPicker] = useState(false);
+ const [filter, setFilter] = useState('');
+ const [renaming, setRenaming] = useState(
+ create ? draft.rows[draft.rows.length - 1]?.key : undefined,
+ );
+ const [confirmClose, setConfirmClose] = useState(false);
+ const [confirmReload, setConfirmReload] = useState(false);
+ const [announcement, setAnnouncement] = useState('');
+ const [deleteKey, setDeleteKey] = useState(null);
+ const [picking, setPicking] = useState(false);
+ const [pickError, setPickError] = useState('');
+ const [editingCell, setEditingState] = useState(null);
+ const editingRef = useRef(null);
+ const [cellError, setCellError] = useState('');
+ const [cellBusy, setCellBusy] = useState(false);
+ const draftRef = useRef(draft);
+ draftRef.current = draft;
+ const cellGeneration = useRef(0);
+ const cellFlight = useRef | null>(null);
+ const originalName = useRef(create ? draft.rows[draft.rows.length - 1]?.name : '');
+ const [dropTarget, setDropTarget] = useState(null);
+ const dialog = useRef(null);
+ const drag = useRef<{
+ axis: Axis;
+ index: number;
+ pointerId: number;
+ x: number;
+ y: number;
+ moved: boolean;
+ target: number | null;
+ } | null>(null);
+ const pickGeneration = useRef(0);
+ const tokens = useRef({
+ variantsToken: model.variantsToken,
+ snapshotToken: model.variantSnapshotToken,
+ });
+ const stale =
+ tokens.current.variantsToken !== model.variantsToken ||
+ tokens.current.snapshotToken !== model.variantSnapshotToken;
+ const unavailable = disabled || stale;
+ const problem = tableProblem(draft);
+ const completionParameters = useMemo(() => {
+ const row = draft.rows.find((r) => r.key === editingCell?.rowKey);
+ return row ? cellParameters(row) : model.parameters;
+ }, [model.parameters, draft.rows, draft.newParameters, editingCell?.rowKey]);
+
+ useEffect(() => {
+ const element = dialog.current!;
+ const target = create
+ ? element.querySelector('[aria-label="Variant name"]')
+ : element.querySelector('[aria-label="Close variant editor"]');
+ (
+ target ?? element.querySelector('[aria-label="Close variant editor"]')
+ )?.focus();
+ return () => {
+ cellGeneration.current++;
+ pickGeneration.current++;
+ };
+ }, []);
+
+ useEffect(() => {
+ if (!picking || unavailable) return;
+ return onTimelineSelection((selection) => addPickedFeatures(selection));
+ }, [picking, unavailable, draft, model.documentId]);
+
+ function addPickedFeatures(selection: TimelineSelection) {
+ if (selection.documentId !== model.documentId || unavailable) return;
+ setDraft((current) => {
+ const added = selection.features.filter(
+ (f) =>
+ !current.columns.some((c) => c.kind === 'feature' && c.entityToken === f.entityToken),
+ );
+ if (!added.length) return current;
+ setDirty(true);
+ setAnnouncement(`Added ${added.map((f) => f.name).join(', ')} to the configured set.`);
+ return {
+ ...current,
+ columns: [
+ ...current.columns,
+ ...added.map((f) => ({
+ kind: 'feature' as const,
+ name: f.name,
+ entityToken: f.entityToken,
+ })),
+ ],
+ rows: current.rows.map((r) => ({
+ ...r,
+ features: [...(r.features ?? []), ...added.map((f) => ({ ...f }))],
+ })),
+ };
+ });
+ }
+ function stopPicking() {
+ pickGeneration.current++;
+ setPicking(false);
+ }
+ async function togglePicking() {
+ const generation = ++pickGeneration.current;
+ if (picking) {
+ stopPicking();
+ return;
+ }
+ setPickError('');
+ setPicking(true);
+ try {
+ const selection = await request(
+ 'variants.selection.get',
+ {},
+ model.documentId!,
+ );
+ if (generation === pickGeneration.current) addPickedFeatures(selection);
+ } catch (error) {
+ if (generation === pickGeneration.current) {
+ setPickError(error instanceof Error ? error.message : String(error));
+ stopPicking();
+ }
+ }
+ }
+ function afterCell(action: (current: TableDraft) => void) {
+ if (!editingRef.current && !cellFlight.current) action(draftRef.current);
+ else
+ void commitCell().then((current) => {
+ if (current) action(current);
+ });
+ }
+ function addVariant() {
+ afterCell((current) => {
+ const added = newRow(model, current.columns, unusedName(current.rows));
+ change({ ...current, rows: [...current.rows, added] });
+ originalName.current = added.name;
+ setRenaming(added.key);
+ });
+ }
+ function duplicateVariant(source: TableRow) {
+ afterCell((current) => {
+ const row = current.rows.find((r) => r.key === source.key);
+ if (!row) return;
+ const added = {
+ ...row,
+ id: undefined,
+ key: crypto.randomUUID(),
+ name: unusedName(current.rows, `${row.name} copy`),
+ parameters: row.parameters.map((p) => ({ ...p })),
+ features: row.features?.map((f) => ({ ...f })),
+ };
+ change({ ...current, rows: [...current.rows, added] });
+ originalName.current = added.name;
+ setRenaming(added.key);
+ });
+ }
+
+ function change(next: TableDraft) {
+ draftRef.current = next;
+ setDraft(next);
+ setDirty(true);
+ }
+ function setEditingCell(next: CellEdit | null) {
+ editingRef.current = next;
+ setEditingState(next);
+ }
+ function cellParameters(row: TableRow): Parameter[] {
+ return [...model.parameters, ...(draft.newParameters ?? [])].map((parameter) => {
+ const cell = row.parameters.find((p) => p.name === parameter.name);
+ return cell
+ ? {
+ ...parameter,
+ expression: cell.expression,
+ value: cell.unit === 'Text' ? cell.value : cell.expression,
+ valueExpression: cell.expression,
+ }
+ : parameter;
+ });
+ }
+ async function commitCell(): Promise {
+ if (cellFlight.current) return cellFlight.current;
+ const edit = editingRef.current;
+ if (!edit) return draftRef.current;
+ if (edit.value === edit.original) {
+ setEditingCell(null);
+ return draftRef.current;
+ }
+ const row = draftRef.current.rows.find((r) => r.key === edit.rowKey);
+ const parameter = row?.parameters.find((p) => p.entityToken === edit.token);
+ if (!row || !parameter) return null;
+ const generation = ++cellGeneration.current;
+ const promise = Promise.resolve().then(async () => {
+ setCellBusy(true);
+ setCellError('');
+ try {
+ const parameters = cellParameters(row);
+ const target = parameters.find((p) => p.name === parameter.name)!;
+ const prepared = prepareInlineEdit(target, edit.value, parameters);
+ const result = await request(
+ 'variants.cell.preview',
+ {
+ target: parameter.name,
+ parameters: row.parameters,
+ text: prepared.text,
+ ...(prepared.equation ? { inlineEquation: prepared.equation } : {}),
+ ...(prepared.sourceValueExpression ? { sourceName: parameter.name } : {}),
+ newParameters: draftRef.current.newParameters,
+ ...tokens.current,
+ },
+ model.documentId!,
+ );
+ if (generation !== cellGeneration.current) return null;
+ const current = draftRef.current;
+ if (
+ !current.rows.some(
+ (r) => r.key === row.key && r.parameters.some((p) => p.entityToken === edit.token),
+ )
+ ) {
+ setEditingCell(null);
+ return current;
+ }
+ const next = {
+ ...current,
+ newParameters: [...(current.newParameters ?? []), ...result.newParameters],
+ rows: current.rows.map((r) =>
+ r.key !== row.key
+ ? r
+ : {
+ ...r,
+ parameters: r.parameters.map((p) =>
+ p.entityToken !== edit.token ? p : { ...p, expression: result.expression },
+ ),
+ },
+ ),
+ };
+ change(next);
+ draftRef.current = next;
+ setEditingCell(null);
+ return next;
+ } catch (error) {
+ if (generation === cellGeneration.current)
+ setCellError(error instanceof Error ? error.message : String(error));
+ return null;
+ } finally {
+ setCellBusy(false);
+ cellFlight.current = null;
+ }
+ });
+ cellFlight.current = promise;
+ return promise;
+ }
+ function close() {
+ if (!disabled) {
+ if (dirty) setConfirmClose(true);
+ else onClose();
+ }
+ }
+ function beginCell(row: TableRow, column: VariantColumn) {
+ const open = (current: TableDraft) => {
+ const parameter = current.rows
+ .find((r) => r.key === row.key)
+ ?.parameters.find((p) => p.entityToken === column.entityToken);
+ if (!parameter) return;
+ setCellError('');
+ setEditingCell({
+ rowKey: row.key,
+ token: column.entityToken,
+ value: parameter.expression,
+ original: parameter.expression,
+ wasDirty: dirty,
+ });
+ };
+ if (editingRef.current || cellFlight.current)
+ void commitCell().then((current) => {
+ if (current) open(current);
+ });
+ else open(draftRef.current);
+ }
+ function reload() {
+ setDraft(tableDraft(model));
+ tokens.current = {
+ variantsToken: model.variantsToken,
+ snapshotToken: model.variantSnapshotToken,
+ };
+ setDirty(false);
+ setConfirmReload(false);
+ setRenaming(undefined);
+ stopPicking();
+ setDeleteKey(null);
+ cellGeneration.current++;
+ setEditingCell(null);
+ setCellError('');
+ }
+ function reorder(axis: Axis, from: number, to: number) {
+ if (unavailable) return;
+ if (axis === 'rows') change({ ...draft, rows: moveItem(draft.rows, from, to) });
+ else change({ ...draft, columns: moveItem(draft.columns, from, to) });
+ setAnnouncement(
+ `${axis === 'rows' ? 'Variant' : 'Parameter or feature'} moved to position ${to + 1}.`,
+ );
+ }
+ useLayoutEffect(() => {
+ function cancelDrag() {
+ drag.current = null;
+ setDropTarget(null);
+ }
+ function track(event: PointerEvent) {
+ const source = drag.current;
+ if (!source || source.pointerId !== event.pointerId || unavailable) return;
+ if (Math.hypot(event.clientX - source.x, event.clientY - source.y) < 4 && !source.moved)
+ return;
+ source.moved = true;
+ event.preventDefault();
+ const scroller = dialog.current?.querySelector('.variant-table-scroll');
+ if (scroller) {
+ const bounds = scroller.getBoundingClientRect();
+ if (source.axis === 'columns') {
+ if (event.clientX > bounds.right - 28) scroller.scrollLeft += 24;
+ else if (event.clientX < bounds.left + 28) scroller.scrollLeft -= 24;
+ } else {
+ if (event.clientY > bounds.bottom - 28) scroller.scrollTop += 24;
+ else if (event.clientY < bounds.top + 28) scroller.scrollTop -= 24;
+ }
+ }
+ // Pointer capture retargets events to the handle. Hit-test the actual position instead.
+ const hit = document.elementFromPoint(event.clientX, event.clientY);
+ const target = hit?.closest(`[data-reorder-${source.axis}]`);
+ source.target =
+ target && dialog.current?.contains(target)
+ ? Number(target.getAttribute(`data-reorder-${source.axis}`))
+ : null;
+ setDropTarget(source.target === null ? null : `${source.axis}:${source.target}`);
+ }
+ function finish(event: PointerEvent) {
+ const source = drag.current;
+ if (!source || source.pointerId !== event.pointerId) return;
+ track(event);
+ cancelDrag();
+ if (source.moved && source.target !== null && !unavailable)
+ reorder(source.axis, source.index, source.target);
+ }
+ function escape(event: KeyboardEvent) {
+ if (event.key === 'Escape' && drag.current) {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ cancelDrag();
+ }
+ }
+ window.addEventListener('pointermove', track, { passive: false });
+ window.addEventListener('pointerup', finish);
+ window.addEventListener('pointercancel', cancelDrag);
+ window.addEventListener('lostpointercapture', cancelDrag);
+ window.addEventListener('blur', cancelDrag);
+ window.addEventListener('keydown', escape, true);
+ return () => {
+ window.removeEventListener('pointermove', track);
+ window.removeEventListener('pointerup', finish);
+ window.removeEventListener('pointercancel', cancelDrag);
+ window.removeEventListener('lostpointercapture', cancelDrag);
+ window.removeEventListener('blur', cancelDrag);
+ window.removeEventListener('keydown', escape, true);
+ drag.current = null;
+ };
+ }, [unavailable, draft]);
+ function dropProps(axis: Axis, index: number) {
+ return {
+ [`data-reorder-${axis}`]: index,
+ class: dropTarget === `${axis}:${index}` ? 'table-drop-target' : '',
+ };
+ }
+ function handle(axis: Axis, index: number, name: string) {
+ return (
+
+ );
+ }
+ function cell(r: TableRow, column: VariantColumn) {
+ const parameter = r.parameters.find((p) => p.entityToken === column.entityToken);
+ const feature = r.features?.find((f) => f.entityToken === column.entityToken);
+ const missingCell = column.kind === 'parameter' ? !parameter : !feature;
+ return (
+