Skip to content
Open

Canvas #1635

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ parameters:
- name: brainstorm
type: string
default: brainstorm
- name: canvas
type: string
default: canvas
- name: item-counter
type: string
default: item-counter
Expand Down
10 changes: 10 additions & 0 deletions canvas/.editorconfig
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't think we use these any more.

Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
root = true

[*]
end_of_line = lf
insert_final_newline = true

[*.{js,json,yml}]
charset = utf-8
indent_style = space
indent_size = 2
5 changes: 5 additions & 0 deletions canvas/.env.defaults
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# .env.defaults should not contain private information. Create a .env file locally to override these values.
AZURE_TENANT_ID=<tenant-id>
AZURE_ORDERER=<orderer-url>
AZURE_FUNCTION_TOKEN_PROVIDER_URL=<token-provider-url>
FLUID_CLIENT=azure
36 changes: 36 additions & 0 deletions canvas/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*!
* Copyright (c) Microsoft Corporation and contributors. All rights reserved.
* Licensed under the MIT License.
*/

module.exports = {
"env": {
"browser": true,
"es2021": true
},
"extends": [
"eslint:recommended",
"plugin:react/recommended",
"plugin:@typescript-eslint/recommended"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": [
"react",
"@typescript-eslint"
],
"settings": {
"react": {
"version": "detect",
},
},
"rules": {
"no-undef": "off",
}
}
4 changes: 4 additions & 0 deletions canvas/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/.yarn/** linguist-vendored
/.yarn/releases/* binary
/.yarn/plugins/**/* binary
/.pnp.* binary linguist-generated
106 changes: 106 additions & 0 deletions canvas/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
# Dependencies
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*

# Other package manager files (using npm)
yarn.lock
pnpm-lock.yaml
.yarn/
.pnpm/
.pnp.*

# Build outputs
dist/
build/
*.tsbuildinfo

# Environment variables
.env
.env.local
.env.development.local
.env.test.local
.env.production.local

# IDE and editor files
# Keep .vscode/settings.json for project-specific VS Code settings
# but ignore personal VS Code configurations
.vscode/launch.json
.vscode/tasks.json
.vscode/.ropeproject
.vscode/extensions.json
.idea/
*.swp
*.swo
*~

# OS generated files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db

# Logs
logs/
*.log

# Runtime data
pids/
*.pid
*.seed
*.pid.lock

# Coverage directory used by tools like istanbul
coverage/
*.lcov

# nyc test coverage
.nyc_output

# Dependency directories
jspm_packages/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Vite
.vite/

# Playwright
test-results/
playwright-report/
playwright/.cache/

# Azure Functions
local.settings.json
.azure/

# Nix
shell.nix
1 change: 1 addition & 0 deletions canvas/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node-linker=hoisted
1 change: 1 addition & 0 deletions canvas/.nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
v20
13 changes: 13 additions & 0 deletions canvas/.prettierrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/*!
* Copyright (c) Microsoft Corporation and contributors. All rights reserved.
* Licensed under the MIT License.
*/

module.exports = {
semi: true,
trailingComma: "es5",
singleQuote: false,
printWidth: 100,
tabWidth: 4,
useTabs: true,
};
5 changes: 5 additions & 0 deletions canvas/.vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"cSpell.words": ["insertable"],
}
9 changes: 9 additions & 0 deletions canvas/CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Microsoft Open Source Code of Conduct

This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).

Resources:

