/// /** * DIAGNOSTIC PATTERN: Understanding Cell.get() array access behavior * * This pattern helps us understand what happens when we: * 1. Call items.get()[index] * 2. Set selectedItem to that value * 3. Check if it creates links/aliases vs copies */ import { Cell, Default, handler, NAME, pattern, UI } from "commontools"; interface Item { title: string; value: number; } interface DiagInput { items: Default; selectedItem: Default; log: Default; } // Add item handler const addItem = handler; log: Cell }>( (_, { items, log }) => { const newItem: Item = { title: `Item-${Date.now()}`, value: Math.floor(Math.random() * 100), }; items.push(newItem); log.push(`Added item: ${newItem.title}`); }, ); // Select item by index - logs what we're doing const selectByIndex = handler< unknown, { items: Cell; selectedItem: Cell; log: Cell; index: number; } >( (_, { items, selectedItem, log, index }) => { const itemsArray = items.get(); log.push(`items.get() returned array of length: ${itemsArray.length}`); const targetItem = itemsArray[index]; log.push(`itemsArray[${index}] = ${JSON.stringify(targetItem)}`); log.push(`typeof targetItem: ${typeof targetItem}`); log.push(`targetItem constructor: ${targetItem?.constructor?.name}`); // Check if it has special symbols const symbols = Object.getOwnPropertySymbols(targetItem || {}); log.push(`Symbols on targetItem: ${symbols.length}`); // Now set it selectedItem.set(targetItem); log.push(`Called selectedItem.set(targetItem)`); // Read back const readBack = selectedItem.get(); log.push(`selectedItem.get() = ${JSON.stringify(readBack)}`); // Check items again const itemsAfter = items.get(); log.push(`items after set: ${JSON.stringify(itemsAfter)}`); }, ); // Clear selection const clearSelection = handler< unknown, { selectedItem: Cell; log: Cell } >( (_, { selectedItem, log }) => { selectedItem.set(null); log.push("Cleared selection"); }, ); // Clear log const clearLog = handler }>( (_, { log }) => { log.set([]); }, ); export default pattern( ({ items, selectedItem, log }) => { return { [NAME]: "Cell.equals Diagnostic", [UI]: ( Cell.equals() Diagnostic Add Item Clear Selection Clear Log Items ({items.length}): {items.map((item, index) => ( [{index}] {item.title}: {item.value} Select ))} Selected Item: {JSON.stringify(selectedItem, null, 2)} Log: {log.map((entry) => ( {entry} ))} ), items, selectedItem, log, }; }, );
{JSON.stringify(selectedItem, null, 2)}