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: -![Cedar & Sage feeder in Autodesk Fusion with the installed Paramood palette and Classic variant](assets/screenshots/fusion-classic.jpg) +

Paramood 2.0 palette with a parameter completion and calculator result

-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 Hybrid view showing grouped parameters and a 90 mm calculator result Paramood menu showing Free and the saved Classic, Compact, and Garden variants +![Paramood 2.0 wide palette with calculator and parameter tree side by side](assets/screenshots/v2-review/palette-wide.jpg) -## 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. +

Paramood 2.0 preview of two parameter changes before applying

+ +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: + +

+ Paramood 2.0 variant selector + Paramood 2.0 variant table showing Compact dimensions +

+ +The Compact configuration of the Cedar & Sage review model: + +![Cedar & Sage Compact model in Fusion](assets/screenshots/v2-review/compact.png) + +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 подсказывает параметры модели при вводе, а калькулятор использует их текущие значения: -![Кормушка Cedar & Sage в Autodesk Fusion с установленной палитрой Paramood и вариантом Classic](assets/screenshots/fusion-classic.jpg) +

Палитра Paramood 2.0 с подсказкой параметра и результатом вычисления

-Ввод закреплён под списком, результаты открываются над ним. Меню переключает три конфигурации, сохранённые в примере. +В широкой палитре вид Calculator располагает поле и результат рядом с деревом параметров: -Вид Hybrid в Paramood: группы параметров и результат вычисления 90 mm Меню Paramood: Free и сохранённые варианты Classic, Compact и Garden +![Широкая палитра Paramood 2.0 с калькулятором и деревом параметров](assets/screenshots/v2-review/palette-wide.jpg) -## Возможности Paramood 1.5.0 +Введи несколько присваиваний, чтобы увидеть текущие и предлагаемые значения до применения. В этом примере показан предпросмотр изменений варианта Compact; значения ещё не применены: -Обзор описывает исходный код v1.5.0. На [странице Releases](https://github.com/4FusionLab/Paramood/releases) перечислены опубликованные сборки; доступные в установленной версии функции сверяй с примечаниями к её релизу. +

Предпросмотр двух изменений параметров в Paramood 2.0 до применения

+ +Переключай сохранённые варианты в шапке или открывай таблицу, чтобы сравнивать и редактировать выражения параметров и состояния поддерживаемых фич. Ширина лотка **Compact** — 120 мм; остальные столбцы доступны горизонтальной прокруткой: + +

+ Меню выбора варианта Paramood 2.0 + Таблица вариантов Paramood 2.0 с размерами Compact +