- [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/)
- [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
- Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns
124 changes: 124 additions & 0 deletions canvas/EVENT_SUBSCRIPTION_CONSOLIDATION.md
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks like a dev doc - maybe move this and similar ones into a docs folder or delete? I think they'll be confusing to people reading the example.

Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
# Event Subscription Consolidation Summary

## Problem Identified

The codebase had repetitive event subscription patterns scattered throughout multiple React components, particularly:

1. **Selection state management**: Components repeatedly subscribed to selection events with similar patterns
2. **Button state management**: Multiple buttons used identical logic to enable/disable based on selections
3. **DOM event listeners**: Repetitive patterns for adding/removing event listeners with cleanup
4. **Fluid Framework events**: Similar subscription patterns for tree commits and presence updates

## Solution Implemented

### Created Unified Event Subscription Utility (`src/utils/eventSubscriptions.ts`)

**Key Features:**

- **Type-safe event handling** with proper cleanup management
- **Selection-based state synchronization** helpers
- **Automatic subscription/unsubscription** lifecycle management
- **Performance optimized** with minimal re-renders using useRef patterns
- **Flexible and reusable** across different component types

**Main Utilities Created:**

1. **`useEventSubscription`** - Generic event subscription with automatic cleanup
2. **`useSelectionSync`** - Selection state synchronization for UI updates
3. **`useSelectionBasedButtonState`** - Button disabled state based on selection criteria
4. **`useTableButtonState`** - Specialized utility for table button components
5. **`useMultiTypeSelectionSync`** - Manages multiple selection types (row, column, cell)
6. **`useDOMEventListener`** - DOM event listeners with cleanup
7. **`useMultipleDOMEventListeners`** - Multiple DOM event listeners at once

## Implementation Examples

### Before (Repetitive Pattern):

```tsx
const [disabled, setDisabled] = React.useState(getSelected(selection, "row").length === 0);
useEffect(() => {
const unsubscribe = selection.events.on("localUpdated", () => {
if (getSelected(selection, "row").length === 0) {
setDisabled(true);
} else {
setDisabled(false);
}
});
return unsubscribe;
}, []);
```

### After (Unified Utility):

```tsx
const [disabled, setDisabled] = React.useState(true);
useTableButtonState(selection, ["row"], setDisabled);
```

## Components Updated

### 1. Table Button Components (`tablebuttonux.tsx`)

- **MoveSelectedRowsButton**: Consolidated repetitive selection subscription logic
- **MoveSelectedColumnsButton**: Multi-type selection logic simplified
- **DeleteSelectedRowsButton**: Button state management unified

### 2. Main UX Component (`ux.tsx`)

- **Item selection sync**: Replaced manual subscription with `useSelectionSync`
- **Table selection sync**: Used `useMultiTypeSelectionSync` for row/column state management

## Benefits Achieved

### 1. **Code Reduction**

- Eliminated ~15-20 lines of repetitive code per component
- Consolidated 6+ similar patterns into reusable utilities

### 2. **Consistency**

- Standardized event subscription patterns across codebase
- Consistent cleanup and lifecycle management

### 3. **Type Safety**

- Proper TypeScript integration with selection managers
- Compile-time verification of event handling

### 4. **Performance**

- Optimized with useRef to prevent unnecessary re-renders
- Automatic cleanup prevents memory leaks

### 5. **Maintainability**

- Single source of truth for event subscription logic
- Easy to update subscription patterns in one place
- Clear separation of concerns

## Architecture Improvement

The event subscription utilities follow the same successful pattern as the previous `ContentHandler` consolidation:

1. **Identified repetitive patterns** across multiple components
2. **Created centralized utilities** with proper abstraction
3. **Maintained type safety** and performance
4. **Provided clear migration path** from old to new patterns

## Testing & Validation

- ✅ **Build Success**: All TypeScript compilation passes
- ✅ **No Runtime Errors**: Proper cleanup and subscription management
- ✅ **Type Safety**: Full TypeScript support maintained
- ✅ **Backwards Compatible**: Existing functionality preserved

## Next Steps

The event subscription utilities can be further extended to consolidate:

1. **Presence manager subscriptions** (user updates, attendee changes)
2. **Canvas/pointer event patterns** (drag, resize operations)
3. **Container event subscriptions** (save, dispose, connection state)

This consolidation significantly improves code maintainability and provides a solid foundation for future event-driven features.
21 changes: 21 additions & 0 deletions canvas/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
Copyright (c) Microsoft Corporation and contributors. All rights reserved.

MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Loading