docs: add React and Angular focused comp ref example

This commit is contained in:
Corbin Crutchley
2024-01-15 21:14:44 -08:00
parent c93f3acb23
commit 34a8af5fd0
15 changed files with 15340 additions and 4 deletions

View File

@@ -9,8 +9,7 @@ import {
Input,
OnDestroy,
Output,
QueryList,
ViewChildren,
ViewChild,
} from "@angular/core";
import { NgIf } from "@angular/common";
@@ -45,7 +44,7 @@ import { NgIf } from "@angular/common";
`,
})
class ContextMenuComponent implements AfterViewInit, OnDestroy {
@ViewChildren("contextMenu") contextMenu!: QueryList<ElementRef<HTMLElement>>;
@ViewChild("contextMenu") contextMenu!: ElementRef<HTMLElement>;
@Input() isOpen!: boolean;
@Input() x!: number;
@@ -54,7 +53,7 @@ class ContextMenuComponent implements AfterViewInit, OnDestroy {
@Output() close = new EventEmitter();
closeIfOutsideOfContext = (e: MouseEvent) => {
const contextMenuEl = this.contextMenu?.first?.nativeElement;
const contextMenuEl = this.contextMenu?.nativeElement;
if (!contextMenuEl) return;
const isClickInside = contextMenuEl.contains(e.target as HTMLElement);
if (isClickInside) return;

View File

@@ -0,0 +1,42 @@
# See http://help.github.com/ignore-files/ for more about ignoring files.
# Compiled output
/dist
/tmp
/out-tsc
/bazel-out
# Node
/node_modules
npm-debug.log
yarn-error.log
# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# Miscellaneous
/.angular/cache
.sass-cache/
/connect.lock
/coverage
/libpeerconnection.log
testem.log
/typings
# System files
.DS_Store
Thumbs.db

View File

@@ -0,0 +1,71 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"DemoApp": {
"projectType": "application",
"schematics": {},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/demo-app",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": ["zone.js"],
"tsConfig": "tsconfig.app.json",
"scripts": []
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"outputHashing": "all"
},
"development": {
"buildOptimizer": false,
"optimization": false,
"vendorChunk": true,
"extractLicenses": false,
"sourceMap": true,
"namedChunks": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"browserTarget": "DemoApp:build:production"
},
"development": {
"browserTarget": "DemoApp:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "DemoApp:build"
}
}
}
}
}
}

View File

@@ -0,0 +1,31 @@
{
"name": "@ffg-fundamentals/angular-focused-comp-ref-68",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"dev": "ng serve",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development"
},
"private": true,
"dependencies": {
"@angular/animations": "^16.2.0",
"@angular/common": "^16.2.0",
"@angular/compiler": "^16.2.0",
"@angular/core": "^16.2.0",
"@angular/forms": "^16.2.0",
"@angular/platform-browser": "^16.2.0",
"@angular/platform-browser-dynamic": "^16.2.0",
"@angular/router": "^16.2.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.13.0"
},
"devDependencies": {
"@angular-devkit/build-angular": "^16.2.10",
"@angular/cli": "^16.2.10",
"@angular/compiler-cli": "^16.2.0",
"typescript": "~5.1.3"
}
}

View File

@@ -0,0 +1,8 @@
<html>
<head>
<title>Angular Focused Comp Ref - Example #68 - FFG Fundamentals</title>
</head>
<body>
<app-root></app-root>
</body>
</html>

View File

@@ -0,0 +1,122 @@
import "zone.js";
import { bootstrapApplication } from "@angular/platform-browser";
import {
AfterViewInit,
Component,
ElementRef,
EventEmitter,
Input,
OnDestroy,
Output,
QueryList,
ViewChild,
ViewChildren,
} from "@angular/core";
import { NgIf } from "@angular/common";
@Component({
selector: "context-menu",
standalone: true,
imports: [NgIf],
template: `
<div
*ngIf="isOpen"
tabIndex="0"
#contextMenu
[style]="
'
position: fixed;
top: ' +
y +
'px;
left: ' +
x +
'px;
background: white;
border: 1px solid black;
border-radius: 16px;
padding: 1rem;
'
"
>
<button (click)="close.emit()">X</button>
This is a context menu
</div>
`,
})
class ContextMenuComponent implements AfterViewInit, OnDestroy {
@ViewChild("contextMenu") contextMenu!: ElementRef<HTMLElement>;
@Input() isOpen!: boolean;
@Input() x!: number;
@Input() y!: number;
@Output() close = new EventEmitter();
focus() {
this.contextMenu?.nativeElement?.focus();
}
closeIfOutsideOfContext = (e: MouseEvent) => {
const contextMenuEl = this.contextMenu?.nativeElement;
if (!contextMenuEl) return;
const isClickInside = contextMenuEl.contains(e.target as HTMLElement);
if (isClickInside) return;
this.close.emit();
};
ngAfterViewInit() {
document.addEventListener("click", this.closeIfOutsideOfContext);
}
ngOnDestroy() {
document.removeEventListener("click", this.closeIfOutsideOfContext);
}
}
@Component({
selector: "app-root",
standalone: true,
imports: [NgIf, ContextMenuComponent],
template: `
<div style="margin-top: 5rem; margin-left: 5rem">
<div #contextOrigin (contextmenu)="open($event)">Right click on me!</div>
</div>
<context-menu
#contextMenu
(close)="close()"
[isOpen]="isOpen"
[x]="mouseBounds.x"
[y]="mouseBounds.y"
/>
`,
})
class AppComponent {
@ViewChild("contextMenu") contextMenu!: ContextMenuComponent;
isOpen = false;
mouseBounds = {
x: 0,
y: 0,
};
close() {
this.isOpen = false;
}
open(e: MouseEvent) {
e.preventDefault();
this.isOpen = true;
this.mouseBounds = {
x: e.clientX,
y: e.clientY,
};
setTimeout(() => {
this.contextMenu.focus();
}, 0);
}
}
bootstrapApplication(AppComponent);

View File

@@ -0,0 +1,10 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"files": ["src/main.ts"],
"include": ["src/**/*.d.ts"]
}

View File

@@ -0,0 +1,30 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"experimentalDecorators": true,
"moduleResolution": "node",
"importHelpers": true,
"target": "ES2022",
"module": "ES2022",
"useDefineForClassFields": false,
"lib": ["ES2022", "dom"]
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}

View File

@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@@ -0,0 +1,9 @@
<html>
<head>
<title>React Focused Comp Ref - Example #68 - FFG Fundamentals</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>

View File

@@ -0,0 +1,19 @@
{
"name": "@ffg-fundamentals/react-focused-comp-ref-68",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.0.4",
"vite": "^4.4.9"
}
}

View File

@@ -0,0 +1,94 @@
import { createRoot } from "react-dom/client";
import {
forwardRef,
useState,
useImperativeHandle,
useEffect,
useRef,
} from "react";
const ContextMenu = forwardRef(({ isOpen, x, y, onClose }, ref) => {
const [contextMenu, setContextMenu] = useState();
useImperativeHandle(ref, () => ({
focus: () => contextMenu && contextMenu.focus(),
}));
useEffect(() => {
if (!contextMenu) return;
const closeIfOutsideOfContext = (e) => {
const isClickInside = contextMenu.contains(e.target);
if (isClickInside) return;
onClose(false);
};
document.addEventListener("click", closeIfOutsideOfContext);
return () => document.removeEventListener("click", closeIfOutsideOfContext);
}, [contextMenu]);
if (!isOpen) return null;
return (
<div
ref={(el) => setContextMenu(el)}
tabIndex={0}
style={{
position: "fixed",
top: y,
left: x,
background: "white",
border: "1px solid black",
borderRadius: 16,
padding: "1rem",
}}
>
<button onClick={() => onClose()}>X</button>
This is a context menu
</div>
);
});
function App() {
const [mouseBounds, setMouseBounds] = useState({
x: 0,
y: 0,
});
const [isOpen, setIsOpen] = useState(false);
function onContextMenu(e) {
e.preventDefault();
setIsOpen(true);
setMouseBounds({
x: e.clientX,
y: e.clientY,
});
}
const contextMenuRef = useRef();
useEffect(() => {
if (isOpen) {
setTimeout(() => {
if (contextMenuRef.current) return;
contextMenuRef.current.focus();
}, 0);
}
}, [isOpen, mouseBounds]);
return (
<>
<div style={{ marginTop: "5rem", marginLeft: "5rem" }}>
<div onContextMenu={onContextMenu}>Right click on me!</div>
</div>
<ContextMenu
ref={contextMenuRef}
isOpen={isOpen}
onClose={() => setIsOpen(false)}
x={mouseBounds.x}
y={mouseBounds.y}
/>
</>
);
}
createRoot(document.getElementById("root")).render(<App />);

View File

@@ -0,0 +1,6 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
});