# DSS Principles Summary

**Complete guide to all coding principles, architectural decisions, and best practices for DSS development.**

Last Updated: 2025-12-06
Status: ✅ Complete (Grade A with accessibility focus)

---

## Quick Reference

### Core Principles (Pick 3 to Remember)

1. **Single Source of Truth** - Design tokens are the canonical representation
2. **Atomic Composition** - 5-level hierarchy (Tokens→Primitives→Components→Layouts→Views)
3. **Keyboard First** - All UI must be accessible via keyboard

---

## Organizational Structure

### By Topic

#### 🏗️ Architecture

- **Monolithic Core Design**: Single source of truth with immutable core
- **Layered Architecture**: Clear separation between storage, domain, ingestion, analysis, generation, and API
- **External Translation Pattern**: External systems translate TO DSS, not reverse
- **Architectural Patterns**: Strategy, Abstract Base Classes, Data Classes, Dependency Injection

**Reference**: [`DSS_CODING_PRINCIPLES.md` Section 1](./DSS_CODING_PRINCIPLES.md#1-architectural-principles)

#### 💻 Code Quality

- **Python Style**: PEP 8 with 4-space indent, snake_case, 100-char lines
- **Error Handling**: Explicit exceptions, meaningful messages, no silent failures
- **Async Patterns**: All I/O must be async via asyncio
- **Docstrings**: All modules, classes, and public functions documented
- **Type Hints**: 100% coverage for public APIs, 80% overall target
- **Comments**: Explain WHY not WHAT, mark TODOs with urgency

**Reference**: [`DSS_CODING_PRINCIPLES.md` Section 2](./DSS_CODING_PRINCIPLES.md#2-code-quality-standards)

#### 🏛️ 7-Layer Architecture

DSS has seven logical layers:

1. **Core** - Database, configuration, schemas, event bus
2. **Ingestion** - Token extraction from CSS, Figma, JSON, Tailwind
3. **Validation** - Schema checking, linting, error detection
4. **State** - Token models, stores, data flow
5. **Processing** - Transformations, analysis, style-dictionary
6. **Presentation** - Admin UI, Storybook, documentation
7. **Integration** - APIs, MCP tools, webhooks, CLI

**Design Principle**: Each layer has clear responsibility and health indicators

**Reference**: [Architecture Overview](./architecture/OVERVIEW.md)

#### ⌨️ Keyboard Accessibility

- **Tabindex Management**: Use `tabindex="0"` on all interactive elements
- **Focus Styling**: `:focus-visible` CSS for keyboard users, 3:1 contrast
- **Keyboard Handlers**: Enter/Space/Escape/Arrows all work as expected
- **ARIA Attributes**: Label all elements, indicate state, describe errors
- **Web Components**: Proper lifecycle management, focus delegation

**Key Metric**: Application fully operable via keyboard only

**Reference**: [`DSS_CODING_PRINCIPLES.md` Section 4](./DSS_CODING_PRINCIPLES.md#4-keyboard-accessibility)

#### 🔒 Security

- **No Global State**: Never expose classes to `window` global
- **HTML Sanitization**: Always use DOMPurify before inserting HTML
- **No Monkey-Patching**: Never override native APIs (fetch, etc.)
- **Input Validation**: Validate at system boundaries only
- **Environment Variables**: Secrets via env vars, never hardcoded

**Reference**: [`DSS_CODING_PRINCIPLES.md` Sections 5-6](./DSS_CODING_PRINCIPLES.md#5-security-guidelines)

#### 🎭 Web Components

- **Lifecycle Management**: Implement `connectedCallback()` and `disconnectedCallback()`
- **Event Listener Storage**: Store handlers on `this` for cleanup
- **Attribute Observation**: Include ALL affecting attributes in `observedAttributes()`
- **Focus Delegation**: Delegate focus to internal focusable elements
- **ARIA Support**: Pass through ARIA attributes to internal elements

**Reference**: [`DSS_CODING_PRINCIPLES.md` Section 5](./DSS_CODING_PRINCIPLES.md#5-web-component-standards)

#### 🎯 Event Handling & Memory

- **Event Delegation**: Use document-level listeners, not per-element
- **Guard Flags**: Prevent re-attachment with flags (`hasActionListener`)
- **Data-Driven Actions**: Use `data-action` attributes instead of `onclick`
- **Listener Cleanup**: Remove all listeners in `disconnectedCallback()`
- **No Accumulation**: Same listener only attached once

**Problem Solved**: Memory leaks from event listener accumulation in SPAs

**Reference**: [`DSS_CODING_PRINCIPLES.md` Section 7](./DSS_CODING_PRINCIPLES.md#7-event-handling--memory-management)

---

## Principles by Category

### If You're Building a Component...

**Checklist**:
- [ ] All interactive elements have `tabindex="0"`
- [ ] Icon buttons have `aria-label`
- [ ] Toggles have `aria-expanded`
- [ ] Form errors have `aria-invalid` and `aria-describedby`
- [ ] `:focus-visible` CSS for keyboard users
- [ ] Keyboard shortcuts work (Enter, Space, Escape)
- [ ] `disconnectedCallback()` removes all listeners
- [ ] Event listeners stored as `this.handler`
- [ ] No HTML inserted via `innerHTML` without sanitization
- [ ] No functions exposed to `window`
- [ ] Works with keyboard-only navigation
- [ ] Works with screen readers

**Reference**: [`DSS_CODING_PRINCIPLES.md` Accessibility Checklist](./DSS_CODING_PRINCIPLES.md#summary-accessibility-checklist)

### If You're Designing an API Endpoint...

**Checklist**:
- [ ] Input validation on all parameters
- [ ] Clear error messages (no generic 500 errors)
- [ ] Async/await for all I/O
- [ ] Proper HTTP status codes
- [ ] Rate limiting considered
- [ ] CORS configured if needed
- [ ] Documented in docstring

### If You're Adding a New Token Source...

**Checklist**:
- [ ] Extends `TokenSource` abstract base class
- [ ] Implements `extract()` async method
- [ ] Returns `TokenCollection` with normalized tokens
- [ ] Handles all error cases gracefully
- [ ] Zero data loss during parsing
- [ ] Tests for edge cases (empty files, malformed input)

---

## Before You Commit

### Code Review Checklist

- [ ] All tests pass
- [ ] Docstrings added for new functions/classes
- [ ] Type hints for new code (100% for public APIs)
- [ ] No new bare `except:` statements
- [ ] Error messages are clear and helpful
- [ ] No hardcoded secrets (use env vars)
- [ ] No console.log/print statements left
- [ ] README/docs updated if needed
- [ ] Keyboard navigation works
- [ ] Accessible to screen readers
- [ ] No global state pollution

### Accessibility Review Checklist

- [ ] Keyboard users can access all features
- [ ] Screen reader users get proper labels
- [ ] Focus indicator is visible (3:1 contrast)
- [ ] Color is not only way to convey information
- [ ] All images have alt text
- [ ] Form errors are clearly described
- [ ] No auto-playing audio/video

---

## Important Files

### Documentation

- **[DSS_CODING_PRINCIPLES.md](./DSS_CODING_PRINCIPLES.md)** - Complete principles guide
- **[ARCHITECTURE_REVIEW.md](./ARCHITECTURE_REVIEW.md)** - Architecture decisions
- **[CODE_QUALITY.md](./CODE_QUALITY.md)** - Quality metrics and standards
- **[GLOSSARY.md](./GLOSSARY.md)** - Corporate terminology
- **[Architecture Overview](./architecture/OVERVIEW.md)** - 7-layer system
- **[First Principles](./principles/FIRST_PRINCIPLES.md)** - 7 foundational truths
- **[Atomic Hierarchy](./principles/ATOMIC_HIERARCHY.md)** - 5-level composition

### Implementation Examples

- **Web Components**: `/admin-ui/js/components/ds-button.js` (keyboard + ARIA)
- **Web Components**: `/admin-ui/js/components/ds-input.js` (form validation + accessibility)
- **Event Delegation**: `/admin-ui/js/core/app.js` (lines 2202-2484)
- **Keyboard Handlers**: `/admin-ui/js/core/app.js` (lines 2486-2533)
- **Sanitization**: `/admin-ui/js/core/sanitizer.js` (DOMPurify integration)
- **Focus CSS**: `/admin-ui/css/components.css` (lines 661-709)
- **Accessibility Utilities**: `/admin-ui/css/base.css` (lines 278-293)

---

## Learning Path

### For New Contributors

1. **Start Here**: Read [PRINCIPLES_SUMMARY.md](./PRINCIPLES_SUMMARY.md) (this file) - 5 min
2. **Terminology**: Read [GLOSSARY.md](./GLOSSARY.md) - 5 min
3. **First Principles**: Read [First Principles](./principles/FIRST_PRINCIPLES.md) - 10 min
4. **Architecture**: Read [Architecture Overview](./architecture/OVERVIEW.md) - 10 min
5. **Atomic Hierarchy**: Read [Atomic Hierarchy](./principles/ATOMIC_HIERARCHY.md) - 10 min
6. **Code Quality**: Review [CODE_QUALITY.md](./CODE_QUALITY.md) - 10 min
7. **Complete Guide**: Read [DSS_CODING_PRINCIPLES.md](./DSS_CODING_PRINCIPLES.md) - 30 min

**Total Time**: ~80 minutes for complete understanding

### For Quick Reference

- **"How do I add a button?"** → See Web Components section
- **"How should I handle errors?"** → See Code Quality section
- **"Is my keyboard support right?"** → See Keyboard Accessibility checklist
- **"Where does this go architecturally?"** → See Layered Architecture section
- **"How do I keep the system healthy?"** → See Observable Health in First Principles

---

## Key Statistics

**Current State** (as of 2025-12-06):

| Metric | Value | Target |
|--------|-------|--------|
| Code Quality Grade | A | A+ |
| Type Hints Coverage | 60% | 100% |
| Test Coverage | Basic | 80% |
| Accessibility Compliance | WCAG 2.1 AA | WCAG 2.1 AAA |
| Documentation | Excellent | Excellent |
| Keyboard Accessibility | Complete | Fully Tested |
| ARIA Support | Comprehensive | Comprehensive |

---

## Frequently Asked Questions

### "Can I use `window.myVariable` for debugging?"

Only in development mode, and always check the environment first:

```javascript
if (process.env.NODE_ENV === 'development') {
  window.__DSS_DEBUG = { ... };
}
```

### "Should I write comments for my code?"

Comments should explain WHY, not WHAT. Code should be clear enough to explain itself. Only comment:
- Complex algorithms or business logic
- Non-obvious decisions
- TODO items with urgency level

### "What if I don't have tests?"

All new public functions should have tests. Start with:
- Happy path test
- Error case test
- Edge case test (if applicable)

### "How do I handle accessibility for complex components?"

1. Use semantic HTML elements when possible
2. Add ARIA attributes for dynamic state
3. Test with keyboard navigation (Tab/Shift-Tab)
4. Test with screen reader (NVDA, JAWS, VoiceOver)
5. Check color contrast (3:1 minimum, 4.5:1 for text)

### "Do I need to support IE11?"

No. Browser support:
- ✅ Chrome/Edge (last 2 versions)
- ✅ Firefox (last 2 versions)
- ✅ Safari (last 2 versions)
- ❌ IE11 (no longer supported)

---

## Governance

### Pull Request Requirements

All PRs must demonstrate:
1. ✅ Tests passing
2. ✅ Code quality maintained (no new violations)
3. ✅ Accessibility checklist passed
4. ✅ Documentation updated
5. ✅ At least one approval from maintainer

### Decision Log

Major architectural decisions and their rationale are documented in [ARCHITECTURE_REVIEW.md](./ARCHITECTURE_REVIEW.md).

### Contributing

When adding new principles:
1. Update [DSS_CODING_PRINCIPLES.md](./DSS_CODING_PRINCIPLES.md) with complete detail
2. Add summary to this file
3. Add implementation example
4. Create or update relevant checklist
5. Link to all related docs

---

## External References

- **[WCAG 2.1 Guidelines](https://www.w3.org/WAI/WCAG21/quickref/)** - Accessibility standards
- **[ARIA Authoring Practices](https://www.w3.org/WAI/ARIA/apg/)** - Accessible component patterns
- **[Web Components Best Practices](https://web.dev/articles/custom-elements-best-practices)** - Component lifecycle
- **[PEP 8](https://peps.python.org/pep-0008/)** - Python style guide
- **[Clean Code Python](https://github.com/zedr/clean-code-python)** - Code quality patterns

---

## Summary

The Design System Server is a **A-grade, production-ready system** with:

✅ **Strong architecture** - Monolithic core, clear layering, separation of concerns
✅ **Excellent code quality** - Type hints, documentation, error handling
✅ **Complete accessibility** - Keyboard navigation, ARIA, screen reader support
✅ **Secure by design** - No global state, HTML sanitization, no monkey-patching
✅ **Health monitoring** - Observable health at every layer
✅ **Clear governance** - Review checklists, principles documentation, examples

**Next Steps**:
- Increase test coverage from "basic" to 80%
- Add type hints to remaining 40% of codebase
- Create integration tests for Figma API
- Monitor accessibility compliance (target: AAA)

---

**Remember**: Code is read far more often than it's written. Write for readability, accessibility, and maintainability.