+ +Вариант Compact проверочной модели Cedar & Sage: + +![Модель Cedar & Sage Compact во Fusion](assets/screenshots/v2-review/compact.png) + +Снимки сделаны в проверочной сборке 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. + +![Classic model](../assets/screenshots/v2-review/classic.png) + +![Compact model](../assets/screenshots/v2-review/compact.png) + +![Garden model](../assets/screenshots/v2-review/garden.png) + +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 ещё не завершены. + +![Модель Classic](../assets/screenshots/v2-review/classic.png) + +![Модель Compact](../assets/screenshots/v2-review/compact.png) + +![Модель Garden](../assets/screenshots/v2-review/garden.png) + +Это снимки области модели 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 ( + + {column.missing || parameter?.missing || feature?.missing ? ( + Missing from model + ) : missingCell ? ( + Unavailable + ) : column.kind === 'parameter' ? ( + editingCell?.rowKey === r.key && editingCell.token === column.entityToken ? ( + { + setEditingCell({ ...editingCell, value }); + setDirty(true); + setCellError(''); + }} + onSubmit={() => void commitCell()} + onBlur={() => void commitCell()} + onCancel={() => { + cellGeneration.current++; + setDirty(editingCell.wasDirty); + setEditingCell(null); + setCellError(''); + }} + /> + ) : ( + + ) + ) : ( + { + const enabled = event.currentTarget.checked; + change({ + ...draft, + rows: draft.rows.map((item) => + item.key !== r.key + ? item + : { + ...item, + features: item.features!.map((f) => + f.entityToken === column.entityToken ? { ...f, enabled } : f, + ), + }, + ), + }); + }} + /> + )} + + ); + } + function variantHeader(r: TableRow, index: number) { + return ( +
+ {renaming === r.key ? ( + { + if (element && document.activeElement !== element) { + element.focus(); + element.select(); + } + }} + onInput={(event) => { + const name = event.currentTarget.value; + change({ + ...draft, + rows: draft.rows.map((row) => (row.key === r.key ? { ...row, name } : row)), + }); + }} + onBlur={() => setRenaming(undefined)} + onKeyDown={(event) => { + if (event.key === 'Enter') { + event.preventDefault(); + event.stopPropagation(); + setRenaming(undefined); + } + if (event.key === 'Escape') { + event.preventDefault(); + event.stopPropagation(); + change({ + ...draft, + rows: draft.rows.map((row) => + row.key === r.key ? { ...row, name: originalName.current } : row, + ), + }); + setRenaming(undefined); + } + }} + /> + ) : ( + + )} + {r.id && r.id === model.activeVariantId && ( + Active + )} +
+ {handle('rows', index, r.name)} + + +
+
+ ); + } + function columnHeader(column: VariantColumn, index: number) { + return ( +
+ {handle('columns', index, column.name)} + + {column.name.split('_').map((part, index) => ( + + {index > 0 && ( + <> + . + + )} + {part} + + ))} + {column.kind === 'feature' ? 'Enabled' : column.unit || 'Unitless'} + +
+ ); + } + function toggleColumn(column: VariantColumn, selected: boolean) { + if (selected) { + const existing = draft.columns.find((c) => columnKey(c) === columnKey(column)); + if (existing) return; + change({ + ...draft, + columns: [...draft.columns, column], + rows: draft.rows.map((r) => { + const current = newRow(model, [column], r.name); + return { + ...r, + parameters: [...r.parameters, ...current.parameters], + features: [...(r.features ?? []), ...(current.features ?? [])], + }; + }), + }); + } else + change({ + ...draft, + columns: draft.columns.filter((c) => columnKey(c) !== columnKey(column)), + rows: draft.rows.map((r) => ({ + ...r, + parameters: + column.kind === 'parameter' + ? r.parameters.filter((p) => p.entityToken !== column.entityToken) + : r.parameters, + features: + column.kind === 'feature' + ? r.features?.filter((f) => f.entityToken !== column.entityToken) + : r.features, + })), + }); + } + const editable = model.parameters + .filter((p) => !p.driven && p.entityToken) + .map((p) => ({ ...p, entityToken: p.entityToken! })); + const pickerRows = editable.filter((p) => + p.name.toLocaleLowerCase().includes(filter.replaceAll('.', '_').toLocaleLowerCase()), + ); + const selected = draft.columns + .filter((c) => c.kind === 'parameter') + .map((c) => ({ + name: c.name, + entityToken: c.entityToken, + unit: c.unit ?? '', + expression: '', + value: 0, + missing: c.missing, + })); + const missing = draft.columns.filter((c) => c.missing); + + return ( +
+ +
+ ); +} diff --git a/frontend/src/variants.test.tsx b/frontend/src/variants.test.tsx index 4457666..dafb16e 100644 --- a/frontend/src/variants.test.tsx +++ b/frontend/src/variants.test.tsx @@ -1,16 +1,19 @@ // @vitest-environment jsdom import { afterEach, describe, expect, it, vi } from 'vitest'; import { render } from 'preact'; -import { act } from 'preact/test-utils'; import { EditorView } from '@codemirror/view'; import { currentCompletions, startCompletion } from '@codemirror/autocomplete'; +import { act } from 'preact/test-utils'; import { VariantsControl } from './variants'; import type { ModelState } from './bridge'; +import { ParameterList } from './parameter-list'; let host: HTMLDivElement; afterEach(() => { if (host) act(() => render(null, host)); document.body.innerHTML = ''; + vi.restoreAllMocks(); + delete window.adsk; }); const parameter = { name: 'width', @@ -18,369 +21,522 @@ const parameter = { unit: 'mm', value: '10 mm', entityToken: 'width-token', + configured: true, +}; +const saved = { + id: 'compact', + name: 'Compact', + parameters: [{ ...parameter, value: 1 }], + features: [{ name: 'Cut', entityToken: 'cut', enabled: true }], }; const model: ModelState = { documentId: 'model', parameters: [ parameter, - { ...parameter, name: 'height', entityToken: 'height-token' }, + { ...parameter, name: 'height', entityToken: 'height-token', configured: false }, { ...parameter, name: 'driven', driven: true }, ], - variants: [], + variants: [saved], + variantColumns: [ + { kind: 'parameter', name: 'width', entityToken: 'width-token', unit: 'mm' }, + { kind: 'feature', name: 'Cut', entityToken: 'cut' }, + ], + timelineFeatures: [{ name: 'Cut', entityToken: 'cut', enabled: true }], variantsToken: 'storage', variantSnapshotToken: 'snapshot', activeVariantId: null, }; -function mount(state = model, onAction = vi.fn().mockResolvedValue(true), disabled = false) { +function mount(state = model, onAction = vi.fn().mockResolvedValue(true)) { + // jsdom has no pointer event properties; Preact otherwise preserves an unsupported event's case. + if (!('onpointerdown' in HTMLElement.prototype)) + Object.defineProperty(HTMLElement.prototype, 'onpointerdown', { + configurable: true, + value: null, + }); if (!Range.prototype.getClientRects) Range.prototype.getClientRects = () => [] as unknown as DOMRectList; if (!Range.prototype.getBoundingClientRect) Range.prototype.getBoundingClientRect = () => new DOMRect(); + if (!window.adsk) + window.adsk = { + fusionSendData: (_action, raw) => { + const message = JSON.parse(raw), + text = message.payload.text as string; + window.fusionJavaScriptHandler!.handle( + 'response', + JSON.stringify({ + requestId: message.requestId, + ok: true, + documentId: state.documentId, + data: { expression: text?.slice(text.indexOf('=') + 1).trim(), newParameters: [] }, + }), + ); + }, + }; host = document.createElement('div'); document.body.appendChild(host); - act(() => - render(, host), - ); + act(() => render(, host)); return onAction; } function click(label: string) { - const button = Array.from(host.querySelectorAll('button')).find( - (item) => item.getAttribute('aria-label') === label || item.textContent?.trim() === label, + const b = Array.from(host.querySelectorAll('button')).find( + (b) => b.getAttribute('aria-label') === label || b.textContent?.trim() === label, ); - expect(button, label).toBeTruthy(); - act(() => button!.click()); + expect(b, label).toBeTruthy(); + act(() => b!.click()); } function input(label: string, value: string) { - const element = host.querySelector(`[aria-label="${label}"]`)!; + let e = host.querySelector(`[aria-label="${label}"]`)!; + expect(e, label).toBeTruthy(); + if (e.matches('button.variant-cell-value')) { + act(() => e.click()); + e = host.querySelector(`[aria-label="${label}"]`)!; + } act(() => { - if (element.matches('.cm-content')) { - const editor = EditorView.findFromDOM(element)!; - editor.dispatch({ - changes: { from: 0, to: editor.state.doc.length, insert: value }, + if (e.matches('.cm-content')) { + const view = EditorView.findFromDOM(e)!; + view.dispatch({ + changes: { from: 0, to: view.state.doc.length, insert: value }, selection: { anchor: value.length }, }); } else { - element.value = value; - element.dispatchEvent(new Event('input', { bubbles: true })); + const field = e as HTMLInputElement; + field.value = value; + field.dispatchEvent(new Event('input', { bubbles: true })); } }); } -function name(value: string) { - const element = host.querySelector('#variant-name')!; - act(() => { - element.value = value; - element.dispatchEvent(new Event('input', { bubbles: true })); - }); +function cellValue(label: string) { + const e = host.querySelector(`[aria-label="${label}"]`)!; + return e.matches('.cm-content') ? EditorView.findFromDOM(e)!.state.doc.toString() : e.textContent; } -function create() { + +function open() { click('Variants: Free'); - click('Create variant'); + click('Edit variants'); +} +function checkbox(label: string) { + const e = host.querySelector(`[aria-label="${label}"]`)!; + expect(e, label).toBeTruthy(); + act(() => e.click()); +} +async function save() { + click('Save'); + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)); + }); } -const saved = { - id: 'compact', - name: 'Compact', - parameters: [ - { name: 'width', entityToken: 'width-token', expression: '10 mm', unit: 'mm', value: 1 }, - ], -}; -describe('variants workflow', () => { - it('starts in Free and exposes a useful empty state', () => { +describe('global variant table', () => { + it('shows shared counts and one table editor entry in the switcher header', () => { mount(); click('Variants: Free'); - expect(host.textContent).toContain('Save parameter values'); - expect(host.textContent).toContain('Create variant'); + const heading = host.querySelector('.variant-menu-heading')!; + expect(heading.textContent).toContain('1 parameter · 1 feature'); + expect(heading.querySelector('[aria-label="Edit variants"]')).toBeTruthy(); + const options = host.querySelector('.variant-options')!; + expect(options.querySelector('.icon')).toBeNull(); + expect(options.textContent).not.toContain('parameter'); + click('Edit variants'); + expect(host.querySelector('[role="dialog"]')).toBeTruthy(); }); - it('creates a variant from selected parameters and values with captured document tokens', async () => { - const action = mount(); - create(); - name('Compact'); - expect(host.querySelector('[aria-label="Include driven"]')).toBeNull(); - click('Save & apply'); - expect(action).not.toHaveBeenCalled(); - act(() => host.querySelector('[aria-label="Include width"]')!.click()); - input('Value for width', '25 mm'); - click('Save & apply'); + it('uses shared IntelliSense, this and function completions inside a table cell', async () => { + mount(); + open(); + input('Compact / width', ''); + const view = EditorView.findFromDOM(host.querySelector('.cm-content')!)!; + act(() => { + startCompletion(view); + }); await vi.waitFor(() => - expect(action).toHaveBeenCalledWith( - 'variants.save', - expect.objectContaining({ - name: 'Compact', - variantsToken: 'storage', - snapshotToken: 'snapshot', - parameters: [ - expect.objectContaining({ - name: 'width', - expression: '25 mm', - entityToken: 'width-token', - }), - ], - }), - ), + expect(currentCompletions(view.state).map((c) => c.label)).toContain('this'), ); - await vi.waitFor(() => expect(host.querySelector('[role="dialog"]')).toBeNull()); + expect(currentCompletions(view.state).map((c) => c.label)).toContain('random'); + input('Compact / width', 'sin(30 deg)'); + expect(host.querySelector('.token-function')?.textContent).toBe('sin'); + expect(host.querySelector('.variant-table-scroll .cm-tooltip')).toBeNull(); }); - it('removes membership without sending a model deletion', async () => { - const action = mount({ ...model, variants: [saved] }); - click('Variants: Free'); - click('Edit Compact'); - act(() => host.querySelector('[aria-label="Include width"]')!.click()); - act(() => host.querySelector('[aria-label="Include height"]')!.click()); - click('Save & apply'); - await vi.waitFor(() => - expect(action).toHaveBeenCalledWith( - 'variants.save', - expect.objectContaining({ parameters: [expect.objectContaining({ name: 'height' })] }), - ), - ); + it('keeps newly linked global parameters in the draft and sends them only on Save', async () => { + window.adsk = { + fusionSendData: (_action, raw) => { + const message = JSON.parse(raw); + window.fusionJavaScriptHandler!.handle( + 'response', + JSON.stringify({ + requestId: message.requestId, + ok: true, + documentId: 'model', + data: { + expression: 'beam', + newParameters: [{ name: 'beam', expression: '25 mm', unit: 'mm', value: 25 }], + }, + }), + ); + }, + }; + const action = mount(); + open(); + input('Compact / width', 'beam=25'); + await save(); + expect(action.mock.calls[0][1].newParameters).toEqual([ + { name: 'beam', expression: '25 mm', unit: 'mm' }, + ]); + expect(action.mock.calls[0][1].columns.map((c: { name: string }) => c.name)).toEqual([ + 'width', + 'Cut', + ]); + expect(action.mock.calls[0][1].variants[0].parameters[0].expression).toBe('beam'); }); - it('filters parameters while preserving selected values', () => { + it('duplicates the committed cell draft without losing the action during editor blur', async () => { mount(); - create(); - act(() => host.querySelector('[aria-label="Include width"]')!.click()); - input('Value for width', '30 mm'); - input('Find parameters for variant', 'height'); - expect(host.querySelector('[aria-label="Include width"]')).toBeNull(); - input('Find parameters for variant', ''); - expect(host.querySelector('[aria-label="Value for width"]')!.value).toBe( - '30 mm', - ); + open(); + input('Compact / width', '35 mm'); + click('Duplicate Compact'); + await vi.waitFor(() => expect(host.querySelector('[aria-label="Variant name"]')).toBeTruthy()); + expect(cellValue('Compact / width')).toBe('35 mm'); + expect(cellValue('Compact copy / width')).toBe('35 mm'); }); - it('switches and returns to Free without resetting parameter values', async () => { - const action = mount({ ...model, variants: [saved], activeVariantId: saved.id }); - click('Variants: Compact'); - click('FreeEdit without updating a variant'); - await vi.waitFor(() => - expect(action).toHaveBeenCalledWith( - 'variants.free', - expect.objectContaining({ snapshotToken: 'snapshot' }), - ), + it('keeps variants as rows at any width and appends Add variant as the last row', () => { + mount(); + open(); + expect(host.querySelector('thead th')?.textContent).toBe('Variant'); + expect(host.querySelector('tbody tr:last-child')?.textContent).toContain('Add variant'); + click('Add variant'); + input('Variant name', 'Garden'); + expect( + host.querySelector('[aria-label="Garden / width"]')?.closest('tr')?.querySelector('th'), + ).toBeTruthy(); + expect(host.querySelector('tbody tr:last-child')?.textContent).toContain('Add variant'); + }); + it('renames in place and confirms deletion next to the row without writing before Save', async () => { + const action = mount(); + open(); + click('Rename Compact'); + input('Variant name', 'Garden'); + click('Delete Garden'); + expect(host.textContent).toContain('Model parameters and features will stay'); + click('Keep variant'); + expect(host.querySelector('[aria-label="Garden / width"]')).toBeTruthy(); + click('Delete Garden'); + click('Delete variant'); + expect(action).not.toHaveBeenCalled(); + expect(host.querySelector('[aria-label="Garden / width"]')).toBeNull(); + await save(); + expect(action.mock.calls[0][1].variants).toEqual([]); + }); + it('adds picked timeline features to every draft row only while picking the same document', async () => { + window.adsk = { + fusionSendData: (_action, raw) => { + const request = JSON.parse(raw); + window.fusionJavaScriptHandler!.handle( + 'response', + JSON.stringify({ + requestId: request.requestId, + ok: true, + documentId: 'model', + data: { documentId: 'model', features: [] }, + }), + ); + }, + }; + const action = mount(); + open(); + click('Configure · 2'); + click('Pick from timeline'); + await vi.waitFor(() => expect(host.textContent).toContain('Done picking')); + const emit = (documentId: string, name = 'Fillet') => + act(() => { + window.fusionJavaScriptHandler!.handle( + 'variants.selection', + JSON.stringify({ documentId, features: [{ name, entityToken: name, enabled: false }] }), + ); + }); + emit('other'); + expect(host.querySelector('[aria-label="Compact / Fillet enabled"]')).toBeNull(); + emit('model'); + emit('model'); + expect(host.querySelectorAll('[aria-label="Compact / Fillet enabled"]')).toHaveLength(1); + expect( + host.querySelector('[aria-label="Compact / Fillet enabled"]')!.checked, + ).toBe(false); + click('Done picking'); + emit('model', 'Extrude'); + expect(host.querySelector('[aria-label="Compact / Extrude enabled"]')).toBeNull(); + expect(action).not.toHaveBeenCalled(); + await save(); + expect(action.mock.calls[0][1].columns).toHaveLength(3); + }); + it('saves all rows without applying or changing the switcher contract', async () => { + const action = mount(); + open(); + input('Compact / width', '25 mm'); + await save(); + expect(action).toHaveBeenCalledWith( + 'variants.table.save', + expect.objectContaining({ + variantsToken: 'storage', + snapshotToken: 'snapshot', + columns: model.variantColumns, + variants: [ + expect.objectContaining({ + id: 'compact', + parameters: [expect.objectContaining({ expression: '25 mm' })], + }), + ], + }), ); + expect(action).not.toHaveBeenCalledWith('variants.apply', expect.anything()); }); - it('disables duplicate names and missing parameters but lets users repair membership', () => { - mount({ + it('selects the parameter set globally and initializes every row from current values', async () => { + const action = mount({ ...model, - variants: [ - saved, - { - ...saved, - id: 'missing', - name: 'Missing', - parameters: [{ ...saved.parameters[0], missing: true }], - }, - ], + variants: [saved, { ...saved, id: 'garden', name: 'Garden' }], }); - create(); - name('compact'); - expect(host.textContent).toContain('already exists'); - click('Cancel'); + open(); + click('Configure · 2'); + expect(host.querySelector('[aria-label="Include driven"]')).toBeNull(); + checkbox('Include height'); + await save(); + const payload = action.mock.calls[0][1]; + expect(payload.columns.map((c: { name: string }) => c.name)).toEqual([ + 'width', + 'Cut', + 'height', + ]); + expect( + payload.variants.every((r: { parameters: { name: string }[] }) => + r.parameters.some((p) => p.name === 'height'), + ), + ).toBe(true); + }); + it('treats a checked feature as enabled and unchecked as suppressed', async () => { + const action = mount(); + open(); + expect( + host.querySelector('[aria-label="Compact / Cut enabled"]')!.checked, + ).toBe(true); + checkbox('Compact / Cut enabled'); + await save(); + expect(action.mock.calls[0][1].variants[0].features[0].enabled).toBe(false); + }); + it('removes a member from every row without deleting anything from the model', async () => { + const action = mount(); + open(); + click('Configure · 2'); + checkbox('Include width'); + await save(); + expect(action.mock.calls[0][1].columns.map((c: { kind: string }) => c.kind)).toEqual([ + 'feature', + ]); + expect(action.mock.calls[0][1].variants[0].parameters).toEqual([]); + }); + it('creates and duplicates rows with editable names and no per-variant membership selector', async () => { + const action = mount(); click('Variants: Free'); - click('Edit Missing'); - expect(host.textContent).toContain('Missing from model'); - act(() => host.querySelector('[aria-label="Include width"]')!.click()); - expect(host.textContent).not.toContain('Missing from model'); + click('Create variant'); + input('Variant name', 'Garden'); + expect(host.querySelector('[aria-label="Garden / width"]')).toBeTruthy(); + click('Duplicate Garden'); + input('Variant name', 'Patio'); + await save(); + expect(action).toHaveBeenCalledTimes(1); + expect(action.mock.calls[0][1].variants.map((r: { name: string }) => r.name)).toEqual([ + 'Compact', + 'Garden', + 'Patio', + ]); }); - it('retains draft when the backend rejects a save', async () => { + it('blocks duplicate names and preserves a rejected draft', async () => { const action = mount(model, vi.fn().mockResolvedValue(false)); - create(); - name('Compact'); - act(() => host.querySelector('[aria-label="Include width"]')!.click()); - input('Value for width', 'bad expression'); - click('Save & apply'); - await vi.waitFor(() => expect(action).toHaveBeenCalled()); - expect(host.querySelector('[aria-label="Value for width"]')!.value).toBe( - 'bad expression', + open(); + click('Duplicate Compact'); + input('Variant name', 'Compact'); + expect(host.textContent).toContain('names must be unique'); + expect(host.querySelector('.variant-dialog-footer .primary')!.disabled).toBe( + true, ); + input('Variant name', 'Garden'); + input('Garden / width', 'bad expression'); + await save(); + expect(action).toHaveBeenCalled(); + expect(cellValue('Garden / width')).toBe('bad expression'); + }); + it('requires explicit discard before closing a dirty table', () => { + mount(); + open(); + input('Compact / width', '40 mm'); + click('Cancel'); + expect(host.textContent).toContain('Discard unsaved table'); + click('Keep editing'); expect(host.querySelector('[role="dialog"]')).toBeTruthy(); + click('Cancel'); + click('Discard changes'); + expect(host.querySelector('[role="dialog"]')).toBeNull(); }); - it('confirms deleting a variant while preserving the model', async () => { - const action = mount({ ...model, variants: [saved] }); - click('Variants: Free'); - click('Edit Compact'); - click('Delete variant'); - expect(action).not.toHaveBeenCalled(); - expect(host.textContent).toContain('Model parameters will stay'); - click('Delete variant'); - await vi.waitFor(() => - expect(action).toHaveBeenCalledWith( - 'variants.delete', - expect.objectContaining({ id: saved.id }), + it('preserves the draft across stale model refreshes until the user confirms replacement', () => { + const action = mount(); + open(); + input('Compact / width', '40 mm'); + act(() => + render( + , + host, ), ); + expect(cellValue('Compact / width')).toBe('40 mm'); + click('Reload from model'); + click('Keep editing'); + expect(host.textContent).toContain('draft is preserved'); + click('Reload from model'); + click('Replace draft'); + expect(cellValue('Compact / width')).toBe('10 mm'); }); - it('supports Escape, focus restoration and a trapped dialog tab order', async () => { - mount(); - create(); - await vi.waitFor(() => expect(document.activeElement?.id).toBe('variant-name')); - const dialog = host.querySelector('[role="dialog"]')!; - const close = dialog.querySelector('[aria-label="Close variant editor"]')!; - act(() => { - close.focus(); - close.dispatchEvent( - new KeyboardEvent('keydown', { key: 'Tab', shiftKey: true, bubbles: true }), - ); - }); - expect(document.activeElement?.textContent).toBe('Cancel'); - act(() => { - dialog.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); + it('reorders both axes with keyboard handles and keeps cell identities intact', async () => { + const action = mount({ + ...model, + variants: [saved, { ...saved, id: 'garden', name: 'Garden' }], }); - expect(host.querySelector('[role="dialog"]')).toBeNull(); - expect(document.activeElement?.getAttribute('aria-label')).toBe('Variants: Free'); - }); - it('disables variants when storage cannot be safely read', () => { - mount({ ...model, variantsError: 'Cannot read saved variants.' }); - expect(host.querySelector('.variant-trigger')!.disabled).toBe(true); + open(); + for (const name of ['Compact', 'width']) { + const handle = host.querySelector(`[aria-label="Reorder ${name}"]`)!; + act(() => { + handle.dispatchEvent( + new KeyboardEvent('keydown', { key: 'ArrowRight', altKey: true, bubbles: true }), + ); + }); + } + await save(); + const payload = action.mock.calls[0][1]; + expect(payload.variants.map((r: { name: string }) => r.name)).toEqual(['Garden', 'Compact']); + expect(payload.columns.map((c: { name: string }) => c.name)).toEqual(['Cut', 'width']); + expect(payload.variants[0].parameters[0].entityToken).toBe('width-token'); }); -}); - -describe('variant parameter hierarchy', () => { - it('selects a parent value and child independently without losing either on collapse', () => { - mount({ + it('reorders rows and columns with pointer gestures when native HTML drag events are unavailable', async () => { + const action = mount({ ...model, - parameters: [ - { ...parameter, name: 'post', unit: '', expression: '4', value: '4', entityToken: 'post' }, - { ...parameter, name: 'post_height', entityToken: 'post-height' }, - ], + variants: [saved, { ...saved, id: 'garden', name: 'Garden' }], }); - create(); - act(() => host.querySelector('[aria-label="Include post"]')!.click()); - input('Value for post', '6'); - expect(host.querySelector('[aria-label="Include post_height"]')).toBeTruthy(); - act(() => host.querySelector('[aria-label="Include post_height"]')!.click()); - input('Value for post_height', '120 mm'); - click('Collapse post'); - expect(host.querySelector('[aria-label="Value for post"]')!.value).toBe('6'); - act(() => host.querySelector('[aria-label="Include post"]')!.click()); - click('Expand post'); - expect( - host.querySelector('[aria-label="Include post_height"]')!.checked, - ).toBe(true); - expect( - host.querySelector('[aria-label="Value for post_height"]')!.value, - ).toBe('120 mm'); - expect(host.querySelector('[aria-label="Include post"]')!.checked).toBe( - false, - ); + open(); + const pointer = (type: string, x: number, y: number) => + new MouseEvent(type, { bubbles: true, cancelable: true, button: 0, clientX: x, clientY: y }); + for (const [source, destination] of [ + ['Compact', 'Garden'], + ['width', 'Cut'], + ]) { + const handle = host.querySelector(`[aria-label="Reorder ${source}"]`)!; + const target = host.querySelector(`[aria-label="Reorder ${destination}"]`)!; + Object.defineProperty(document, 'elementFromPoint', { + configurable: true, + value: () => target, + }); + act(() => { + handle.dispatchEvent(pointer('pointerdown', 20, 20)); + }); + act(() => { + window.dispatchEvent(pointer('pointermove', 60, 60)); + }); + act(() => { + window.dispatchEvent(pointer('pointerup', 60, 60)); + }); + } + expect(host.querySelector('[data-reorder-rows="0"]')?.textContent).toContain('Garden'); + await save(); + expect(action).toHaveBeenCalledTimes(1); + expect(action.mock.calls[0][1].variants.map((r: { name: string }) => r.name)).toEqual([ + 'Garden', + 'Compact', + ]); + expect(action.mock.calls[0][1].columns.map((c: { name: string }) => c.name)).toEqual([ + 'Cut', + 'width', + ]); + expect(action.mock.calls[0][1].variants[0].parameters[0].entityToken).toBe('width-token'); }); - const treeModel: ModelState = { - ...model, - parameters: [ - { ...parameter, name: 'box_inner_width', entityToken: 'inner' }, - { ...parameter, name: 'box_height', entityToken: 'height' }, - { ...parameter, name: 'd10', entityToken: 'd10', kind: 'model' }, - ], - }; - it('uses nested underscore groups and a separate Model parameters section', () => { - mount(treeModel); - create(); - expect(host.querySelector('[aria-label="Include box_inner_width"]')).toBeNull(); - click('Expand box'); - click('Expand box.inner'); - expect(host.querySelector('[aria-label="Include box_inner_width"]')).toBeTruthy(); - expect(host.querySelector('[aria-label="Include d10"]')).toBeNull(); - click('Model parameters'); - expect(host.querySelector('[aria-label="Include d10"]')).toBeTruthy(); - click('Collapse all groups'); - expect(host.querySelector('[aria-label="Include box_inner_width"]')).toBeNull(); - click('Expand all groups'); - expect(host.querySelector('[aria-label="Include box_inner_width"]')).toBeTruthy(); + it('cancels pointer reorder on Escape, pointer cancellation, or release outside the table', () => { + mount({ ...model, variants: [saved, { ...saved, id: 'garden', name: 'Garden' }] }); + open(); + const pointer = (type: string, x: number) => + new MouseEvent(type, { bubbles: true, cancelable: true, button: 0, clientX: x, clientY: 20 }); + const handle = host.querySelector('[aria-label="Reorder Compact"]')!; + const target = host.querySelector('[aria-label="Reorder Garden"]')!; + for (const cancel of ['Escape', 'pointercancel', 'outside']) { + Object.defineProperty(document, 'elementFromPoint', { + configurable: true, + value: () => target, + }); + act(() => { + handle.dispatchEvent(pointer('pointerdown', 20)); + }); + act(() => { + window.dispatchEvent(pointer('pointermove', 60)); + }); + act(() => { + if (cancel === 'outside') + Object.defineProperty(document, 'elementFromPoint', { + configurable: true, + value: () => null, + }); + else if (cancel === 'Escape') + window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); + else window.dispatchEvent(pointer('pointercancel', 60)); + window.dispatchEvent(pointer('pointerup', 60)); + }); + expect(host.querySelector('[data-reorder-rows="0"]')?.textContent).toContain('Compact'); + expect(host.textContent).toContain('All changes saved'); + expect(host.querySelector('.table-drop-target')).toBeNull(); + expect(host.querySelector('[role="dialog"]')).toBeTruthy(); + } }); - it('opens matching ancestors during search and preserves selection after clearing it', () => { - mount(treeModel); - create(); - input('Find parameters for variant', 'inner_width'); - expect(host.querySelector('[aria-label="Include box_inner_width"]')).toBeTruthy(); - expect(host.querySelector('[aria-label="Include box_height"]')).toBeNull(); - expect(host.textContent).toContain('box'); + it('ignores foreign HTML drops without changing the draft', () => { + mount({ ...model, variants: [saved, { ...saved, id: 'garden', name: 'Garden' }] }); + open(); + const target = host.querySelector('[aria-label="Reorder Garden"]')!.closest('th')!; act(() => { - host.querySelector('[aria-label="Include box_inner_width"]')!.click(); + target.dispatchEvent(new Event('drop', { bubbles: true, cancelable: true })); }); - input('Value for box_inner_width', '15 mm'); - input('Find parameters for variant', ''); - expect( - host.querySelector('[aria-label="Value for box_inner_width"]')!.value, - ).toBe('15 mm'); + expect(host.textContent).toContain('All changes saved'); }); -}); - -describe('smart variant search', () => { - const searchModel: ModelState = { - ...model, - parameters: [ - { ...parameter, name: 'box_width', entityToken: 'box-width' }, - { ...parameter, name: 'box_height', entityToken: 'box-height' }, - ], - }; - it('selects and assigns a dotted path immediately without applying to Fusion', async () => { - const action = mount(searchModel); - create(); - input('Find parameters for variant', 'box.width=30'); - expect(host.querySelector('[aria-label="Include box_width"]')!.checked).toBe( - true, - ); - expect(host.querySelector('[aria-label="Value for box_width"]')!.value).toBe( - '30 mm', - ); - expect(action).not.toHaveBeenCalled(); - input('Find parameters for variant', 'box.width=40'); - expect(host.querySelector('[aria-label="Value for box_width"]')!.value).toBe( - '40 mm', - ); - expect(host.textContent).toContain('1 selected'); - input('Find parameters for variant', ''); - expect(host.querySelector('[aria-label="Value for box_width"]')!.value).toBe( - '40 mm', - ); - name('Smart'); - click('Save & apply'); + it('uses the original apply and Free actions when switching', async () => { + const action = mount(); + click('Variants: Free'); + click('Compact'); await vi.waitFor(() => expect(action).toHaveBeenCalledWith( - 'variants.save', - expect.objectContaining({ - parameters: [expect.objectContaining({ name: 'box_width', expression: '40 mm' })], - }), + 'variants.apply', + expect.objectContaining({ id: 'compact' }), ), ); }); - it('offers hierarchy IntelliSense in the search and compiles formula references', async () => { - mount(searchModel); - create(); - input('Find parameters for variant', 'box.'); - const editor = EditorView.findFromDOM( - host.querySelector('[aria-label="Find parameters for variant"]')!, - )!; - act(() => { - startCompletion(editor); - }); - await vi.waitFor(() => - expect(currentCompletions(editor.state).map((item) => item.label)).toContain('width'), - ); - input('Find parameters for variant', 'box.width=box.height/2'); - expect(host.querySelector('[aria-label="Value for box_width"]')!.value).toBe( - 'box_height/2', - ); - input('Find parameters for variant', 'unknown=20'); - expect(host.textContent).toContain('Choose an existing editable parameter'); - }); - it('shows variant search only above five saved variants', () => { - const variants = Array.from({ length: 5 }, (_, index) => ({ - ...saved, - id: String(index), - name: `Size ${index}`, - })); - mount({ ...model, variants }); - click('Variants: Free'); - expect(host.querySelector('[aria-label="Find variant"]')).toBeNull(); + it('closes the draft when the active document changes', () => { + const action = mount(); + open(); + input('Compact / width', '40 mm'); act(() => render( , host, ), ); - expect(host.querySelector('[aria-label="Find variant"]')).toBeTruthy(); + expect(host.querySelector('[role="dialog"]')).toBeNull(); + expect(action).not.toHaveBeenCalled(); + }); + it('marks configured parameters in the common list independently of the active variant', () => { + host = document.createElement('div'); + act(() => + render( + {}} onDelete={() => {}} />, + host, + ), + ); + expect(host.querySelector('[aria-label="width: controlled by variants"]')).toBeTruthy(); + expect(host.querySelector('[aria-label="height: controlled by variants"]')).toBeNull(); }); }); diff --git a/frontend/src/variants.tsx b/frontend/src/variants.tsx index 8c7471b..38fdeca 100644 --- a/frontend/src/variants.tsx +++ b/frontend/src/variants.tsx @@ -1,32 +1,19 @@ import { useEffect, useRef, useState } from 'preact/hooks'; -import { Check, ChevronDown, Pencil, Plus, Search, Trash2, X } from 'lucide-preact'; -import type { ModelState, Variant, VariantParameter } from './bridge'; -import { VariantParameterTree } from './variant-parameter-tree'; -import { ExpressionEditor } from './editor'; -import { parseVariantQuery } from './variant-query'; +import { Check, ChevronDown, Pencil, Plus, Search } from 'lucide-preact'; +import type { ModelState, Variant } from './bridge'; +import { VariantTable } from './variant-table'; -type Action = 'variants.save' | 'variants.apply' | 'variants.free' | 'variants.delete'; +type Action = 'variants.table.save' | 'variants.apply' | 'variants.free' | 'variants.delete'; type Props = { model: ModelState; disabled: boolean; error?: string; onAction: (action: Action, payload: Record) => Promise; }; -type Draft = { - id?: string; - name: string; - parameters: VariantParameter[]; - variantsToken: string | undefined; - snapshotToken: string | undefined; -}; - export function VariantsControl({ model, disabled, error, onAction }: Props) { const [open, setOpen] = useState(false); const [filter, setFilter] = useState(''); - const [draft, setDraft] = useState(null); - const [parameterFilter, setParameterFilter] = useState(''); - const [selectedOnly, setSelectedOnly] = useState(false); - const [deleting, setDeleting] = useState(false); + const [editor, setEditor] = useState<{ create: boolean } | null>(null); const [menuPosition, setMenuPosition] = useState({ left: 12, top: 38, @@ -35,18 +22,15 @@ export function VariantsControl({ model, disabled, error, onAction }: Props) { }); const root = useRef(null); const trigger = useRef(null); - const dialog = useRef(null); - const nameInput = useRef(null); const variants = model.variants || []; const active = variants.find((variant) => variant.id === model.activeVariantId); const unavailable = disabled || !!model.variantsError || !model.variantSnapshotToken; const tokens = { variantsToken: model.variantsToken, snapshotToken: model.variantSnapshotToken }; - function positionMenu() { const bounds = trigger.current?.getBoundingClientRect(); if (!bounds) return; - const width = Math.min(360, window.innerWidth - 24); - const top = bounds.bottom + 6; + const width = Math.min(360, window.innerWidth - 24), + top = bounds.bottom + 6; setMenuPosition({ left: Math.max(12, Math.min(bounds.right - width, window.innerWidth - width - 12)), top, @@ -54,7 +38,6 @@ export function VariantsControl({ model, disabled, error, onAction }: Props) { maxHeight: Math.max(80, window.innerHeight - top - 8), }); } - useEffect(() => { if (!open) return; positionMenu(); @@ -69,27 +52,17 @@ export function VariantsControl({ model, disabled, error, onAction }: Props) { }; }, [open]); useEffect(() => { - if (draft) nameInput.current?.focus(); - }, [!!draft]); - + setOpen(false); + setEditor(null); + }, [model.documentId]); + function edit(create = false) { + setOpen(false); + setEditor({ create }); + } function closeEditor() { - if (disabled) return; - setDraft(null); - setDeleting(false); + setEditor(null); trigger.current?.focus(); } - function edit(variant?: Variant) { - setOpen(false); - setParameterFilter(''); - setSelectedOnly(false); - setDeleting(false); - setDraft({ - ...(variant ? { id: variant.id } : {}), - name: variant?.name || '', - parameters: variant ? variant.parameters.map((parameter) => ({ ...parameter })) : [], - ...tokens, - }); - } async function select(variant?: Variant) { if ( await onAction(variant ? 'variants.apply' : 'variants.free', { id: variant?.id, ...tokens }) @@ -98,66 +71,15 @@ export function VariantsControl({ model, disabled, error, onAction }: Props) { trigger.current?.focus(); } } + const parameterCount = (model.variantColumns || []).filter( + (column) => column.kind === 'parameter', + ).length; + const featureCount = (model.variantColumns || []).filter( + (column) => column.kind === 'feature', + ).length; const matching = variants.filter((variant) => variant.name.toLocaleLowerCase().includes(filter.toLocaleLowerCase()), ); - const nameExists = - !!draft && - variants.some( - (variant) => - variant.id !== draft.id && - variant.name.toLocaleLowerCase() === draft.name.trim().toLocaleLowerCase(), - ); - const parameters = model.parameters.filter( - (parameter) => !parameter.driven && parameter.entityToken, - ); - // Resolve by name for the UI. The adapter validates actual Fusion entities by token before writing. - const rows: (VariantParameter & { kind?: 'user' | 'model' })[] = parameters.map((parameter) => ({ - name: parameter.name, - entityToken: parameter.entityToken!, - expression: parameter.expression, - unit: parameter.unit, - value: parameter.value, - missing: false, - kind: parameter.kind, - })); - for (const parameter of draft?.parameters || []) { - if (parameter.missing || !rows.some((row) => row.name === parameter.name)) { - const replacement = rows.findIndex((row) => row.name === parameter.name); - if (replacement !== -1) rows.splice(replacement, 1); - rows.unshift({ ...parameter, missing: true, kind: undefined }); - } - } - const query = parseVariantQuery(parameterFilter, model.parameters); - const visibleRows = rows.filter( - (parameter) => - parameter.name.toLocaleLowerCase().includes(query.filter) && - (!selectedOnly || draft?.parameters.some((entry) => entry.name === parameter.name)), - ); - function changeParameterQuery(text: string) { - setParameterFilter(text); - const result = parseVariantQuery(text, model.parameters); - if (!result.assignment) return; - const { parameter, expression } = result.assignment; - setDraft((current) => { - if (!current) return current; - const entry: VariantParameter = { - name: parameter.name, - entityToken: parameter.entityToken!, - unit: parameter.unit, - expression, - value: 0, - }; - const exists = current.parameters.some((item) => item.name === parameter.name); - return { - ...current, - parameters: exists - ? current.parameters.map((item) => (item.name === parameter.name ? entry : item)) - : [...current.parameters, entry], - }; - }); - } - return (
+
{error && ( ))} {!variants.length && ( @@ -297,214 +228,21 @@ export function VariantsControl({ model, disabled, error, onAction }: Props) {

No matching variants.

)} - )} - {draft && ( -
- -
+ {editor && ( + onAction('variants.table.save', payload)} + /> )} ); diff --git a/frontend/variants-preview.html b/frontend/variants-preview.html index 68ca9e0..df30655 100644 --- a/frontend/variants-preview.html +++ b/frontend/variants-preview.html @@ -32,7 +32,25 @@ documentName: 'Enclosure v12', defaultLengthUnit: 'mm', parameters, - variants: [], + variantTableVersion: 2, + variantColumns: [ + ...parameters.slice(0, 2).map((p) => ({ + kind: 'parameter', + name: p.name, + entityToken: p.entityToken, + unit: p.unit, + })), + { kind: 'feature', name: 'Lid cut', entityToken: 'lid-cut' }, + ], + timelineFeatures: [{ name: 'Lid cut', entityToken: 'lid-cut', enabled: true }], + variants: ['Classic', 'Compact', 'Garden'].map((name, index) => ({ + id: String(index), + name, + parameters: parameters + .slice(0, 2) + .map((p) => ({ ...p, value: 12, expression: index ? '90 mm' : p.expression })), + features: [{ name: 'Lid cut', entityToken: 'lid-cut', enabled: index !== 1 }], + })), activeVariantId: null, variantsToken: 'storage', variantSnapshotToken: 'snapshot', @@ -50,7 +68,9 @@ unit: 'mm', value: (90 + index) / 10, }, + { ...parameters[1], value: 8 }, ], + features: [{ name: 'Lid cut', entityToken: 'lid-cut', enabled: true }], })); } window.adsk = { @@ -58,7 +78,69 @@ const r = JSON.parse(raw); let data = {}; const p = r.payload; - if (r.action === 'state.get') data = structuredClone(model); + if (r.action === 'state.get') { + parameters.forEach( + (p) => + (p.configured = model.variantColumns.some( + (c) => c.kind === 'parameter' && c.name === p.name, + )), + ); + data = structuredClone(model); + } + if (r.action === 'variants.selection.get') + data = { documentId: model.documentId, features: [] }; + if (r.action === 'variants.cell.preview') { + // This browser-only fixture preserves syntax; Fusion performs real validation. + let parts = [], + part = '', + depth = 0, + quote = '', + escaped = false; + for (const character of p.text) { + if (quote) { + part += character; + if (escaped) escaped = false; + else if (character === '\\') escaped = true; + else if (character === quote) quote = ''; + continue; + } + if (character === "'" || character === '"') { + quote = character; + part += character; + } else if (character === '(') { + depth++; + part += character; + } else if (character === ')') { + depth--; + part += character; + } else if (character === ';' && depth === 0) { + parts.push(part); + part = ''; + } else part += character; + } + parts.push(part); + const definitions = parts.map((text) => { + const at = text.indexOf('='); + return { + name: text.slice(0, at).trim().replaceAll('.', '_'), + expression: text.slice(at + 1).trim(), + }; + }); + const target = definitions.find((x) => x.name === p.target); + data = { + expression: + target?.expression || + p.parameters.find((x) => x.name === p.target)?.expression || + '', + newParameters: definitions + .filter((x) => x.name !== p.target) + .map((x) => ({ + ...x, + unit: parameters.find((x) => x.name === p.target)?.unit || 'mm', + value: x.expression, + })), + }; + } if (r.action === 'document.units') model.defaultLengthUnit = p.unit; if (r.action === 'calculator.evaluate') { const arithmetic = p.expression @@ -135,32 +217,49 @@ if (active) { const entry = { ...parameter }; const index = active.parameters.findIndex((item) => item.name === name); - if (index < 0) active.parameters.push(entry); - else active.parameters[index] = entry; + if (index >= 0) active.parameters[index] = entry; } }); } - if (r.action === 'variants.save') { - let v = { - id: p.id || String(Date.now()), - name: p.name, - parameters: structuredClone(p.parameters), - }; - const i = model.variants.findIndex((x) => x.id === v.id); - if (i < 0) model.variants.push(v); - else model.variants[i] = v; - model.activeVariantId = v.id; - v.parameters.forEach((e) => { - let a = parameters.find((x) => x.name === e.name); - a.expression = e.expression; - a.value = e.expression; - }); + if (r.action === 'variants.table.save') { + (p.newParameters || []).forEach((entry) => + parameters.push({ + ...entry, + entityToken: entry.name, + kind: 'user', + favorite: false, + configured: false, + value: entry.expression, + }), + ); + model.variantColumns = structuredClone(p.columns); + model.variants = structuredClone(p.variants).map((v) => ({ + ...v, + id: v.id || crypto.randomUUID(), + })); + const active = model.variants.find((v) => v.id === model.activeVariantId); + if (active) { + active.parameters.forEach((e) => { + const p = parameters.find((x) => x.name === e.name); + p.expression = e.expression; + p.value = e.expression; + }); + (active.features || []).forEach((f) => { + model.timelineFeatures.find((x) => x.entityToken === f.entityToken).enabled = + f.enabled; + }); + } + if (model.activeVariantId && !active) model.activeVariantId = null; } if (r.action === 'variants.free') model.activeVariantId = null; if (r.action === 'variants.apply') { const v = model.variants.find((x) => x.id === p.id); model.activeVariantId = v.id; + (v.features || []).forEach((f) => { + model.timelineFeatures.find((x) => x.entityToken === f.entityToken).enabled = + f.enabled; + }); v.parameters.forEach((e) => { let a = parameters.find((x) => x.name === e.name); a.expression = e.expression; diff --git a/tests/fusion_variants_v2_smoke.py b/tests/fusion_variants_v2_smoke.py new file mode 100644 index 0000000..6e13b3c --- /dev/null +++ b/tests/fusion_variants_v2_smoke.py @@ -0,0 +1,265 @@ +"""Manual Fusion smoke test: creates and discards only its own temporary document. + +Run through Fusion's permitted main-thread script context. This exercises the source adapter, +not the installed Paramood palette. No Configuration API, save, export, or user model writes. +""" + +import importlib +import builtins +import importlib.util +import json +import math +import sys +import uuid +from pathlib import Path + +import adsk.core +import adsk.fusion + + +def run(_context): + app = adsk.core.Application.get() + assert app.userInterface.activeCommand == 'SelectCommand', 'Finish the active command first.' + original = app.activeDocument + package = Path(__file__).resolve().parents[1] / 'Paramood' + alias = 'paramood_v2_smoke_' + uuid.uuid4().hex + spec = importlib.util.spec_from_file_location( + alias, package / '__init__.py', submodule_search_locations=[str(package)] + ) + module = importlib.util.module_from_spec(spec) + sys.modules[alias] = module + spec.loader.exec_module(module) + adapter_type = importlib.import_module(alias + '.fusion.adapter').FusionAdapter + document = app.documents.add(adsk.core.DocumentTypes.FusionDesignDocumentType) + design = adsk.fusion.Design.cast(app.activeProduct) + assert design + design.designType = adsk.fusion.DesignTypes.ParametricDesignType + design.attributes.add('4FusionLab.Paramood', 'variants.v1', 'legacy-untouched') + height = design.userParameters.add( + 'test_height', adsk.core.ValueInput.createByString('20 mm'), 'mm', '' + ) + width = design.userParameters.add( + 'test_width', adsk.core.ValueInput.createByString('10 mm'), 'mm', '' + ) + outside = design.userParameters.add( + 'global_clearance', adsk.core.ValueInput.createByString('1 mm'), 'mm', '' + ) + root = design.rootComponent + sketch = root.sketches.add(root.xYConstructionPlane) + sketch.sketchCurves.sketchCircles.addByCenterRadius(adsk.core.Point3D.create(0, 0, 0), 1) + feature = root.features.extrudeFeatures.addSimple( + sketch.profiles.item(0), + adsk.core.ValueInput.createByString('test_height'), + adsk.fusion.FeatureOperations.NewBodyFeatureOperation, + ) + feature.name = 'Variant controlled extrusion' + adapter = adapter_type(app) + adapter.in_direct_apply = True + adapter._design() + selection_events = [] + + class SelectionProbe(adsk.core.ActiveSelectionEventHandler): + def notify(self, args): + selection_events.append(adapter._variant_timeline_selection()) + + probe = SelectionProbe() + ui = app.userInterface + ui.activeSelectionChanged.add(probe) + ui.activeSelections.clear() + assert ui.activeSelections.add(feature) + adsk.doEvents() + selection = adapter.request('variants.selection.get', {}) + assert [item['name'] for item in selection['features']] == [feature.name] + assert any(event['features'] for event in selection_events) + ui.activeSelections.clear() + ui.activeSelectionChanged.remove(probe) + + def send(action, payload): + assert app.activeDocument == document, 'Temporary document is no longer active.' + state = adapter._variants_state(design) + assert not state.get('variantsError'), state + return adapter.request( + action, + { + 'variantsToken': state['variantsToken'], + 'snapshotToken': state['variantSnapshotToken'], + **payload, + }, + ) + + assert adapter._variants_state(design)['variants'] == [] + columns = [ + {'kind': 'parameter', 'name': p.name, 'entityToken': p.entityToken, 'unit': p.unit} + for p in (width, height) + ] + [{'kind': 'feature', 'name': feature.name, 'entityToken': feature.entityToken}] + rows = [] + for name, values, enabled in ( + ('Off', ('40 mm', '30 mm'), False), + ('On', ('25 mm', '35 mm'), True), + ): + rows.append( + { + 'name': name, + 'parameters': [ + dict(adapter._variant_entry(p), expression=value) + for p, value in zip((width, height), values) + ], + 'features': [dict(adapter._feature_entry(feature), enabled=enabled)], + } + ) + send('variants.table.save', {'columns': columns, 'variants': rows}) + assert height.expression == '20 mm' and width.expression == '10 mm' + assert not feature.isSuppressed and root.bRepBodies.count == 1 + assert adapter._variants_state(design)['activeVariantId'] is None + saved = adapter._variants_state(design)['variants'] + send('variants.apply', {'id': saved[0]['id']}) + assert feature.isSuppressed and root.bRepBodies.count == 0 + send('variants.apply', {'id': saved[1]['id']}) + assert not feature.isSuppressed and root.bRepBodies.count == 1 + assert math.isclose(root.bRepBodies.item(0).boundingBox.maxPoint.z, 3.5, abs_tol=1e-6) + edited = adapter._variants_state(design)['variants'] + edited[1]['parameters'][1]['expression'] = '45 mm' + edited[0]['parameters'][1]['expression'] = '99 mm' + send('variants.table.save', {'columns': columns, 'variants': edited}) + assert math.isclose(height.value, 4.5) + assert math.isclose(root.bRepBodies.item(0).boundingBox.maxPoint.z, 4.5, abs_tol=1e-6) + assert adapter._variants_state(design)['activeVariantId'] == saved[1]['id'] + state = adapter.state() + assert {p['name'] for p in state['parameters'] if p.get('configured')} == { + 'test_width', + 'test_height', + } + context = adapter._variant_edit_context(design) + outside.expression = '2 mm' + adapter._capture_variant_edits(design, context, ['global_clearance']) + stored = json.loads(design.attributes.itemByName('4FusionLab.Paramood', 'variants.v2').value) + assert len(stored['columns']) == 3 + assert all(len(row['parameters']) == 2 for row in stored['variants']) + assert ( + design.attributes.itemByName('4FusionLab.Paramood', 'variants.v1').value + == 'legacy-untouched' + ) + state = adapter._variants_state(design) + on_row = state['variants'][1] + preview = send( + 'variants.cell.preview', + { + 'target': width.name, + 'parameters': on_row['parameters'], + 'text': 'draft_beam=27 mm;test_width=draft_beam', + }, + ) + assert preview['expression'] == 'draft_beam' + assert not design.userParameters.itemByName('draft_beam') + assert width.expression == '25 mm' + updated = state['variants'] + updated[1]['parameters'][0]['expression'] = preview['expression'] + definition = ui.commandDefinitions.addButtonDefinition( + 'ParamoodV2CreateSmoke_' + uuid.uuid4().hex, 'Paramood V2 smoke', 'Temporary test command' + ) + dispatch = importlib.import_module(alias + '.bridge.protocol').dispatch + responses = [] + handlers = [] + + class Execute(adsk.core.CommandEventHandler): + def notify(self, args): + adapter.in_direct_apply = False + adapter.in_command = True + result = dispatch( + adapter, + { + 'requestId': 'create-smoke', + 'documentId': adapter.document_id, + 'action': 'variants.table.save', + 'payload': { + 'columns': columns, + 'variants': updated, + 'newParameters': preview['newParameters'], + 'variantsToken': state['variantsToken'], + 'snapshotToken': state['variantSnapshotToken'], + }, + }, + ) + responses.append(result) + args.executeFailed = not result['ok'] + adapter.in_command = False + adapter.in_direct_apply = True + + class Created(adsk.core.CommandCreatedEventHandler): + def notify(self, args): + handler = Execute() + args.command.execute.add(handler) + handlers.append(handler) + + created = Created() + definition.commandCreated.add(created) + builtins._paramood_v2_smoke_pending = { + 'app': app, + 'adapter': adapter, + 'document': document, + 'original': original, + 'alias': alias, + 'responses': responses, + 'definition': definition, + 'created': created, + 'handlers': handlers, + 'width': width, + 'height': height, + 'feature': feature, + } + assert definition.execute() + print('QUEUED: run finish after returning to the Fusion event loop.') + + +def finish(_context): + context = builtins._paramood_v2_smoke_pending + app, adapter, document = context['app'], context['adapter'], context['document'] + original, alias = context['original'], context['alias'] + width, height, feature = context['width'], context['height'], context['feature'] + responses, definition, created = context['responses'], context['definition'], context['created'] + assert app.activeDocument == document and app.userInterface.activeCommand == 'SelectCommand' + assert responses and responses[0]['ok'], responses + design = adsk.fusion.Design.cast(app.activeProduct) + assert design.userParameters.itemByName('draft_beam') + assert width.expression == 'draft_beam' and math.isclose(width.value, 2.7) + assert not next(p for p in adapter.state()['parameters'] if p['name'] == 'draft_beam')[ + 'configured' + ] + definition.commandCreated.remove(created) + definition.deleteMe() + state = adapter._variants_state(design) + adapter.request( + 'variants.free', + {'variantsToken': state['variantsToken'], 'snapshotToken': state['variantSnapshotToken']}, + ) + assert not feature.isSuppressed and math.isclose(height.value, 4.5) + assert document.close(False) + if original: + assert original.activate() + for key in list(sys.modules): + if key == alias or key.startswith(alias + '.'): + del sys.modules[key] + del builtins._paramood_v2_smoke_pending + print( + json.dumps( + { + 'result': 'PASS', + 'fusion': app.version, + 'checks': [ + 'v2 storage only', + 'native feature selection and activeSelectionChanged event', + 'save without model changes', + 'suppress and unsuppress extrusion', + '35 and 45 mm CAD heights', + 'active-row Save applies only active row', + 'configured markers', + 'outside-set edit stays global', + 'Free preserves geometry', + 'cell creation preview is read-only', + 'Save creates and links a global parameter in a native command transaction', + 'temporary document discarded', + 'original document restored', + ], + } + ) + ) diff --git a/tests/integration/test_package_imports.py b/tests/integration/test_package_imports.py index 7c51b7e..0341ab6 100644 --- a/tests/integration/test_package_imports.py +++ b/tests/integration/test_package_imports.py @@ -11,6 +11,7 @@ def test_fusion_entry_import_ignores_other_addins_common_module_names(monkeypatc fusion = types.ModuleType('adsk.fusion') for name in ( 'HTMLEventHandler', + 'ActiveSelectionEventHandler', 'CommandEventHandler', 'CommandCreatedEventHandler', 'DocumentEventHandler', diff --git a/tests/integration/test_palette_routing.py b/tests/integration/test_palette_routing.py index d393217..f95669a 100644 --- a/tests/integration/test_palette_routing.py +++ b/tests/integration/test_palette_routing.py @@ -13,6 +13,7 @@ def entry(monkeypatch): core, fusion = types.ModuleType('adsk.core'), types.ModuleType('adsk.fusion') for name in ( 'HTMLEventHandler', + 'ActiveSelectionEventHandler', 'CommandEventHandler', 'CommandCreatedEventHandler', 'DocumentEventHandler', diff --git a/tests/integration/test_release_package.py b/tests/integration/test_release_package.py index 5e62aed..aa5263c 100644 --- a/tests/integration/test_release_package.py +++ b/tests/integration/test_release_package.py @@ -56,6 +56,7 @@ def test_packaged_addin_imports_under_its_release_name(tmp_path, monkeypatch): fusion = types.ModuleType('adsk.fusion') for name in ( 'HTMLEventHandler', + 'ActiveSelectionEventHandler', 'CommandEventHandler', 'CommandCreatedEventHandler', 'DocumentEventHandler', diff --git a/tests/integration/test_variants_adapter.py b/tests/integration/test_variants_adapter.py index 387ced8..ca1f0e1 100644 --- a/tests/integration/test_variants_adapter.py +++ b/tests/integration/test_variants_adapter.py @@ -12,16 +12,25 @@ class Attributes: def __init__(self): - self.value = None + self.values = {} self.fail = False + @property + def value(self): + return self.values.get('variants.v2') + + @value.setter + def value(self, value): + self.values['variants.v2'] = value + def itemByName(self, group, name): - return SimpleNamespace(value=self.value) if self.value is not None else None + value = self.values.get(name) + return SimpleNamespace(value=value) if value is not None else None def add(self, group, name, value): if self.fail: return None - self.value = value + self.values[name] = value return SimpleNamespace(value=value) @@ -37,16 +46,27 @@ def model(monkeypatch): core.ValueInput = SimpleNamespace(createByString=lambda value: value) fusion.Design = SimpleNamespace(cast=lambda product: product) fusion.ModelParameter = SimpleNamespace(cast=lambda parameter: None) + fusion.ParameterValueTypes = SimpleNamespace( + NumericParameterValueType=0, TextParameterValueType=1 + ) adsk.core, adsk.fusion = core, fusion for name, module in [('adsk', adsk), ('adsk.core', core), ('adsk.fusion', fusion)]: monkeypatch.setitem(sys.modules, name, module) sys.modules.pop('Paramood.fusion.adapter', None) sys.modules.pop('Paramood.fusion.variants', None) + sys.modules.pop('Paramood.fusion.variant_table', None) module = importlib.import_module('Paramood.fusion.adapter') params = Parameters( [ SimpleNamespace( - name=name, entityToken='token-' + name, expression='10 mm', unit='mm', value=1.0 + name=name, + entityToken='token-' + name, + expression='10 mm', + unit='mm', + value=1.0, + valueType=0, + dependencyParameters=[], + dependentParameters=[], ) for name in ('width', 'height') ] @@ -68,6 +88,7 @@ def modify(parameters, expressions): userParameters=params, fusionUnitsManager=SimpleNamespace( defaultLengthUnits='mm', + formatUnits=lambda name: '', isValidExpression=lambda expression, unit: expression != 'invalid', ), findEntityByToken=lambda token: [p for p in params if p.entityToken == token], @@ -80,6 +101,7 @@ def modify(parameters, expressions): yield adapter, design, params, calls sys.modules.pop('Paramood.fusion.adapter', None) sys.modules.pop('Paramood.fusion.variants', None) + sys.modules.pop('Paramood.fusion.variant_table', None) def send(adapter, action, **payload): @@ -92,198 +114,376 @@ def send(adapter, action, **payload): return adapter.request(action, body) -def save(adapter, params, name='Compact', **kwargs): - return send( - adapter, - 'variants.save', - name=name, - parameters=[adapter._variant_entry(params[0])], - **kwargs, - )['activeVariantId'] +def table_save(adapter, params, expressions=('20 mm', '30 mm')): + columns = [ + dict( + kind='parameter', + **{k: adapter._variant_entry(p)[k] for k in ('name', 'entityToken', 'unit')}, + ) + for p in params + ] + rows = [ + dict( + name='Compact', + parameters=[ + dict(adapter._variant_entry(p), expression=e) for p, e in zip(params, expressions) + ], + ) + ] + send(adapter, 'variants.table.save', columns=columns, variants=rows) + return json.loads(adapter._design().attributes.value) -def test_save_switch_free_and_reopen_match(model): +def test_table_save_plans_all_cells_without_changing_or_activating_model(model): adapter, design, params, calls = model - identity = save(adapter, params) - assert json.loads(design.attributes.value)['variants'][0]['id'] == identity - send(adapter, 'variants.free') - assert adapter._variants_state(design)['activeVariantId'] is None - adapter._variant_sessions.clear() - assert adapter._variants_state(design)['activeVariantId'] == identity - params[0].value = 2 + table = table_save(adapter, params) + assert table['version'] == 2 + assert [p['value'] for p in table['variants'][0]['parameters']] == [2, 3] + assert [p.expression for p in params] == ['10 mm', '10 mm'] + assert not calls assert adapter._variants_state(design)['activeVariantId'] is None - send(adapter, 'variants.apply', id=identity) - assert params[0].value == 1 - assert calls[-1] == ['10 mm'] - assert adapter._variants_state(design)['activeVariantId'] == identity + send(adapter, 'variants.apply', id=table['variants'][0]['id']) + assert [p.value for p in params] == [2, 3] -def test_delete_membership_never_deletes_model_parameters(model): +def test_save_applies_only_active_row_after_validating_every_row(model): adapter, design, params, calls = model - identity = send( - adapter, - 'variants.save', - name='Both', - parameters=[adapter._variant_entry(p) for p in params], - )['activeVariantId'] - send( - adapter, - 'variants.save', - id=identity, - name='Height only', - parameters=[adapter._variant_entry(params[1])], - ) - assert len(params) == 2 - assert len(adapter._read_variants(design)[0][0]['parameters']) == 1 - send(adapter, 'variants.delete', id=identity) - assert len(params) == 2 - assert adapter._read_variants(design)[0] == [] + table = table_save(adapter, params) + row = table['variants'][0] + send(adapter, 'variants.apply', id=row['id']) + row['parameters'][0]['expression'] = '50 mm' + other = dict(copy.deepcopy(row), id=None, name='Other') + other['parameters'][0]['expression'] = '90 mm' + send(adapter, 'variants.table.save', columns=table['columns'], variants=[other, row]) + assert params[0].value == 5 + assert adapter._variants_state(design)['activeVariantId'] == row['id'] + assert len(calls) == 2 + raw = design.attributes.value + other['parameters'][0]['expression'] = 'unknown_variable' + row['parameters'][0]['expression'] = '60 mm' + with pytest.raises(Exception): + send(adapter, 'variants.table.save', columns=table['columns'], variants=[other, row]) + assert params[0].value == 5 and design.attributes.value == raw + assert len(calls) == 2 -def test_active_edits_capture_new_parameter_and_existing_values(model): +def test_active_row_save_storage_failure_restores_model_and_metadata(model): adapter, design, params, calls = model - identity = save(adapter, params) + table = table_save(adapter, params) + row = table['variants'][0] + send(adapter, 'variants.apply', id=row['id']) + raw = design.attributes.value + row['parameters'][0]['expression'] = '50 mm' + design.attributes.fail = True + with pytest.raises(Exception, match='save variants'): + send(adapter, 'variants.table.save', columns=table['columns'], variants=[row]) + assert params[0].value == 2 and design.attributes.value == raw + + +def test_reordering_active_variant_cells_does_not_recompute_cad(model): + adapter, design, params, calls = model + table = table_save(adapter, params) + row = table['variants'][0] + send(adapter, 'variants.apply', id=row['id']) + row['parameters'].reverse() + send(adapter, 'variants.table.save', columns=list(reversed(table['columns'])), variants=[row]) + assert len(calls) == 1 + assert [c['name'] for c in json.loads(design.attributes.value)['columns']] == [ + 'height', + 'width', + ] + + +def test_table_formulas_use_each_rows_proposed_values(model): + adapter, design, params, calls = model + table = table_save(adapter, params, ('20 mm', 'width / 2')) + assert table['variants'][0]['parameters'][1]['value'] == 1 + assert not calls + + +def test_table_global_set_and_row_column_order_survive_edits(model): + adapter, design, params, calls = model + table = table_save(adapter, params) + first = table['variants'][0] + second = dict(copy.deepcopy(first), id=None, name='Garden') + columns = list(reversed(table['columns'])) + for row in (first, second): + row['parameters'].reverse() + send(adapter, 'variants.table.save', columns=columns, variants=[second, first]) + stored = json.loads(design.attributes.value) + assert [r['name'] for r in stored['variants']] == ['Garden', 'Compact'] + assert [c['name'] for c in stored['columns']] == ['height', 'width'] + assert not calls + + +def test_table_rejects_missing_cells_duplicate_names_and_foreign_ids_atomically(model): + adapter, design, params, calls = model + table = table_save(adapter, params) + raw = design.attributes.value + for problem in ('cell', 'name', 'id'): + rows = copy.deepcopy(table['variants']) + if problem == 'cell': + rows[0]['parameters'].pop() + elif problem == 'name': + rows.append(dict(copy.deepcopy(rows[0]), id=None, name=rows[0]['name'].upper())) + else: + rows[0]['id'] = 'foreign' + with pytest.raises(Exception): + send(adapter, 'variants.table.save', columns=table['columns'], variants=rows) + assert design.attributes.value == raw + assert not calls + + +def test_table_capture_updates_configured_only_and_preserves_column_identity(model): + adapter, design, params, calls = model + table = table_save(adapter, params[:1], ('20 mm',)) + identity = table['variants'][0]['id'] + send(adapter, 'variants.apply', id=identity) context = adapter._variant_edit_context(design) - params[1].expression, params[1].value = '30 mm', 3 + params[0].expression, params[0].value = '40 mm', 4 + params[1].expression, params[1].value = '50 mm', 5 + adapter._capture_variant_edits(design, context, ['width', 'height']) + stored = json.loads(design.attributes.value) + assert len(stored['columns']) == 1 + assert [p['name'] for p in stored['variants'][0]['parameters']] == ['width'] + assert stored['variants'][0]['parameters'][0]['value'] == 4 + assert params[1].value == 5 + + +def test_outside_set_edit_never_writes_variant_metadata(model): + adapter, design, params, calls = model + table = table_save(adapter, params[:1], ('20 mm',)) + send(adapter, 'variants.apply', id=table['variants'][0]['id']) + raw = design.attributes.value + context = adapter._variant_edit_context(design) + design.attributes.fail = True + params[1].expression, params[1].value = '60 mm', 6 adapter._capture_variant_edits(design, context, ['height']) - stored = adapter._read_variants(design)[0][0] - assert stored['id'] == identity - assert [p['name'] for p in stored['parameters']] == ['width', 'height'] - assert stored['parameters'][1]['value'] == 3 - send(adapter, 'variants.free') - assert adapter._variant_edit_context(design)[1] is None + assert params[1].value == 6 and design.attributes.value == raw -def test_stale_snapshot_and_stale_storage_fail_before_writes(model): +def test_cell_cannot_inject_assignments_to_other_model_parameters(model): adapter, design, params, calls = model + with pytest.raises(Exception): + table_save(adapter, params[:1], ('20 mm; height=80 mm',)) + assert not calls and design.attributes.value is None + + +def test_bare_cell_number_uses_parameter_unit_instead_of_design_default(model): + adapter, design, params, calls = model + design.fusionUnitsManager.defaultLengthUnits = 'cm' + table = table_save(adapter, params[:1], ('20',)) + assert table['variants'][0]['parameters'][0]['value'] == 2 + + +def test_timeline_selection_is_read_only_and_rejects_foreign_and_nonfeature_entities(model): + adapter, design, params, calls = model + parent, child, log = features_model(model) + foreign = Feature('Foreign', log) + selected = [SimpleNamespace(entity=e) for e in (parent, parent, foreign, params[0])] + adapter.app.userInterface = SimpleNamespace( + activeCommand='SelectCommand', + activeSelections=SimpleNamespace(count=len(selected), item=lambda index: selected[index]), + ) + adapter.in_command = adapter.in_direct_apply = False + state = adapter.request('variants.selection.get', {}) + assert state['documentId'] == adapter.document_id + assert [f['name'] for f in state['features']] == ['Parent'] + assert design.attributes.value is None and not log and not calls + adapter.app.userInterface.activeCommand = 'Extrude' + with pytest.raises(Exception, match='Finish'): + adapter.request('variants.selection.get', {}) + + +class Feature: + def __init__(self, name, log, enabled=True): + self.name, self.entityToken = name, 'feature-' + name + self.isValid = self.isParametric = True + self._suppressed, self.log = not enabled, log + self.reject_suppress = False + + @property + def isSuppressed(self): + return self._suppressed + + @isSuppressed.setter + def isSuppressed(self, value): + if value and self.reject_suppress: + raise RuntimeError('suppression refused') + self.log.append((self.name, value)) + self._suppressed = value + + +def features_model(model): + adapter, design, params, calls = model + log = [] + parent, child = Feature('Parent', log), Feature('Child', log) + sys.modules['adsk.fusion'].Feature = SimpleNamespace( + cast=lambda entity: entity if isinstance(entity, Feature) else None + ) + items = [SimpleNamespace(isGroup=False, entity=f) for f in (parent, child)] + design.timeline = SimpleNamespace(count=2, item=lambda i: items[i]) + find = design.findEntityByToken + design.findEntityByToken = lambda token: ( + [f for f in (parent, child) if f.entityToken == token and f.isValid] or find(token) + ) + return parent, child, log + + +def test_feature_only_table_and_suppression_follow_timeline_not_table_order(model): + adapter, design, params, calls = model + parent, child, log = features_model(model) + columns = [ + dict(kind='feature', name=f.name, entityToken=f.entityToken) for f in (child, parent) + ] + cells = [dict(adapter._feature_entry(f), enabled=False) for f in (child, parent)] + send( + adapter, + 'variants.table.save', + columns=columns, + variants=[dict(name='Off', parameters=[], features=cells)], + ) + assert not log and not calls + identity = adapter._variants_state(design)['variants'][0]['id'] + send(adapter, 'variants.apply', id=identity) + assert log == [('Child', True), ('Parent', True)] + assert adapter._variants_state(design)['activeVariantId'] == identity + parent.isSuppressed = False + assert adapter._variants_state(design)['activeVariantId'] is None + + +def test_external_feature_edit_invalidates_table_request_and_removed_identity_never_rebinds(model): + adapter, design, params, calls = model + parent, child, log = features_model(model) state = adapter._variants_state(design) - save(adapter, params) - with pytest.raises(Exception, match='changed'): - adapter.request( - 'variants.free', - { - 'variantsToken': state['variantsToken'], - 'snapshotToken': state['variantSnapshotToken'], - }, - ) - state = adapter._variants_state(design) - params[1].expression = '20 mm' - count = len(calls) + parent.isSuppressed = True with pytest.raises(Exception, match='changed'): adapter.request( - 'variants.free', - { - 'variantsToken': state['variantsToken'], - 'snapshotToken': state['variantSnapshotToken'], - }, + 'variants.table.save', + dict( + columns=[], + variants=[], + variantsToken=state['variantsToken'], + snapshotToken=state['variantSnapshotToken'], + ), ) - assert len(calls) == count + parent.isValid = False + assert adapter._resolve_variant_feature(design, dict(entityToken=parent.entityToken)) is None -def test_deleted_parameter_never_binds_new_parameter_with_same_name(model): +def test_partial_feature_failure_restores_parameters_and_suppression(model): adapter, design, params, calls = model - identity = save(adapter, params) - params[0] = SimpleNamespace( - name='width', entityToken='replacement', expression='10 mm', unit='mm', value=1 - ) - state = adapter._variants_state(design) - assert state['activeVariantId'] is None - assert state['variants'][0]['parameters'][0]['missing'] - with pytest.raises(Exception, match='unavailable'): - send(adapter, 'variants.apply', id=identity) - assert len(calls) == 1 + parent, child, log = features_model(model) + child.reject_suppress = True + table = table_save(adapter, params[:1], ('20 mm',)) + columns = table['columns'] + [ + dict(kind='feature', name=child.name, entityToken=child.entityToken) + ] + row = table['variants'][0] + row['features'] = [dict(adapter._feature_entry(child), enabled=False)] + send(adapter, 'variants.table.save', columns=columns, variants=[row]) + with pytest.raises(Exception, match='suppression refused'): + send(adapter, 'variants.apply', id=row['id']) + assert params[0].expression == '10 mm' + assert not child.isSuppressed and not parent.isSuppressed -def test_renamed_parameter_resolves_via_token(model): +def test_collapsed_timeline_groups_keep_feature_order(model): adapter, design, params, calls = model - identity = save(adapter, params) - params[0].name = 'new_width' - state = adapter._variants_state(design) - assert state['activeVariantId'] == identity - assert state['variants'][0]['parameters'][0]['name'] == 'new_width' - send(adapter, 'variants.apply', id=identity) + parent, child, log = features_model(model) + children = [SimpleNamespace(isGroup=False, entity=f) for f in (parent, child)] + group = SimpleNamespace(isGroup=True, count=2, item=lambda i: children[i]) + design.timeline = SimpleNamespace(count=1, item=lambda i: group) + adapter._set_feature_states([(child, False), (parent, False)]) + assert log == [('Child', True), ('Parent', True)] -def test_invalid_expression_and_batch_failure_preserve_saved_variant(model): +def test_major_version_two_ignores_and_preserves_old_attribute(model): adapter, design, params, calls = model - identity = save(adapter, params) - raw = design.attributes.value - for expression in ('invalid', 'reject'): - entry = {**adapter._variant_entry(params[0]), 'expression': expression} - with pytest.raises(Exception): - send(adapter, 'variants.save', id=identity, name='Changed', parameters=[entry]) - assert design.attributes.value == raw - assert params[0].expression == '10 mm' + design.attributes.values['variants.v1'] = 'legacy data must stay untouched' + assert adapter._variants_state(design)['variants'] == [] + table_save(adapter, params) + assert design.attributes.values['variants.v1'] == 'legacy data must stay untouched' + assert json.loads(design.attributes.values['variants.v2'])['version'] == 2 -def test_direct_storage_failure_restores_parameter_expressions(model): +def test_table_switch_free_external_edits_and_reopen(model): adapter, design, params, calls = model - adapter.in_command, adapter.in_direct_apply = False, True - design.attributes.fail = True - entry = {**adapter._variant_entry(params[0]), 'expression': '20 mm'} - with pytest.raises(Exception, match='save variants'): - send(adapter, 'variants.save', name='Failure', parameters=[entry]) - assert params[0].expression == '10 mm' - assert design.attributes.value is None - assert calls == [['20 mm'], ['10 mm']] + table = table_save(adapter, params) + identity = table['variants'][0]['id'] + send(adapter, 'variants.apply', id=identity) + assert adapter._variants_state(design)['activeVariantId'] == identity + send(adapter, 'variants.free') + assert [p.value for p in params] == [2, 3] + assert adapter._variants_state(design)['activeVariantId'] is None + adapter._variant_sessions.clear() + assert adapter._variants_state(design)['activeVariantId'] == identity + params[0].value = 9 + assert adapter._variants_state(design)['activeVariantId'] is None -def test_corrupt_or_future_storage_preserved(model): +def test_same_name_replacement_never_binds_and_deleted_variant_keeps_parameters(model): adapter, design, params, calls = model - for raw in ('broken', '{"version":2,"variants":[]}'): - design.attributes.value = raw - state = adapter._variants_state(design) - assert state['variantsError'] - with pytest.raises(Exception, match='preserved'): - send( - adapter, 'variants.save', name='No', parameters=[adapter._variant_entry(params[0])] - ) - assert design.attributes.value == raw + table = table_save(adapter, params[:1], ('20 mm',)) + identity = table['variants'][0]['id'] + original = params[0] + params[0] = copy.copy(original) + params[0].entityToken = 'replacement' + assert adapter._variants_state(design)['variants'][0]['parameters'][0]['missing'] + with pytest.raises(Exception, match='unavailable'): + send(adapter, 'variants.apply', id=identity) + send(adapter, 'variants.delete', id=identity) + assert len(params) == 2 assert not calls -def test_bridge_rejects_foreign_document(model): +def test_corrupt_v2_storage_is_preserved_and_foreign_document_rejected(model): adapter, design, params, calls = model + design.attributes.value = 'broken' + assert adapter._variants_state(design)['variantsError'] + with pytest.raises(Exception, match='preserved'): + send(adapter, 'variants.table.save', columns=[], variants=[]) result = dispatch( - adapter, {'requestId': 'x', 'action': 'variants.save', 'documentId': 'other', 'payload': {}} + adapter, + dict(requestId='wrong-doc', action='variants.table.save', documentId='other', payload={}), ) assert result['error']['code'] == 'STALE_DOCUMENT' - assert not calls - - -def test_two_models_and_identical_variants_have_deterministic_selection(model): - adapter, design, params, calls = model - first = save(adapter, params) - second = save(adapter, params, name='Same values') - assert adapter._variants_state(design)['activeVariantId'] == second - adapter._variant_sessions.clear() - assert adapter._variants_state(design)['activeVariantId'] == first - adapter.app.activeDocument = SimpleNamespace(name='Other') - adapter.app.activeProduct = copy.copy(design) - adapter.app.activeProduct.attributes = Attributes() - assert adapter._variants_state(adapter._design())['activeVariantId'] is None + assert design.attributes.value == 'broken' and not calls -def test_auto_save_failure_restores_direct_parameter_updates(model, monkeypatch): +def test_table_storage_failure_does_not_change_model_and_active_capture_restores_direct_edits( + model, monkeypatch +): adapter, design, params, calls = model - identity = save(adapter, params) + design.attributes.fail = True + with pytest.raises(Exception, match='save variants'): + table_save(adapter, params) + assert not calls and [p.value for p in params] == [1, 1] + design.attributes.fail = False + table = table_save(adapter, params[:1], ('20 mm',)) + send(adapter, 'variants.apply', id=table['variants'][0]['id']) raw = design.attributes.value adapter.in_command, adapter.in_direct_apply = False, True design.attributes.fail = True op = SimpleNamespace(name='width', status='Update') def execute(design, ops): - assert ops == [op] - params[0].expression, params[0].value = '20 mm', 2 + params[0].expression, params[0].value = '40 mm', 4 return {'created': [], 'updated': ['width']} monkeypatch.setattr(adapter, '_execute_direct_batch', execute) with pytest.raises(Exception, match='save variants'): adapter._execute_tracked_parameters(design, [op]) - assert params[0].expression == '10 mm' - assert params[0].value == 1 + assert params[0].expression == '20 mm' and params[0].value == 2 assert design.attributes.value == raw - assert adapter._variants_state(design)['activeVariantId'] == identity + assert adapter._variants_state(design)['activeVariantId'] == table['variants'][0]['id'] + + +def save(adapter, params): + table = table_save(adapter, params[:1], (params[0].expression,)) + identity = table['variants'][0]['id'] + send(adapter, 'variants.apply', id=identity) + return identity def test_parameter_preview_rejected_after_variant_selection_changes(model): @@ -369,3 +569,82 @@ def test_random_variant_matches_its_expression_after_recompute(model): assert adapter._variant_matches(design, variant) params[0].expression = 'random()*20 mm' assert not adapter._variant_matches(design, variant) + + +def preview_cell(adapter, params, text, **extra): + state = adapter._variants_state(adapter._design()) + return adapter.request( + 'variants.cell.preview', + { + 'target': params[0].name, + 'parameters': [adapter._variant_entry(p) for p in params], + 'text': text, + 'variantsToken': state['variantsToken'], + 'snapshotToken': state['variantSnapshotToken'], + **extra, + }, + ) + + +def test_cell_preview_relative_this_and_new_link_use_variant_row_without_writes(model): + adapter, design, params, calls = model + cells = [adapter._variant_entry(p) for p in params] + cells[0]['expression'] = '30 mm' + for text, expected in [('width=this*2', 60), ('width+=2', 32)]: + result = preview_cell(adapter, params, text, parameters=cells) + _, ops = adapter._plan('width=' + result['expression']) + assert ops[0].quantity.value == expected + result = preview_cell( + adapter, params, 'beam=10 mm;width=beam', parameters=cells, sourceName='width' + ) + assert result['newParameters'][0]['name'] == 'beam' + assert result['newParameters'][0]['value'] == 30 + assert result['expression'] == 'beam' + equation = preview_cell(adapter, params, '', parameters=cells, inlineEquation='span*2=50') + assert equation['newParameters'][0]['name'] == 'span' + assert equation['newParameters'][0]['value'] == 25 + assert not calls and design.attributes.value is None and len(params) == 2 + + +def test_pending_new_parameters_are_deferred_and_never_enrolled(model, monkeypatch): + adapter, design, params, calls = model + table = table_save(adapter, params[:1], ('20 mm',)) + row = table['variants'][0] + row['parameters'][0]['expression'] = 'beam' + pending = [{'name': 'beam', 'expression': '25 mm', 'unit': 'mm'}] + adapter.in_command, adapter.in_direct_apply = False, True + with pytest.raises(Exception, match='Finish'): + send( + adapter, + 'variants.table.save', + columns=table['columns'], + variants=[row], + newParameters=pending, + ) + assert len(params) == 2 and not calls + adapter.in_command, adapter.in_direct_apply = True, False + created = [] + + def create(design, operations): + created.extend(operations) + + monkeypatch.setattr(adapter, '_execute_new_batch', create) + send( + adapter, + 'variants.table.save', + columns=table['columns'], + variants=[row], + newParameters=pending, + ) + stored = json.loads(design.attributes.value) + assert [op.name for op in created] == ['beam'] + assert [c['name'] for c in stored['columns']] == ['width'] + assert stored['variants'][0]['parameters'][0]['value'] == 2.5 + assert not calls + + +def test_table_stores_derived_native_units_in_fusion_database_units(model): + adapter, design, params, calls = model + params[0].unit, params[0].expression, params[0].value = 'mm^2', '10 mm^2', 0.1 + table = table_save(adapter, params[:1], ('20 mm^2',)) + assert table['variants'][0]['parameters'][0]['value'] == 0.2 diff --git a/tests/unit/test_text_parameters.py b/tests/unit/test_text_parameters.py index 7a7fb64..d1a49d5 100644 --- a/tests/unit/test_text_parameters.py +++ b/tests/unit/test_text_parameters.py @@ -142,7 +142,23 @@ def test_text_variant_schema_roundtrips_empty_and_exact_values(): ], } ] - assert decode_variants(encode_variants(variants)) == variants + assert ( + decode_variants( + encode_variants( + variants, + [ + dict( + kind='parameter', + **{ + key: variants[0]['parameters'][0][key] + for key in ('name', 'entityToken', 'unit') + }, + ) + ], + ) + ) + == variants + ) assert values_match('a b', 'a b') assert not values_match('a b', 'a b') assert not values_match('1', 1) diff --git a/tests/unit/test_variants.py b/tests/unit/test_variants.py index af157ef..c85125f 100644 --- a/tests/unit/test_variants.py +++ b/tests/unit/test_variants.py @@ -2,7 +2,13 @@ import pytest -from Paramood.core.variants import decode_variants, encode_variants, values_match, variants_token +from Paramood.core.variants import ( + decode_variants, + encode_variants, + values_match, + variants_token, + decode_variant_table, +) def variant(): @@ -21,15 +27,19 @@ def variant(): } +def columns(): + return [{'kind': 'parameter', 'name': 'width', 'entityToken': 'token', 'unit': 'mm'}] + + def test_roundtrip_unicode_and_many_variants(): variants = [{**variant(), 'id': str(index), 'name': str(index)} for index in range(1000)] - assert decode_variants(encode_variants(variants)) == variants + assert decode_variants(encode_variants(variants, columns())) == variants assert decode_variants('') == [] - assert variants_token('') != variants_token(encode_variants([])) + assert variants_token('') != variants_token(encode_variants([], [])) @pytest.mark.parametrize( - 'data', [None, [], {}, {'version': 2, 'variants': []}, {'version': 1, 'variants': [{}]}] + 'data', [None, [], {}, {'version': 1, 'variants': []}, {'version': 1, 'variants': [{}]}] ) def test_invalid_data_is_not_treated_as_empty(data): with pytest.raises(ValueError): @@ -51,10 +61,35 @@ def test_invalid_records_rejected(mutation): else: item['parameters'][0]['entityToken'] = '' with pytest.raises(ValueError): - encode_variants(items) + encode_variants(items, columns()) def test_numeric_comparison_has_small_tolerance_and_rejects_nan(): assert values_match(1.00000000001, 1) assert not values_match(1.01, 1) assert not values_match(float('nan'), 1) + + +def test_table_requires_every_row_to_have_the_same_ordered_set(): + item = variant() + item['parameters'] = [] + with pytest.raises(ValueError, match='same ordered'): + encode_variants([item], columns()) + + +def test_feature_only_variants_and_interleaved_column_order_round_trip(): + feature = {'kind': 'feature', 'name': 'Cut', 'entityToken': 'cut'} + item = variant() + item['features'] = [{'name': 'Cut', 'entityToken': 'cut', 'enabled': False}] + configured = [feature] + columns() + raw = encode_variants([item], configured) + assert decode_variant_table(raw)['columns'] == configured + assert not decode_variants(raw)[0]['features'][0]['enabled'] + item['parameters'] = [] + assert decode_variants(encode_variants([item], [feature])) == [item] + + +def test_no_legacy_format_or_migration(): + with pytest.raises(ValueError, match='Unsupported'): + decode_variant_table(json.dumps({'version': 1, 'variants': [variant()]})) + assert decode_variant_table('') == {'version': 2, 'columns': [], 'variants': []}