#!/usr/bin/env python3 """ Demonstration of the new create_and_add_to pattern in pyWebLayout. This script shows how the pattern enables automatic style and language inheritance throughout the document hierarchy without copying strings - using object references instead. """ # Mock the style system for this demonstration class MockFont: def __init__(self, family="Arial", size=12, language="en-US", background="white"): self.family = family self.size = size self.language = language self.background = background def __str__(self): return f"Font(family={self.family}, size={self.size}, lang={self.language}, bg={self.background})" # Import the abstract classes from pyWebLayout.abstract import ( Document, Paragraph, Heading, HeadingLevel, Quote, HList, ListStyle, Table, TableRow, TableCell, Word, FormattedSpan ) def demonstrate_create_and_add_pattern(): """Demonstrate the create_and_add_to pattern with style inheritance.""" print("=== pyWebLayout create_and_add_to Pattern Demonstration ===\n") # Create a document with a default style document_style = MockFont(family="Georgia", size=14, language="en-US", background="white") doc = Document("Style Inheritance Demo", default_style=document_style) print(f"1. Document created with style: {document_style}") print(f" Document default style: {doc.default_style}\n") # Create a paragraph using the new pattern - it inherits the document's style para1 = Paragraph.create_and_add_to(doc) print(f"2. Paragraph created with inherited style: {para1.style}") print(f" Style object ID matches document: {id(para1.style) == id(doc.default_style)}") print(f" Number of blocks in document: {len(doc.blocks)}\n") # Create words using the paragraph's create_word method word1 = para1.create_word("Hello") word2 = para1.create_word("World") print(f"3. Words created with inherited paragraph style:") print(f" Word 1 '{word1.text}' style: {word1.style}") print(f" Word 2 '{word2.text}' style: {word2.style}") print(f" Style object IDs match paragraph: {id(word1.style) == id(para1.style)}") print(f" Word count in paragraph: {para1.word_count}\n") # Create a quote with a different style quote_style = MockFont(family="Times", size=13, language="en-US", background="lightgray") quote = Quote.create_and_add_to(doc, style=quote_style) print(f"4. Quote created with custom style: {quote.style}") print(f" Style object ID different from document: {id(quote.style) != id(doc.default_style)}") # Create a paragraph inside the quote - it inherits the quote's style quote_para = Paragraph.create_and_add_to(quote) print(f" Quote paragraph inherits quote style: {quote_para.style}") print(f" Style object ID matches quote: {id(quote_para.style) == id(quote.style)}\n") # Create a heading with specific styling heading_style = MockFont(family="Arial Black", size=18, language="en-US", background="white") heading = Heading.create_and_add_to(doc, HeadingLevel.H1, style=heading_style) print(f"5. Heading created with custom style: {heading.style}") # Add words to the heading heading.create_word("Chapter") heading.create_word("One") print(f" Heading words inherit heading style:") for i, word in heading.words(): print(f" - Word {i}: '{word.text}' with style: {word.style}") print() # Create a list with inherited style list_obj = HList.create_and_add_to(doc, ListStyle.UNORDERED) print(f"6. List created with inherited document style: {list_obj.default_style}") # Create list items that inherit from the list item1 = list_obj.create_item() item2 = list_obj.create_item() print(f" List item 1 style: {item1.style}") print(f" List item 2 style: {item2.style}") print(f" Both inherit from list: {id(item1.style) == id(list_obj.default_style)}") # Create paragraphs in list items item1_para = item1.create_paragraph() item2_para = item2.create_paragraph() print(f" Item 1 paragraph style: {item1_para.style}") print(f" Item 2 paragraph style: {item2_para.style}") print(f" Both inherit from list item: {id(item1_para.style) == id(item1.style)}\n") # Create a table with inherited style table = Table.create_and_add_to(doc, "Example Table") print(f"7. Table created with inherited document style: {table.style}") # Create table rows and cells header_row = table.create_row("header") header_cell1 = header_row.create_cell(is_header=True) header_cell2 = header_row.create_cell(is_header=True) print(f" Header row style: {header_row.style}") print(f" Header cell 1 style: {header_cell1.style}") print(f" Header cell 2 style: {header_cell2.style}") # Create paragraphs in cells cell1_para = header_cell1.create_paragraph() cell2_para = header_cell2.create_paragraph() print(f" Cell 1 paragraph style: {cell1_para.style}") print(f" Cell 2 paragraph style: {cell2_para.style}") # Add words to cell paragraphs cell1_para.create_word("Name") cell2_para.create_word("Age") print(f" All styles inherit properly through the hierarchy\n") # Create a formatted span to show style inheritance span = para1.create_span() span_word = span.add_word("formatted") print(f"8. FormattedSpan and Word inheritance:") print(f" Span style: {span.style}") print(f" Span word style: {span_word.style}") print(f" Both inherit from paragraph: {id(span.style) == id(para1.style)}") print() # Demonstrate the object reference pattern vs string copying print("9. Object Reference vs String Copying Demonstration:") print(" - All child elements reference the SAME style object") print(" - No string copying occurs - efficient memory usage") print(" - Changes to parent style affect all children automatically") print() # Show the complete hierarchy print("10. Document Structure Summary:") print(f" Document blocks: {len(doc.blocks)}") for i, block in enumerate(doc.blocks): if hasattr(block, 'word_count'): print(f" - Block {i}: {type(block).__name__} with {block.word_count} words") elif hasattr(block, 'item_count'): print(f" - Block {i}: {type(block).__name__} with {block.item_count} items") elif hasattr(block, 'row_count'): counts = block.row_count print(f" - Block {i}: {type(block).__name__} with {counts['total']} total rows") else: print(f" - Block {i}: {type(block).__name__}") print("\n=== Pattern Benefits ===") print("✓ Automatic style inheritance throughout document hierarchy") print("✓ Object references instead of string copying (memory efficient)") print("✓ Consistent API pattern across all container/child relationships") print("✓ Language and styling properties inherited as objects") print("✓ Easy to use fluent interface for document building") print("✓ Type safety with proper return types") if __name__ == "__main__": try: demonstrate_create_and_add_pattern() except ImportError as e: print(f"Import error: {e}") print("Note: This demo requires the pyWebLayout abstract classes") print("Make sure the pyWebLayout package is in your Python path") except Exception as e: print(f"Error during demonstration: {e}") import traceback traceback.print_exc()