diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000..793ac7589e --- /dev/null +++ b/.dockerignore @@ -0,0 +1,46 @@ +# Node modules (will be installed in container) +node_modules +*/node_modules +**/node_modules + +# Build outputs +dist +**/dist +build +**/build +coverage +**/coverage +*.tsbuildinfo +**/*.tsbuildinfo + +# Development files +.git +.github +.vscode +*.log +# Note: We need yarn.lock and package-lock.json for dependency resolution +# *.lock + +# Docker +*.dockerignore +Dockerfile* +docker-compose* +.docker + +# Docker volumes +docker_data/ +docker_volumes/ + +# Development +.env.local +.env.development.local +.env.test.local +.env.production.local + +# Cypress +cypress/videos +cypress/screenshots + +# Misc +.DS_Store +Thumbs.db diff --git a/.env.example b/.env.example new file mode 100644 index 0000000000..69d4a88f84 --- /dev/null +++ b/.env.example @@ -0,0 +1,33 @@ +# Environment Variables for Docker Compose +# Copy this file to .env and modify as needed + +# Authentication Type (SNAuth or IdentityServer) +AUTH_TYPE=SNAuth + +# Node Environment +NODE_ENV=production + +# Ports +SENSENET_CLIENT_PORT=8080 +SENSENET_DEV_PORT=3000 + +# Development Settings (for hot reload) +CHOKIDAR_USEPOLLING=true +WATCHPACK_POLLING=true +DISABLE_VIEW_OPTIONS_MENU=false +WEBPACK_DEV_SERVER_CLIENT_WEB_SOCKET_URL=auto://0.0.0.0:0/ws + +# Database Settings (if using database service) +# DB_PASSWORD=YourPassword123! +# DB_NAME=SenseNet +# DB_USER=sa + +# Redis Settings (if using redis service) +# REDIS_PASSWORD= + +# Traefik Settings (if using traefik service) +# TRAEFIK_DOMAIN=sensenet.local + +# Backend API URL (if connecting to external backend) +# REACT_APP_SERVICE_URL=https://dev.demo.sensenet.com +# REACT_APP_IDENTITY_SERVER_URL=https://is.demo.sensenet.com diff --git a/.eslintrc.js b/.eslintrc.js index 623ff317fb..c55783cead 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -12,7 +12,7 @@ module.exports = { ], parser: '@typescript-eslint/parser', plugins: ['@typescript-eslint', 'react', 'cypress', 'jsdoc', 'import', 'react-hooks'], - env: { browser: true, node: true, es6: true, jest: true, 'cypress/globals': true }, + env: { browser: true, node: true, es6: true, 'cypress/globals': true }, parserOptions: { ecmaVersion: 6, sourceType: 'module', @@ -36,6 +36,9 @@ module.exports = { }, rules: { 'react/prop-types': 0, + 'no-unused-vars': 'off', + 'import/export': 0, + '@typescript-eslint/no-unused-vars': 'off', '@typescript-eslint/ban-ts-comment': 'off', '@typescript-eslint/ban-types': 'off', '@typescript-eslint/no-empty-function': 'off', @@ -45,6 +48,7 @@ module.exports = { '@typescript-eslint/no-non-null-assertion': 'off', '@typescript-eslint/array-type': ['error', { default: 'array-simple', readonly: 'array-simple' }], 'require-jsdoc': 1, + 'cypress/unsafe-to-chain-command': 'off', 'react-hooks/rules-of-hooks': 'error', // Checks rules of Hooks 'react-hooks/exhaustive-deps': 'warn', // Checks effect dependencies 'import/default': 0, diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000..af30865863 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +.husky/* text eol=lf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b642aede3a..e33ce6f9df 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,7 +31,7 @@ jobs: steps: - uses: actions/checkout@v2 - - uses: actions/cache + - uses: actions/cache@v4 with: path: ~/.cache/yarn key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} @@ -46,15 +46,9 @@ jobs: - name: build run: yarn build - - name: build examples - run: yarn build:examples - - name: build snapp run: yarn snapp build env: RELATIVE_CI_KEY: ${{ secrets.RELATIVE_CI_KEY }} - - name: test - run: NODE_OPTIONS='--max-old-space-size=4096' yarn test --coverage --logHeapUsage - - uses: codecov/codecov-action@v1 diff --git a/.github/workflows/deploy-preview.yml b/.github/workflows/deploy-preview.yml index 6ef02634c1..3c3ea38285 100644 --- a/.github/workflows/deploy-preview.yml +++ b/.github/workflows/deploy-preview.yml @@ -8,7 +8,7 @@ jobs: steps: - uses: actions/checkout@v2 - - uses: actions/cache@v4 # Updated from v1 to v4 + - uses: actions/cache@v4 with: path: ~/.cache/yarn key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml new file mode 100644 index 0000000000..4ae75c7563 --- /dev/null +++ b/.github/workflows/docker-image.yml @@ -0,0 +1,68 @@ +name: Docker Image CI + +on: + push: + branches: + - 'develop' + - 'main' + - 'feature/docker-containerization' + - 'feature/sn-auth-package-extraimprovements' + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + branches: + - 'develop' + - 'main' + - 'feature/sn-auth-package-extraimprovements' + +jobs: + build: + runs-on: ubuntu-latest + # Skip draft PRs + if: github.event.pull_request.draft == false || github.event_name == 'push' + + steps: + - name: Check out the repo + uses: actions/checkout@v4 + + - name: Check if Dockerfile exists + id: check_dockerfile + run: | + if [ -f "Dockerfile" ]; then + echo "dockerfile_exists=true" >> $GITHUB_OUTPUT + else + echo "dockerfile_exists=false" >> $GITHUB_OUTPUT + echo "⚠️ No Dockerfile found, skipping Docker build" + fi + + - name: Set up Docker metadata + if: steps.check_dockerfile.outputs.dockerfile_exists == 'true' + id: meta + uses: docker/metadata-action@v5 + with: + images: sensenetcsp/sn-client + tags: | + # Clean branch name (e.g., feature-docker-containerization) + type=ref,event=branch + # Branch name with SHA (e.g., feature-docker-containerization-abc1234) + type=ref,event=branch,suffix=-{{sha}} + # Latest tag for main branch + type=raw,value=latest,enable={{is_default_branch}} + # PR number for pull requests + type=ref,event=pr + + - name: Login to DockerHub + if: steps.check_dockerfile.outputs.dockerfile_exists == 'true' && github.event_name == 'push' + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Build and push Docker image + if: steps.check_dockerfile.outputs.dockerfile_exists == 'true' + uses: docker/build-push-action@v6 + with: + context: . + file: ./Dockerfile + push: ${{ github.event_name == 'push' }} + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} diff --git a/.gitignore b/.gitignore index 6a86cc155e..288a352a61 100644 --- a/.gitignore +++ b/.gitignore @@ -59,3 +59,8 @@ jspm_packages/ # Misc .DS_Store +pipe\[0] +# Environment variable files +.env +.env.local +.env.*.local diff --git a/.husky/pre-commit b/.husky/pre-commit index d2ae35e84b..45609d0f68 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -1,4 +1,5 @@ #!/bin/sh . "$(dirname "$0")/_/husky.sh" -yarn lint-staged +PATH="$(dirname "$0")/../node_modules/.bin:$PATH" +lint-staged diff --git a/DOCKER.md b/DOCKER.md new file mode 100644 index 0000000000..0590481343 --- /dev/null +++ b/DOCKER.md @@ -0,0 +1,129 @@ +# Docker Setup for SenseNet Client + +This guide explains how to run the SenseNet client application using Docker. + +## 🚀 Quick Start + +### Development (with hot reload) +```bash +docker-compose -f docker-compose.dev.yml up -d +``` +- **URL**: http://localhost:8080 +- **Hot reload**: ✅ File changes are instantly reflected +- **Use case**: Active development + +### Production +```bash +docker-compose -f docker-compose.prod.yml up -d +``` +- **URL**: http://localhost:8080 +- **Hot reload**: ❌ Static built files +- **Use case**: Testing production builds, deployment + +## 📁 Files Overview + +| File | Purpose | +|------|---------| +| `Dockerfile` | Single Docker image for both dev and prod | +| `docker-compose.dev.yml` | Development setup with volume mounts | +| `docker-compose.prod.yml` | Production setup without volume mounts | +| `.dockerignore` | Excludes unnecessary files from build context | + +## 🔧 How It Works + +### Development Mode +- **Volume mounting**: Your local code is mounted into the container +- **File watching**: Changes trigger automatic rebuilds +- **Command**: `yarn snapp start` (webpack dev server with hot reload) + +### Production Mode +- **Built files**: Uses pre-built static files inside the container +- **No volumes**: Container is self-contained +- **Command**: `yarn snapp start` (same command, but runs webpack dev server on built files) + +## 🛠️ Common Commands + +```bash +# Start development +docker-compose -f docker-compose.dev.yml up -d + +# Stop development +docker-compose -f docker-compose.dev.yml down + +# Rebuild and start (after dependency changes) +docker-compose -f docker-compose.dev.yml up --build -d + +# View logs +docker-compose -f docker-compose.dev.yml logs -f + +# Start production +docker-compose -f docker-compose.prod.yml up -d +``` + +## 🐳 Docker Images + +Automatic builds are available on DockerHub: + +```bash +# Latest development build +docker pull sensenetcsp/sn-client:feature-docker-containerization + +# Specific commit +docker pull sensenetcsp/sn-client:feature-docker-containerization-abc1234 + +# Production (when merged to main) +docker pull sensenetcsp/sn-client:latest +``` + +## ⚙️ Configuration + +### Environment Variables +Both compose files support these environment variables: + +- `NODE_ENV`: `development` or `production` +- `AUTH_TYPE`: `SNAuth` or `IdentityServer` +- `CHOKIDAR_USEPOLLING`: `true` (dev only, for file watching) +- `WATCHPACK_POLLING`: `true` (dev only, for webpack) + +### Port Configuration +- **Default**: Port 8080 for both dev and prod +- **Customizable**: Change the host port in docker-compose files + +## 🔍 Troubleshooting + +### Container won't start +```bash +# Check logs +docker-compose -f docker-compose.dev.yml logs + +# Rebuild from scratch +docker-compose -f docker-compose.dev.yml down +docker-compose -f docker-compose.dev.yml up --build +``` + +### Hot reload not working +- Ensure you're using the dev compose file +- Restart the container if file watching stops working + +### Port already in use +```bash +# Change the port in docker-compose file +ports: + - "3000:8080" # Use port 3000 instead of 8080 +``` + +## 📦 Build Process + +The Docker build process: +1. **Copy source code** (excluding files in `.dockerignore`) +2. **Install dependencies** with `yarn install` +3. **Build packages** with `yarn build` +4. **Start application** with `yarn snapp start` + +## 🚀 CI/CD + +GitHub Actions automatically builds and pushes Docker images when: +- Code is pushed to `feature/docker-containerization` +- Pull requests target `develop`, `main`, or `feature/sn-auth-package-extraimprovements` + +Images are tagged based on branch names and commit SHAs for easy identification. \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000..1eeba2805c --- /dev/null +++ b/Dockerfile @@ -0,0 +1,27 @@ +# Dockerfile for SenseNet client +FROM node:20-alpine + +# Install serve for static file serving +RUN yarn global add serve + +# Set working directory +WORKDIR /app + +# Copy everything (dockerignore excludes unwanted files) +COPY . . + +# Install dependencies +RUN HUSKY=0 yarn install --frozen-lockfile + +# Build the app bundle in production mode (the snapp webpack config resolves workspace packages from src) +RUN NODE_ENV=production yarn snapp build + +# Expose port +EXPOSE 8080 + +# Health check (start-period is short since static server starts instantly) +HEALTHCHECK --interval=30s --timeout=3s --start-period=15s --retries=3 \ + CMD wget --no-verbose --tries=1 --spider http://localhost:8080/ || exit 1 + +# Serve pre-built static files (fast startup, SPA mode with -s flag) +CMD ["serve", "-s", "apps/sensenet/build", "-l", "8080"] diff --git a/apps/sensenet/README.md b/apps/sensenet/README.md index ea765a613f..24f73527cf 100644 --- a/apps/sensenet/README.md +++ b/apps/sensenet/README.md @@ -35,6 +35,10 @@ The repositories you've visited will be also saved in your Personal Settings - y You can browse the whole repository with the **Content** menu. You can adjust the Content view in the personal setting's _"content"_ section. +### Admin UI Applications + +The Admin UI can render repository-defined `AUIApplication` contents as small custom HTML applications inside the content explorer. See the [Admin UI Applications documentation](./docs/auiapplications.md) for the content type, bridge API, and repository read/update examples. + ## 🌈 Command palette The command palette is useful if you want to search in the repository, navigate to a specific page or execute a specific command on the current content. @@ -59,3 +63,67 @@ If you start typing a Content query term (that starts with a '+' sign), the term ## ℹ Version info (Coming soon...) + +# sensenet Admin UI + +React-based UI for sensenet. This application provides a rich UI for managing your sensenet content repository. It was designed to take advantage of the modern web technologies - which means we built it for evergreen browsers (Edge, Chrome, Firefox). If you need legacy browser support (e.g. IE11) please use the [old admin UI](https://github.com/SenseNet/sensenet/tree/master/src/nuget/snadmin/install-webpages) instead. + +## Authentication Configuration + +The application supports two authentication methods: + +- **SNAuth**: sensenet's JWT-based authentication +- **IdentityServer**: OIDC-based authentication with Identity Server + +You can specify which authentication method to use during the build process. This is a build-time configuration, meaning the application will be built to use only one authentication method. + +### Building with specific authentication method + +To build the application with SNAuth (default): + +```bash +yarn build:snauth +# or npm run build:snauth +``` + +To build the application with Identity Server authentication: + +```bash +yarn build:idserver +# or npm run build:idserver +``` + +### Development with specific authentication method + +To run the development server with SNAuth: + +```bash +yarn start:snauth +# or npm run start:snauth +``` + +To run the development server with Identity Server authentication: + +```bash +yarn start:idserver +# or npm run start:idserver +``` + +If you don't specify an authentication method, the application will default to using SNAuth. + +## Development + +To run the application locally: + +```bash +yarn install +yarn start +``` + +Navigate to http://localhost:8080 in your browser. + +To build the application: + +```bash +yarn build +``` diff --git a/apps/sensenet/content-types/AUIApplication.xml b/apps/sensenet/content-types/AUIApplication.xml new file mode 100644 index 0000000000..f5382c4a8a --- /dev/null +++ b/apps/sensenet/content-types/AUIApplication.xml @@ -0,0 +1,19 @@ + + Admin UI Application + Custom Admin UI application that renders its HTML field instead of the folder grid. + Content + true + + + HTML + HTML rendered by Admin UI when this content is opened. Referenced CSS and JavaScript files can be placed under this application folder and loaded with relative URLs. + + LongText + sn:HtmlEditor + Show + Show + Show + + + + diff --git a/apps/sensenet/docs/auiapplications.md b/apps/sensenet/docs/auiapplications.md new file mode 100644 index 0000000000..055638a954 --- /dev/null +++ b/apps/sensenet/docs/auiapplications.md @@ -0,0 +1,404 @@ +# Admin UI Applications + +`AUIApplication` is a lightweight extension point for the sensenet Admin UI. It lets repository editors create a folder-like content that contains custom HTML. When the Admin UI opens this content, it renders the HTML in place of the regular child grid. + +This is useful for small internal admin tools, dashboards, data fix-up screens, reports, and workflow helpers that should live in the repository instead of being compiled into the Admin UI bundle. + +## Content Type + +The content type definition is available here: + +```text +apps/sensenet/content-types/AUIApplication.xml +``` + +It derives from `Folder` and adds one editable field: + +```xml + + HTML + + LongText + sn:HtmlEditor + Show + Show + Show + + +``` + +After the CTD exists in the repository, create a new `AUIApplication` content anywhere under `/Root/Content`, then put the application markup into its `Html` field. + +## Rendering Model + +When the current content has type `AUIApplication`, `Explore` renders `AUIApplicationView` instead of the grid. + +The custom HTML is loaded from the `Html` field and rendered in an iframe. The iframe receives: + +```js +window.sensenetAdminApp +``` + +This object is injected by the Admin UI before your HTML runs. + +## Bridge Concept + +The HTML app runs inside an iframe. Calling the repository directly from that iframe can hit CORS or authentication problems, and exposing the bearer token directly to arbitrary HTML would be a bad extension pattern. + +Instead, the Admin UI provides a small bridge: + +1. Your HTML calls `window.sensenetAdminApp.fetch(...)`. +2. The iframe sends a `postMessage` request to the parent Admin UI. +3. The parent Admin UI validates that the request targets the current repository. +4. The parent calls `repository.fetch(...)`. +5. The normal Admin UI auth header/token is attached by the repository client. +6. The response body is sent back to the iframe. + +So custom apps can use authenticated repository APIs without reading or storing the token themselves. + +## Available API + +```ts +window.sensenetAdminApp = { + repositoryUrl: string + adminUiUrl: string + content: { + Id?: number + Path?: string + Name?: string + DisplayName?: string + Type?: string + } + location: { + href: string + pathname: string + search: string + hash: string + params: Record + } + theme: 'light' | 'dark' + fetch(input: string, init?: { + method?: string + headers?: Record + body?: string + }): Promise +} +``` + +The `fetch` function intentionally supports a small subset of the browser `fetch` API: + +```ts +type BridgeResponse = { + ok: boolean + status: number + statusText: string + url: string + headers: { + get(name: string): string | null + entries(): Array<[string, string]> + } + text(): Promise + json(): Promise + arrayBuffer(): Promise + blob(): Promise +} +``` + +Binary responses are transferred as `ArrayBuffer`, so downloads from endpoints such as +`/binaryhandler.ashx?nodeid=...&propertyname=Binary` can be read with `blob()` or +`arrayBuffer()` without converting the body through text first. + +Requests are restricted to the current repository origin. Cross-repository and arbitrary external requests are rejected by the parent Admin UI. + +## Admin UI Route Location + +The iframe is sandboxed, so custom HTML should not try to read the parent route through `window.parent.location` or infer it from `document.referrer`. The Admin UI injects the current React Router location into the bridge: + +```js +const app = window.sensenetAdminApp +const userId = app.location.params.userId +``` + +For example, if the browser address bar shows: + +```text +/content/explorer/?path=%2FContent%2FKELERData%2FKYCForm%2Fkycuserforms&userId=tarii +``` + +then inside the `AUIApplication` iframe: + +```js +window.sensenetAdminApp.location.search +// "?path=%2FContent%2FKELERData%2FKYCForm%2Fkycuserforms&userId=tarii" + +window.sensenetAdminApp.location.params.userId +// "tarii" +``` + +The `params` object is built from the parent route query string with `Object.fromEntries(new URLSearchParams(location.search))`. + +## Admin UI Theme + +The bridge also exposes the current Admin UI theme mode. Use this instead of trying to inspect parent styles from the sandboxed iframe: + +```js +const theme = window.sensenetAdminApp.theme +document.documentElement.dataset.theme = theme + +if (theme === 'dark') { + // Render dark-friendly colors. +} +``` + +The value is always either `"light"` or `"dark"`, matching the Admin UI view option. + +## URL Rules + +Use repository-relative URLs when possible: + +```js +await window.sensenetAdminApp.fetch('/odata.svc/Root/Content') +``` + +Absolute URLs are also accepted if they point to the same repository origin: + +```js +await window.sensenetAdminApp.fetch('https://example.test.sensenet.com/odata.svc/Root/Content') +``` + +Use `adminUiUrl` when you need to navigate back to Admin UI routes. Do not use root-relative links for Admin UI navigation inside an `AUIApplication`, because the injected `` tag points relative asset URLs to the repository content path. + +```js +const adminPath = (path) => path.replace(/^\/Root(?=\/|$)/, '') || '/' +const adminUiUrl = window.sensenetAdminApp.adminUiUrl +const query = new URLSearchParams({ + path: adminPath('/Root/Content/test/BannerImages'), + content: adminPath('/Root/Content/test/BannerImages/example.png'), +}) + +const editUrl = `${adminUiUrl}/content/explorer/edit?${query.toString()}` +``` + +For assets such as CSS or JavaScript, the Admin UI injects a `` tag that points to the current `AUIApplication` content path. This means relative references can point to files stored under the application folder: + +```html + + +``` + +## Read Children + +```js +const app = window.sensenetAdminApp + +async function loadChildren(path) { + const url = + `/odata.svc${path}` + + '?$select=Id,Path,Name,DisplayName,Type,IsFolder,IsFile,CreationDate,ModificationDate' + + '&$orderby=Name' + + const response = await app.fetch(url, { + headers: { + Accept: 'application/json', + }, + }) + + if (!response.ok) { + throw new Error(`${response.status} ${response.statusText}`) + } + + const result = await response.json() + + return result.d.results +} + +const items = await loadChildren('/Root/Content/test/BannerImages') +console.log(items) +``` + +## Read One Content + +```js +async function loadContent(path) { + const response = await window.sensenetAdminApp.fetch( + `/odata.svc${path}?$select=Id,Path,Name,DisplayName,Type,Description`, + { + headers: { + Accept: 'application/json', + }, + }, + ) + + if (!response.ok) { + throw new Error(`${response.status} ${response.statusText}`) + } + + const result = await response.json() + + return result.d +} +``` + +## Update Content + +Use `PATCH` for partial updates. Always send a JSON string body and set `Content-Type`. + +```js +async function updateDisplayName(path, displayName) { + const response = await window.sensenetAdminApp.fetch(`/odata.svc${path}`, { + method: 'PATCH', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + DisplayName: displayName, + }), + }) + + if (!response.ok) { + const details = await response.text() + throw new Error(`Update failed: ${response.status} ${response.statusText} ${details}`) + } + + return response.json() +} + +await updateDisplayName('/Root/Content/test/BannerImages/example.png', 'New display name') +``` + +## Create Content + +Use `POST` on the parent path and include `__ContentType`. + +```js +async function createFolder(parentPath, name, displayName) { + const response = await window.sensenetAdminApp.fetch(`/odata.svc${parentPath}`, { + method: 'POST', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + __ContentType: 'Folder', + Name: name, + DisplayName: displayName, + }), + }) + + if (!response.ok) { + const details = await response.text() + throw new Error(`Create failed: ${response.status} ${response.statusText} ${details}`) + } + + return response.json() +} + +await createFolder('/Root/Content/test', 'NewBannerFolder', 'New banner folder') +``` + +## Small Helper Wrapper + +For real applications, define a tiny repository helper in your HTML or external JavaScript file: + +```js +const sn = { + request: async (url, init = {}) => { + const response = await window.sensenetAdminApp.fetch(url, { + ...init, + headers: { + Accept: 'application/json', + ...(init.body ? { 'Content-Type': 'application/json' } : {}), + ...(init.headers || {}), + }, + }) + + if (!response.ok) { + const details = await response.text() + throw new Error(`${response.status} ${response.statusText}: ${details}`) + } + + return response.json() + }, + + loadChildren: async (path) => { + const result = await sn.request(`/odata.svc${path}?$select=Id,Path,Name,DisplayName,Type&$orderby=Name`) + return result.d.results + }, + + patch: async (path, content) => { + const result = await sn.request(`/odata.svc${path}`, { + method: 'PATCH', + body: JSON.stringify(content), + }) + return result.d + }, +} +``` + +## Example Application + +The first example application is here: + +```text +apps/sensenet/examples/auiapplication-banner-images.html +``` + +It lists the children of: + +```text +/Root/Content/test/BannerImages +``` + +The table displays `Name` and `Type`, and each row has an Edit button that navigates back to the normal Admin UI edit view. + +## Recommended Structure + +For small tools, putting everything into the `Html` field is fine: + +```html +
...
+ + +``` + +For larger tools, store assets under the `AUIApplication` folder: + +```text +MyAdminTool + index HTML in the Html field + app.js + styles.css +``` + +Then reference them with relative URLs: + +```html + + +``` + +## Security Notes + +`AUIApplication` is a powerful extension point. Treat it as trusted admin-defined code. + +Important guardrails: + +- The bridge does not expose the bearer token to the iframe. +- Bridge requests are restricted to the current repository origin. +- The iframe is sandboxed and does not get direct parent DOM access. +- User-clicked links may navigate the top-level Admin UI window, which is needed for Edit links and similar Admin UI routes. +- Users who can edit an `AUIApplication` can run JavaScript inside the Admin UI page, so editing rights should be limited to trusted administrators. +- Do not paste third-party scripts into an `AUIApplication` unless they are reviewed and trusted. + +## Limitations + +- `sensenetAdminApp.fetch` is not a full browser `fetch` replacement. +- Request bodies must currently be strings. Use `JSON.stringify(...)` for JSON payloads. +- The response object supports `ok`, `status`, `statusText`, `url`, `headers.get`, `headers.entries`, `text()`, and `json()`. +- File upload and streaming APIs are not exposed through this bridge yet. +- High-level repository methods such as `load`, `patch`, or `post` are not exposed directly. Build tiny wrappers around `fetch` in your app. diff --git a/apps/sensenet/examples/auiapplication-active-users.html b/apps/sensenet/examples/auiapplication-active-users.html new file mode 100644 index 0000000000..f2b6ff2d5a --- /dev/null +++ b/apps/sensenet/examples/auiapplication-active-users.html @@ -0,0 +1,329 @@ +
+
+

Admin UI Application példa

+

Aktív userek

+

+ Ó, admin UI istene, ki a káoszból táblázatot, a bizonytalanságból jogosultságot, a kattintásból pedig + működő workflow-t teremtesz: legyen ma kegyes hozzánk a grid, és mutassa meg a + /Root/IMS alatt élő aktív felhasználókat. +

+
+ +
+
+
+

Felhasználók

+

Betöltés...

+
+
+ + +
+
+ +
Betöltés...
+ + + + + + + + + + +
+
+ + + + diff --git a/apps/sensenet/examples/auiapplication-banner-images.html b/apps/sensenet/examples/auiapplication-banner-images.html new file mode 100644 index 0000000000..869e73b3c4 --- /dev/null +++ b/apps/sensenet/examples/auiapplication-banner-images.html @@ -0,0 +1,274 @@ +
+
+

Admin UI Application példa

+

Banner képek

+

+ Ez a kis alkalmazás a /Root/Content/test/BannerImages alatti contenteket listázza, és minden sorhoz + ad egy gyors szerkesztés gombot. +

+
+ +
+
+

Contentek

+ +
+ +
Betöltés...
+ + + + + + + + + + + +
+
+ + + + diff --git a/apps/sensenet/index.html b/apps/sensenet/index.html index 4f32ba2e91..bc7f6ac4c8 100644 --- a/apps/sensenet/index.html +++ b/apps/sensenet/index.html @@ -1,42 +1,45 @@ - - - - - sensenet - - - - -
- - + /* Track */ + ::-webkit-scrollbar-track { + background: rgba(128, 128, 128, 0.3); + } + + /* Handle */ + ::-webkit-scrollbar-thumb { + background: #888; + } + + /* Handle on hover */ + ::-webkit-scrollbar-thumb:hover { + background: #555; + } + + + + + +
+ + + \ No newline at end of file diff --git a/apps/sensenet/package.json b/apps/sensenet/package.json index 1edf524ec2..0d80852cfc 100644 --- a/apps/sensenet/package.json +++ b/apps/sensenet/package.json @@ -17,7 +17,12 @@ "fix:prettier": "prettier \"{,!(dist|temp|bundle)/**/}*.{ts,tsx}\" --write", "build": "cross-env NODE_OPTIONS=--openssl-legacy-provider webpack --config webpack.prod.js", "build:stats": "webpack --config webpack.prod.js --profile --json > stats.json", + "build:snauth": "cross-env NODE_OPTIONS=--openssl-legacy-provider AUTH_TYPE=SNAuth webpack --config webpack.prod.js", + "build:idserver": "cross-env NODE_OPTIONS=--openssl-legacy-provider AUTH_TYPE=IdentityServer webpack --config webpack.prod.js", "start": "cross-env NODE_OPTIONS=--openssl-legacy-provider webpack serve --progress --config webpack.dev.js", + "start:snauth": "cross-env NODE_OPTIONS=--openssl-legacy-provider AUTH_TYPE=SNAuth webpack serve --progress --config webpack.dev.js", + "start:idserver": "cross-env NODE_OPTIONS=--openssl-legacy-provider AUTH_TYPE=IdentityServer webpack serve --progress --config webpack.dev.js", + "buildstart": "cd ../../ && yarn build && cd apps/sensenet && yarn start", "cypress": "cypress open --env coverage=false", "cypress:local": "cypress open --env coverage=false --config baseUrl=http://localhost:8080", "cypress:all": "cypress run --env coverage=false", @@ -60,6 +65,7 @@ "cypress-file-upload": "^5.0.8", "cypress-xpath": "^1.6.2", "eslint-config-prettier": "8.6.0", + "eslint-config-react-app": "^7.0.1", "file-loader": "^6.1.1", "fork-ts-checker-webpack-plugin": "^6.3.1", "html-webpack-plugin": "^5.5.0", @@ -82,6 +88,7 @@ "webpack-merge": "^5.8.0" }, "dependencies": { + "@ag-grid-community/styles": "30.0.5", "@iconify-icons/logos": "1.2.23", "@iconify/react": "4.1.0", "@material-ui/core": "4.11.4", @@ -100,12 +107,18 @@ "@sensenet/pickers-react": "^2.1.4", "@sensenet/query": "^2.1.3", "@sensenet/repository-events": "^2.1.3", + "@sensenet/sn-auth-react": "^1.0.3", + "@tiptap/pm": "^2.6.6", + "ag-grid-community": "27.3.0", + "ag-grid-enterprise": "27.3.0", + "ag-grid-react": "27.3.0", "autosuggest-highlight": "^3.3.4", "clsx": "1.2.1", "date-fns": "2.29.3", "filesize": "10.0.6", "react": "^16.13.0", "react-autosuggest": "^10.1.0", + "react-data-grid": "6.1.0", "react-day-picker": "^8.6.0", "react-dom": "^16.13.0", "react-markdown": "6.0.3", diff --git a/apps/sensenet/src/application-paths.ts b/apps/sensenet/src/application-paths.ts index 079593a5f6..56dc0965f1 100644 --- a/apps/sensenet/src/application-paths.ts +++ b/apps/sensenet/src/application-paths.ts @@ -1,4 +1,5 @@ import { BrowseType } from './components/content' +import { FAVORITES_ROOT_PATH } from './services/favorites-constants' export const PATHS = { loginCallback: { appPath: '/authentication/login-callback' }, @@ -9,22 +10,26 @@ export const PATHS = { usersAndGroups: { appPath: '/users-and-groups/:browseType/:action?', snPath: '/Root/IMS' }, dashboard: { appPath: '/dashboard' }, contentTypes: { appPath: '/content-types/:browseType/:action?', snPath: '/Root/System/Schema/ContentTypes' }, - search: { appPath: '/search' }, - content: { appPath: '/content/:browseType/:action?', snPath: '/Root/Content' }, + search: { appPath: '/search', snPath: '/Root' }, + favorites: { appPath: '/favorites/:browseType/:action?', snPath: FAVORITES_ROOT_PATH }, + content: { appPath: '/content/:browseType/:action?', snPath: '/Root' }, contentTemplates: { appPath: '/content-templates/:browseType/:action?', snPath: '/Root/ContentTemplates' }, - custom: { appPath: '/custom/:browseType/:path/:action?' }, + custom: { appPath: '/custom/:browseType/:path/:action?', snPath: '/Root' }, configuration: { appPath: '/system/settings/:action?', snPath: '/Root/System/Settings' }, localization: { appPath: '/system/localization/:action?', snPath: '/Root/Localization' }, webhooks: { appPath: '/system/webhooks/:action?', snPath: '/Root/System/WebHooks' }, - settings: { appPath: '/system/:submenu?' }, + settings: { appPath: '/system/:submenu?', snPath: '/Root/System/Settings' }, apiKeys: { appPath: '/system/apikeys' }, + landingPath: { appPath: '/content/explorer/' }, + root: { appPath: '/Root', snPath: '/Root' }, + home: { appPath: '/', snPath: '/' }, } as const -type SettingsItemType = 'stats' | 'apikeys' | 'webhooks' | 'adminui' +type SettingsItemType = 'stats' | 'settings' | 'apikeys' | 'webhooks' | 'adminui' type RoutesWithContentBrowser = keyof Pick< typeof PATHS, - 'content' | 'usersAndGroups' | 'contentTypes' | 'trash' | 'contentTemplates' + 'content' | 'favorites' | 'usersAndGroups' | 'contentTypes' | 'trash' | 'contentTemplates' > type RoutesWithActionParam = keyof Pick diff --git a/apps/sensenet/src/assets/sensenet-logo.svg b/apps/sensenet/src/assets/sensenet-logo.svg new file mode 100644 index 0000000000..04e78ea5d4 --- /dev/null +++ b/apps/sensenet/src/assets/sensenet-logo.svg @@ -0,0 +1,18 @@ + + + + + + + + + + + + diff --git a/apps/sensenet/src/auth-config.ts b/apps/sensenet/src/auth-config.ts new file mode 100644 index 0000000000..2b3ceed021 --- /dev/null +++ b/apps/sensenet/src/auth-config.ts @@ -0,0 +1,10 @@ +export type AuthServerType = 'SNAuth' | 'IdentityServer' + +export interface AuthenticationConfig { + authType: AuthServerType +} + +// Use process.env.AUTH_TYPE if available (from build), otherwise default to 'SNAuth' +export const defaultAuthConfig: AuthenticationConfig = { + authType: (process.env.AUTH_TYPE || 'SNAuth') as AuthServerType, +} diff --git a/apps/sensenet/src/components/AddButton.tsx b/apps/sensenet/src/components/AddButton.tsx index eed47f8a0a..fe05b4d01d 100644 --- a/apps/sensenet/src/components/AddButton.tsx +++ b/apps/sensenet/src/components/AddButton.tsx @@ -28,6 +28,7 @@ const useStyles = makeStyles((theme: Theme) => { return createStyles({ addWrapper: { position: 'relative', + margin: 0, }, addListLoader: { color: theme.palette.secondary.main, @@ -43,12 +44,8 @@ const useStyles = makeStyles((theme: Theme) => { }, }, listItem: { - width: '100%', - display: 'flex', - alignItems: 'center', - justifyContent: 'space-evenly', height: globals.common.addButtonHeight, - paddingLeft: '2px', + paddingLeft: '4px', }, listDropdown: { padding: '10px 0 10px 10px', @@ -64,10 +61,14 @@ const useStyles = makeStyles((theme: Theme) => { disabled: { cursor: 'not-allowed', }, + drawerIconButtonWrapper: { + height: '40px', + }, }) }) export interface AddButtonProps { isOpened?: boolean + isDisabled?: boolean } export const AddButton: FunctionComponent = (props) => { @@ -96,7 +97,7 @@ export const AddButton: FunctionComponent = (props) => { try { const actions = await repo.getActions({ idOrPath: currentPath }) const isActionFound = actions.d.results.some((action) => action.Name === 'Add' || action.Name === 'Upload') - setAvailable(isActionFound && !activeAction) + setAvailable(isActionFound && !activeAction && !props.isDisabled) } catch (error) { logger.error({ message: localization.errorGettingActions, @@ -107,12 +108,12 @@ export const AddButton: FunctionComponent = (props) => { } } - if (currentPath) { + if (currentPath && currentPath !== '/') { getActions() } else { setAvailable(false) } - }, [localization.errorGettingActions, logger, repo, currentPath, activeAction]) + }, [localization.errorGettingActions, logger, repo, currentPath, activeAction, props.isDisabled]) useEffect(() => { const getAllowedChildTypes = async () => { @@ -157,14 +158,15 @@ export const AddButton: FunctionComponent = (props) => { ]) return ( -
+
{!props.isOpened ? ( -
+
{isAvailable ? (
) => { if (isLoading) return setAnchorEl(event.currentTarget) @@ -181,6 +183,7 @@ export const AddButton: FunctionComponent = (props) => { className={clsx(globalClasses.drawerButton, { [classes.addButtonDisabled]: !isAvailable, })} + style={{ margin: 4 }} data-test="add-button" disabled={true}> @@ -196,7 +199,7 @@ export const AddButton: FunctionComponent = (props) => { setShowSelectType(true) }} disabled={!isAvailable}> - + = (props) => { - + )} {!isLoading && ( diff --git a/apps/sensenet/src/components/BatchActions.tsx b/apps/sensenet/src/components/BatchActions.tsx new file mode 100644 index 0000000000..d1bb51f88c --- /dev/null +++ b/apps/sensenet/src/components/BatchActions.tsx @@ -0,0 +1,223 @@ +import { CircularProgress, createStyles, IconButton, makeStyles, Theme, Tooltip } from '@material-ui/core' +import AppsIcon from '@material-ui/icons/Apps' +import ArchiveIcon from '@material-ui/icons/Archive' +import DeleteIcon from '@material-ui/icons/Delete' +import FileCopyIcon from '@material-ui/icons/FileCopy' +import FileCopyOutlinedIcon from '@material-ui/icons/FileCopyOutlined' +import TableChartIcon from '@material-ui/icons/TableChart' +import { CurrentContentContext, useLogger, useRepository } from '@sensenet/hooks-react' +import React, { useContext, useEffect, useState } from 'react' +import { useGlobalStyles } from '../globalStyles' +import { useLocalization, useSelectionService } from '../hooks' +import { downloadContentsAsZip } from '../services/zip-download' +import { CsvExportDialog } from './CsvExportDialog' +import { useDialog } from './dialogs' + +const useStyles = makeStyles((theme: Theme) => + createStyles({ + batchActionWrapper: { + '& .MuiIconButton-root': { + color: theme.palette.type === 'light' ? theme.palette.common.black : theme.palette.common.white, + }, + marginLeft: '12px', + display: 'flex', + alignItems: 'center', + marginRight: '8px', + height: '36px', + }, + actionButton: { + width: '40px', + marginRight: '2px', + '&:disabled': { + opacity: 0.2, + }, + }, + }), +) + +export const BatchActions = () => { + const selectionService = useSelectionService() + const localization = useLocalization() + const globalClasses = useGlobalStyles() + const classes = useStyles() + const { openDialog } = useDialog() + const repository = useRepository() + const logger = useLogger('BatchActions') + const [selected, setSelected] = useState(selectionService.selection.getValue()) + const [isExportDialogOpen, setIsExportDialogOpen] = useState(false) + const [isZipDownloading, setIsZipDownloading] = useState(false) + const parent = useContext(CurrentContentContext) + + useEffect(() => { + const selectedComponentsObserve = selectionService.selection.subscribe((newSelectedComponents) => { + setSelected(newSelectedComponents) + }) + + return function cleanup() { + selectedComponentsObserve.dispose() + } + }, [selectionService.selection]) + + const downloadSelectedContentAsZip = async () => { + if (!selected.length || isZipDownloading) { + return + } + + setIsZipDownloading(true) + + try { + const result = await downloadContentsAsZip({ repository, contents: selected, parent }) + + logger.information({ + message: localization.batchActions.downloadZipSuccess + .replace('{0}', String(result.fileCount)) + .replace('{1}', String(result.folderCount)), + data: { + relatedRepository: repository.configuration.repositoryUrl, + details: { + fileCount: result.fileCount, + folderCount: result.folderCount, + skippedContentCount: result.skippedContentCount, + fileName: result.fileName, + }, + }, + }) + } catch (error) { + logger.error({ + message: localization.batchActions.downloadZipError, + data: { + error, + relatedRepository: repository.configuration.repositoryUrl, + details: { + selectedContentCount: selected.length, + }, + }, + }) + } finally { + setIsZipDownloading(false) + } + } + + return ( +
+ + + + openDialog({ + name: 'odata-actions', + props: { content: selected[0] }, + dialogProps: { classes: { paper: globalClasses.pickerDialog } }, + }) + }> + + + + + + + setIsExportDialogOpen(true)}> + + + + + setIsExportDialogOpen(false)} + /> + + + + {isZipDownloading ? : } + + + + + + + openDialog({ + name: 'delete', + props: { content: selected }, + dialogProps: { disableBackdropClick: true, disableEscapeKeyDown: true }, + }) + }> + + + + + + + + openDialog({ + name: 'copy-move', + props: { + content: selected, + currentParent: parent, + operation: 'move', + }, + dialogProps: { + disableBackdropClick: true, + disableEscapeKeyDown: true, + classes: { paper: globalClasses.pickerDialog }, + }, + }) + }> + + + + + + + + openDialog({ + name: 'copy-move', + props: { + content: selected, + currentParent: parent, + operation: 'copy', + }, + dialogProps: { + disableBackdropClick: true, + disableEscapeKeyDown: true, + classes: { paper: globalClasses.pickerDialog }, + }, + }) + }> + + + + +
+ ) +} diff --git a/apps/sensenet/src/components/Breadcrumbs.tsx b/apps/sensenet/src/components/Breadcrumbs.tsx index f6ce22575c..904af4b31b 100644 --- a/apps/sensenet/src/components/Breadcrumbs.tsx +++ b/apps/sensenet/src/components/Breadcrumbs.tsx @@ -1,10 +1,11 @@ +import { Menu, MenuItem } from '@material-ui/core' import MUIBreadcrumbs from '@material-ui/core/Breadcrumbs' import Button from '@material-ui/core/Button' import Tooltip from '@material-ui/core/Tooltip' import { GenericContent } from '@sensenet/default-content-types' -import React, { MouseEvent, useState } from 'react' +import { useRepository } from '@sensenet/hooks-react' +import React, { MouseEvent, useEffect, useState } from 'react' import { ContentContextMenu } from './context-menu/content-context-menu' -import CopyPath from './CopyPath' import { DropFileArea } from './DropFileArea' export interface BreadcrumbItem { @@ -16,7 +17,77 @@ export interface BreadcrumbItem { export interface BreadcrumbProps { items: Array> - onItemClick: (event: MouseEvent, item: BreadcrumbItem) => void + onItemClick: (event: MouseEvent, item: any) => void +} + +export interface BreadcrumbSeparatorProps { + itemPath: string + onItemClick: (event: MouseEvent, item: any) => void +} + +export function BreadcrumbSeparator(props: BreadcrumbSeparatorProps) { + const { itemPath, onItemClick } = props + const [anchorEl, setAnchorEl] = useState(null) + const [siblings, setSiblings] = useState([]) + const repo = useRepository() + + useEffect(() => { + let isMounted = true + const fetchSiblings = async () => { + if (!itemPath) return + try { + const siblingsResult = await repo.loadCollection({ + path: itemPath, + oDataOptions: { + select: ['Id', 'Path', 'Name'], + orderby: 'Name', + metadata: 'no', + }, + }) + if (isMounted) { + setSiblings( + siblingsResult.d.results.map((s) => { + return { content: s, DisplayName: s.DisplayName, Id: s.Id } + }), + ) + } + } catch (error) { + console.error(error) + } + } + fetchSiblings() + return () => { + isMounted = false + } + }, [itemPath, repo]) + + const handleOpen = (event: React.MouseEvent) => { + setAnchorEl(event.currentTarget) + } + + const handleClose = () => { + setAnchorEl(null) + } + + return ( + <> + + + {siblings.map((sibling) => ( + { + onItemClick(ev, sibling) + handleClose() + }}> + {sibling.DisplayName} + + ))} + + + ) } export function Breadcrumbs(props: BreadcrumbProps) { @@ -26,12 +97,8 @@ export function Breadcrumbs(props: BreadcrumbProps) return ( <> - - {props.items.map((item) => ( + + {props.items.map((item, index) => ( + {index < props.items.length - 1 && ( + + )} ))} - {contextMenuItem ? ( { +const useStyles = makeStyles((theme) => { return createStyles({ - batchActionWrapper: { - ' & .MuiIconButton-root': { - color: theme.palette.type === 'light' ? theme.palette.common.black : theme.palette.common.white, + buttonsWrapper: { + display: 'flex', + alignItems: 'center', + width: '100%', + minWidth: 0, + marginLeft: '10px', + overflow: 'hidden', + [theme.breakpoints.down('sm')]: { + marginLeft: 0, + width: '100%', }, - marginLeft: 'auto', + }, + desktopBreadcrumbs: { display: 'flex', - marginRight: '8px', - height: '40px', + alignItems: 'center', + minWidth: 0, + overflow: 'hidden', + [theme.breakpoints.down('sm')]: { + display: 'none', + }, }, - buttonsWrapper: { + mobileLocation: { + display: 'none', + [theme.breakpoints.down('sm')]: { + display: 'flex', + alignItems: 'center', + minWidth: 0, + flex: '1 1 auto', + }, + }, + mobileLocationButton: { + minWidth: 0, + maxWidth: '100%', + paddingLeft: 4, + paddingRight: 4, + textTransform: 'none', + justifyContent: 'flex-start', + overflow: 'hidden', + '& .MuiButton-label': { + display: 'block', + overflow: 'hidden', + textOverflow: 'ellipsis', + whiteSpace: 'nowrap', + }, + }, + mobileUpButton: { + flex: '0 0 auto', + padding: 6, + }, + breadcrumbsArea: { + display: 'flex', + alignItems: 'center', + flex: '1 1 auto', + minWidth: 0, + overflow: 'hidden', + }, + copyPathArea: { display: 'flex', alignItems: 'center', + flexShrink: 0, }, - actionButton: { - width: '40px', - marginRight: '2px', + actionsArea: { + display: 'flex', + alignItems: 'center', + flexShrink: 0, + marginLeft: 'auto', }, }) }) @@ -47,112 +95,71 @@ export const ContentBreadcrumbs = (pr const repository = useRepository() const history = useHistory() const { location } = history - const localization = useLocalization() - const globalClasses = useGlobalStyles() const classes = useStyles() - const { openDialog } = useDialog() const selectionService = useSelectionService() - const [selected, setSelected] = useState(selectionService.selection.getValue()) + const device = useContext(ResponsiveContext) + + const items = [ + ...ancestors.map((content) => ({ + displayName: content.DisplayName || content.Name, + title: content.Path, + url: getPrimaryActionUrl({ content, repository, uiSettings, location }), + content, + })), + { + displayName: parent.DisplayName || parent.Name, + title: parent.Path, + url: getPrimaryActionUrl({ content: parent, repository, uiSettings, location }), + content: parent, + }, + ] - useEffect(() => { - const selectedComponentsObserve = selectionService.selection.subscribe((newSelectedComponents) => - setSelected(newSelectedComponents), - ) + const handleItemClick = (item: BreadcrumbItem) => { + selectionService.activeContent.setValue(item.content) + props.onItemClick + ? props.onItemClick(item) + : history.push(getPrimaryActionUrl({ content: item.content, repository, uiSettings, location })) + } - return function cleanup() { - selectedComponentsObserve.dispose() - } - }, [selectionService.selection]) + const parentItem = items[items.length - 1] + const ancestorItem = items[items.length - 2] return (
- - items={[ - ...ancestors.map((content) => ({ - displayName: content.DisplayName || content.Name, - title: content.Path, - url: getPrimaryActionUrl({ content, repository, uiSettings, location }), - content, - })), - { - displayName: parent.DisplayName || parent.Name, - title: parent.Path, - url: getPrimaryActionUrl({ content: parent, repository, uiSettings, location }), - content: parent, - }, - ]} - onItemClick={(_ev, item) => { - selectionService.activeContent.setValue(item.content) - props.onItemClick - ? props.onItemClick(item) - : history.push(getPrimaryActionUrl({ content: item.content, repository, uiSettings, location })) - }} - /> - {props.batchActions && selected.length > 0 ? ( -
- - { - openDialog({ - name: 'delete', - props: { content: selected }, - dialogProps: { disableBackdropClick: true, disableEscapeKeyDown: true }, - }) - }}> - - - - - { - openDialog({ - name: 'copy-move', - props: { - content: selected, - currentParent: parent, - operation: 'move', - }, - dialogProps: { - disableBackdropClick: true, - disableEscapeKeyDown: true, - classes: { paper: globalClasses.pickerDialog }, - }, - }) - }}> - - - - - { - openDialog({ - name: 'copy-move', - props: { - content: selected, - currentParent: parent, - operation: 'copy', - }, - dialogProps: { - disableBackdropClick: true, - disableEscapeKeyDown: true, - classes: { paper: globalClasses.pickerDialog }, - }, - }) - }}> - - - +
+ {device === 'mobile' ? ( +
+ {ancestorItem ? ( + + handleItemClick(ancestorItem)}> + + + + ) : null} + + + +
+ ) : ( +
+
+ +
+ items={items} onItemClick={(_ev, item) => handleItemClick(item)} /> +
+ )} +
+ {props.batchActions && ( +
+
- ) : null} + )}
) } diff --git a/apps/sensenet/src/components/CsvExportDialog.tsx b/apps/sensenet/src/components/CsvExportDialog.tsx new file mode 100644 index 0000000000..a9616e95a1 --- /dev/null +++ b/apps/sensenet/src/components/CsvExportDialog.tsx @@ -0,0 +1,448 @@ +import { + Button, + Checkbox, + Chip, + createStyles, + Dialog, + DialogActions, + DialogContent, + FormControl, + FormControlLabel, + InputLabel, + makeStyles, + MenuItem, + Select, + TextField, + Theme, + Typography, +} from '@material-ui/core' +import { FieldSetting, FieldVisibility, GenericContent } from '@sensenet/default-content-types' +import { useLogger, useRepository } from '@sensenet/hooks-react' +import React, { useEffect, useMemo, useState } from 'react' +import { useLocalization } from '../hooks' +import { createCsvFromContents, downloadCsv, getCsvExportFileName, preferredCsvColumns } from '../services/csv-export' +import { DialogTitle } from './dialogs' + +type CsvFieldOption = { + name: string + displayName: string + type: string + visibleBrowse?: FieldVisibility +} + +type CsvExportDialogProps = { + open: boolean + selected: GenericContent[] + parent?: GenericContent + onClose: () => void +} + +const systemFieldOptions = preferredCsvColumns.map((fieldName) => ({ + name: fieldName, + displayName: fieldName, + type: 'System', + visibleBrowse: FieldVisibility.Show, +})) +const exportRequestBatchSize = 8 + +const useStyles = makeStyles((theme: Theme) => + createStyles({ + content: { + display: 'flex', + flexDirection: 'column', + gap: theme.spacing(2), + minHeight: '420px', + }, + layout: { + display: 'grid', + gridTemplateColumns: 'minmax(260px, 360px) 1fr', + gap: theme.spacing(3), + [theme.breakpoints.down('xs')]: { + gridTemplateColumns: '1fr', + }, + }, + fieldToolbar: { + display: 'flex', + gap: theme.spacing(1), + margin: `${theme.spacing(1)}px 0`, + }, + fieldList: { + border: `1px solid ${theme.palette.divider}`, + maxHeight: '300px', + overflowY: 'auto', + padding: theme.spacing(1), + }, + fieldLabel: { + alignItems: 'flex-start', + display: 'flex', + marginRight: 0, + width: '100%', + }, + fieldLabelText: { + display: 'flex', + flexDirection: 'column', + minWidth: 0, + }, + fieldName: { + overflow: 'hidden', + textOverflow: 'ellipsis', + whiteSpace: 'nowrap', + }, + fieldMeta: { + color: theme.palette.text.secondary, + fontSize: '0.75rem', + overflow: 'hidden', + textOverflow: 'ellipsis', + whiteSpace: 'nowrap', + }, + selectedFields: { + alignContent: 'flex-start', + border: `1px solid ${theme.palette.divider}`, + display: 'flex', + flexWrap: 'wrap', + gap: theme.spacing(1), + marginTop: theme.spacing(1), + maxHeight: '300px', + minHeight: '128px', + overflowY: 'auto', + padding: theme.spacing(1), + }, + selectedFieldsHeader: { + alignItems: 'center', + display: 'flex', + gap: theme.spacing(1), + justifyContent: 'space-between', + }, + }), +) + +const getContentTypeNames = (contents: GenericContent[]) => + Array.from(new Set(contents.map((content) => content.Type).filter(Boolean))).sort((left, right) => + left.localeCompare(right), + ) + +const getSortedFieldOptions = (fieldOptions: CsvFieldOption[]) => + [...fieldOptions].sort((left, right) => { + const leftPreferredIndex = preferredCsvColumns.indexOf(left.name) + const rightPreferredIndex = preferredCsvColumns.indexOf(right.name) + + if (leftPreferredIndex >= 0 || rightPreferredIndex >= 0) { + if (leftPreferredIndex === -1) { + return 1 + } + if (rightPreferredIndex === -1) { + return -1 + } + return leftPreferredIndex - rightPreferredIndex + } + + return left.displayName.localeCompare(right.displayName) + }) + +const getFieldOptionsForContentType = (fieldSettings: FieldSetting[]) => { + const fieldOptionsByName = new Map(systemFieldOptions.map((fieldOption) => [fieldOption.name, fieldOption])) + + fieldSettings.forEach((fieldSetting) => { + fieldOptionsByName.set(fieldSetting.Name, { + name: fieldSetting.Name, + displayName: fieldSetting.DisplayName || fieldSetting.Name, + type: fieldSetting.Type, + visibleBrowse: fieldSetting.VisibleBrowse, + }) + }) + + return getSortedFieldOptions(Array.from(fieldOptionsByName.values())) +} + +const getDefaultSelectedFields = (contentTypeFieldOptions: CsvFieldOption[][]) => { + const fieldNames = new Set(preferredCsvColumns) + + contentTypeFieldOptions.forEach((fieldOptions) => { + fieldOptions.forEach((fieldOption) => { + if (fieldOption.visibleBrowse === FieldVisibility.Show) { + fieldNames.add(fieldOption.name) + } + }) + }) + + return Array.from(fieldNames) +} + +const loadContentsForExport = async ( + contents: GenericContent[], + loadContent: (content: GenericContent) => Promise, +) => { + const loadedContents: GenericContent[] = [] + + for (let startIndex = 0; startIndex < contents.length; startIndex += exportRequestBatchSize) { + const contentBatch = contents.slice(startIndex, startIndex + exportRequestBatchSize) + const loadedBatch = await Promise.all(contentBatch.map(loadContent)) + loadedContents.push(...loadedBatch) + } + + return loadedContents +} + +export const CsvExportDialog: React.FC = ({ open, selected, parent, onClose }) => { + const classes = useStyles() + const localization = useLocalization() + const logger = useLogger('CsvExportDialog') + const repository = useRepository() + const contentTypeNames = useMemo(() => getContentTypeNames(selected), [selected]) + const [activeContentType, setActiveContentType] = useState('') + const [selectedFields, setSelectedFields] = useState([]) + const [searchTerm, setSearchTerm] = useState('') + const [isExporting, setIsExporting] = useState(false) + + const fieldOptionsByContentType = useMemo(() => { + return contentTypeNames.reduce((optionsByType, contentTypeName) => { + const schema = repository.schemas.getSchemaByName(contentTypeName) + optionsByType[contentTypeName] = getFieldOptionsForContentType(schema.FieldSettings) + + return optionsByType + }, {} as Record) + }, [contentTypeNames, repository.schemas]) + + useEffect(() => { + if (!open) { + return + } + + setActiveContentType(contentTypeNames[0] || '') + setSelectedFields(contentTypeNames.length ? getDefaultSelectedFields(Object.values(fieldOptionsByContentType)) : []) + setSearchTerm('') + }, [contentTypeNames, fieldOptionsByContentType, open]) + + const activeFieldOptions = activeContentType ? fieldOptionsByContentType[activeContentType] || [] : [] + const filteredFieldOptions = activeFieldOptions.filter((fieldOption) => { + const normalizedSearchTerm = searchTerm.toLocaleLowerCase() + + return ( + fieldOption.name.toLocaleLowerCase().includes(normalizedSearchTerm) || + fieldOption.displayName.toLocaleLowerCase().includes(normalizedSearchTerm) || + fieldOption.type.toLocaleLowerCase().includes(normalizedSearchTerm) + ) + }) + + const fieldLabelsByName = useMemo(() => { + const labelsByName = new Map() + + Object.values(fieldOptionsByContentType).forEach((fieldOptions) => { + fieldOptions.forEach((fieldOption) => { + if (!labelsByName.has(fieldOption.name)) { + labelsByName.set(fieldOption.name, fieldOption.displayName) + } + }) + }) + + return labelsByName + }, [fieldOptionsByContentType]) + + const getFieldLabel = (fieldName: string) => { + const displayName = fieldLabelsByName.get(fieldName) + + return displayName && displayName !== fieldName ? `${displayName} (${fieldName})` : fieldName + } + + const toggleField = (fieldName: string) => { + setSelectedFields((currentFields) => + currentFields.includes(fieldName) + ? currentFields.filter((currentField) => currentField !== fieldName) + : [...currentFields, fieldName], + ) + } + + const selectActiveContentTypeFields = () => { + setSelectedFields((currentFields) => + Array.from(new Set([...currentFields, ...activeFieldOptions.map((fieldOption) => fieldOption.name)])), + ) + } + + const clearActiveContentTypeFields = () => { + const activeFieldNames = new Set(activeFieldOptions.map((fieldOption) => fieldOption.name)) + setSelectedFields((currentFields) => currentFields.filter((fieldName) => !activeFieldNames.has(fieldName))) + } + + const exportSelectedContent = async () => { + if (!selected.length || !selectedFields.length) { + return + } + + setIsExporting(true) + + try { + const contents = await loadContentsForExport(selected, async (content) => { + const response = await repository.load({ + idOrPath: content.Id, + oDataOptions: { select: 'all' }, + }) + + return response.d + }) + const csvContent = createCsvFromContents(contents, selectedFields) + + downloadCsv(csvContent, getCsvExportFileName(contents, parent)) + logger.information({ + message: localization.batchActions.exportCsvSuccess.replace('{0}', String(contents.length)), + data: { + relatedRepository: repository.configuration.repositoryUrl, + details: { + exportedContentCount: contents.length, + selectedFieldCount: selectedFields.length, + }, + }, + }) + onClose() + } catch (error) { + logger.error({ + message: localization.batchActions.exportCsvError, + data: { + error, + relatedRepository: repository.configuration.repositoryUrl, + details: { + selectedContentCount: selected.length, + selectedFields, + }, + }, + }) + } finally { + setIsExporting(false) + } + } + + const selectionSummary = localization.batchActions.exportCsvSelectionSummary + .replace('{0}', String(selected.length)) + .replace('{1}', String(contentTypeNames.length)) + const selectedFieldSummary = localization.batchActions.exportCsvSelectedFieldCount.replace( + '{0}', + String(selectedFields.length), + ) + + return ( + + {localization.batchActions.exportCsvDialogTitle} + + + {selectionSummary} + +
+
+ + + {localization.batchActions.exportCsvContentType} + + + + setSearchTerm(event.target.value)} + label={localization.batchActions.exportCsvSearchFields} + variant="outlined" + margin="normal" + fullWidth + /> +
+ + +
+
+ {filteredFieldOptions.length ? ( + filteredFieldOptions.map((fieldOption) => ( + toggleField(fieldOption.name)} + /> + } + label={ + + {fieldOption.displayName} + + {fieldOption.name} - {fieldOption.type} + + + } + /> + )) + ) : ( + + {localization.batchActions.exportCsvNoFields} + + )} +
+
+
+
+
+ {localization.batchActions.exportCsvSelectedFields} + + {selectedFieldSummary} + +
+ +
+
+ {selectedFields.length ? ( + selectedFields.map((fieldName) => ( + + setSelectedFields((currentFields) => + currentFields.filter((currentField) => currentField !== fieldName), + ) + } + /> + )) + ) : ( + + {localization.batchActions.exportCsvNoSelectedFields} + + )} +
+
+
+
+ + + + +
+ ) +} diff --git a/apps/sensenet/src/components/Home.tsx b/apps/sensenet/src/components/Home.tsx new file mode 100644 index 0000000000..1818bbd603 --- /dev/null +++ b/apps/sensenet/src/components/Home.tsx @@ -0,0 +1,430 @@ +import { + createStyles, + makeStyles, + Table, + TableBody, + TableCell, + TableHead, + TableRow, + Theme, + Tooltip, +} from '@material-ui/core' +import Accordion from '@material-ui/core/Accordion' +import AccordionDetails from '@material-ui/core/AccordionDetails' +import AccordionSummary from '@material-ui/core/AccordionSummary' +import Typography from '@material-ui/core/Typography' +import ExpandMoreIcon from '@material-ui/icons/ExpandMore' +import { useRepository } from '@sensenet/hooks-react' +import React, { lazy, useEffect, useState } from 'react' +import { useAuth } from '../context/auth-provider' +import { useLocalization } from '../hooks' +import { DateTimeFormatter } from './grid/Formatters/DateTimeFormatter' +import { HomeActivitySummary } from './home-activity-summary' + +const DashboardComponent = lazy(() => import(/* webpackChunkName: "dashboard" */ './dashboard')) + +const latestChangesLimit = 100 +const latestChangesWindowInMinutes = 600 + +const useStyles = makeStyles((theme: Theme) => + createStyles({ + homeCont: { + display: 'flex', + flexDirection: 'column', + width: '100%', + height: '100%', + backgroundColor: theme.palette.type === 'light' ? '#f5f7fa' : '#1e1e1e', + padding: '0 20px', + }, + title: { + display: 'flex', + gap: '24px', + padding: '16px 0', + alignItems: 'center', + borderBottom: `1px solid ${theme.palette.type === 'light' ? '#e0e0e0' : '#333'}`, + '& img': { + width: 70, + height: 70, + backgroundColor: 'transparent', + filter: theme.palette.type === 'light' ? 'invert(0)' : 'invert(1)', + }, + '& h1': { + fontSize: '36px', + fontWeight: 600, + color: theme.palette.type === 'light' ? '#333' : '#fff', + }, + }, + sensenetLogo: { + width: 70, + height: 70, + }, + gridsCont: { + gridTemplateColumns: '1fr 1fr', + gap: '24px', + marginTop: '20px', + height: 'calc(100% - 80px)', + overflowY: 'auto', + }, + gridCont: { + backgroundColor: theme.palette.type === 'light' ? '#fff' : '#2c2c2c', + borderRadius: '8px', + boxShadow: '0 2px 10px rgba(0, 0, 0, 0.1)', + padding: '0 20px', + overflowY: 'auto', + '& h2': { + fontSize: '24px', + fontWeight: 500, + color: theme.palette.type === 'light' ? '#333' : '#fff', + marginBottom: '16px', + textAlign: 'left', + }, + }, + accordion: { + backgroundColor: theme.palette.type === 'light' ? '#fafafa' : '#3c3c3c', + borderRadius: '4px', + marginBottom: '12px', + '&.Mui-expanded': { + margin: '0 0 12px 0', + }, + '&:before': { + display: 'none', + }, + '&:hover': { + cursor: 'default', + }, + }, + accordionSummary: { + padding: '12px 16px', + '& .MuiAccordionSummary-content': { + display: 'grid', + gridTemplateColumns: '1fr 1fr 1fr 3.5fr', + gap: '12px', + alignItems: 'center', + [theme.breakpoints.down(900)]: { + gridTemplateColumns: '1fr 1fr', + }, + [theme.breakpoints.down(600)]: { + gridTemplateColumns: '1fr', + }, + }, + }, + accordionDetails: { + padding: '16px', + backgroundColor: theme.palette.type === 'light' ? '#f9f9f9' : '#444', + borderTop: `1px solid ${theme.palette.type === 'light' ? '#e0e0e0' : '#555'}`, + }, + truncatedText: { + overflow: 'hidden', + textOverflow: 'ellipsis', + whiteSpace: 'nowrap', + }, + fixedItem: { + maxWidth: '150px', + overflow: 'hidden', + textOverflow: 'ellipsis', + whiteSpace: 'nowrap', + color: theme.palette.type === 'light' ? '#555' : '#ccc', + }, + contentPathItem: { + flexGrow: 1, + minWidth: 0, + color: theme.palette.type === 'light' ? '#333' : '#ddd', + }, + table: { + width: '100%', + borderCollapse: 'separate', + borderSpacing: '0 8px', + + '& th': { + backgroundColor: theme.palette.type === 'light' ? '#f5f5f5' : '#3c3c3c', + color: theme.palette.type === 'light' ? '#333' : '#fff', + fontWeight: 500, + }, + '& td': { + color: theme.palette.type === 'light' ? '#666' : '#bbb', + }, + '& thead th:first-child': { + backgroundColor: 'unset', + }, + '& thead th:nth-child(2)': { + borderTopLeftRadius: 8, + borderBottomLeftRadius: 8, + }, + '& thead th:last-child': { + borderTopRightRadius: 8, + borderBottomRightRadius: 8, + }, + '& tbody tr td:first-child': { + borderTopLeftRadius: 8, + borderBottomLeftRadius: 8, + }, + '& tbody tr td:last-child': { + borderTopRightRadius: 8, + borderBottomRightRadius: 8, + }, + '& tbody td:nth-child(2), & tbody td:last-child': { + wordBreak: 'break-all', + }, + }, + tableRow: { + borderRadius: '4px', + '&:hover': { + backgroundColor: theme.palette.type === 'light' ? '#f0f0f0' : '#3a3a3a', + }, + }, + '& :hover': { + cursor: 'default', + }, + }), +) + +export const Home = () => { + const classes = useStyles() + const repo = useRepository() + const localization = useLocalization().home + const { user } = useAuth() + + const [lastMinuteLogs, setLastMinuteLogs] = useState([]) + // const [myLogs, setMyLogs] = useState([]) + const [hasGetLogs, setHasGetLogs] = useState(false) + // const [hasGetTopLogsByUser, setHasGetTopLogsByUser] = useState(false) + const [canContentHistory, setCanContentHistory] = useState(false) + const [contentHistories, setContentHistories] = useState>({}) + + useEffect(() => { + async function getActionsAndLogs() { + try { + const { d } = await repo.getActions({ idOrPath: '/Root' }) + const actionNames = d.results.map((a: any) => a.Name) + + const canGetLogs = actionNames.includes('GetLogsForLastMinutes') + setCanContentHistory(actionNames.includes('GetTopLogsByContentId')) + // const canGetUserLogs = actionNames.includes('GetTopLogsByUser') + + setHasGetLogs(canGetLogs) + // setHasGetTopLogsByUser(canGetUserLogs) + + if (canGetLogs) { + await getLatestChanges() + } else { + setLastMinuteLogs([]) + } + // if (canGetUserLogs) await getMyChanges() + } catch (error: any) { + console.error('Fetching actions failed:', error.message) + setCanContentHistory(false) + setHasGetLogs(false) + setLastMinuteLogs([]) + } + } + + async function getLatestChanges() { + try { + const response = await repo.executeAction({ + idOrPath: '/Root', + name: 'LogEntries/GetLogsForLastMinutes', + method: 'GET', + oDataOptions: { + limit: latestChangesLimit, + minutes: latestChangesWindowInMinutes, + top: latestChangesLimit, + } as any, + }) + + if (response) { + setLastMinuteLogs(response.filter((res: any) => res.ContentPath !== '/Root/System/Cache/DatabaseUsage.cache')) + } else { + setHasGetLogs(false) + } + } catch (error: any) { + console.error('GetLogsForLastMinutes error:', error.message) + setHasGetLogs(false) + } + } + + // async function getMyChanges() { + // try { + // const response = await repo.executeAction({ + // idOrPath: '/Root', + // name: 'LogEntries/GetTopLogsByUser', + // method: 'GET', + // oDataOptions: { + // userName: user?.LoginName, + // limit: 100, + // minutes: 2400, + // } as any, + // }) + // // if (response) { + // // setMyLogs(response) + // // } else { + // // setHasGetTopLogsByUser(false) + // // } + // } catch (error: any) { + // console.error('GetTopLogsByUser error:', error.message) + // setHasGetTopLogsByUser(false) + // } + // } + + getActionsAndLogs() + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []) + + const getTable = (log: any) => { + const changes = log.ExtendedProperties?.ChangedData + if (!changes) return null + const rows = changes + .map((change: any[]) => { + const nameObj = change.find((obj) => obj.name) + const oldValueObj = change.find((obj) => obj.oldValue) + const newValueObj = change.find((obj) => obj.newValue) + + if (!nameObj || nameObj.name === 'raw') return null + + return { + key: nameObj.name, + oldValue: oldValueObj?.oldValue ?? '', + newValue: newValueObj?.newValue ?? '', + } + }) + .filter(Boolean) + return ( + + + + + + {localization.oldValue} + + + {localization.newValue} + + + + + {rows.map((row: any, idx: any) => ( + + + {row.key.replace(/([a-z])([A-Z])/g, '$1 $2')} + + {row.oldValue} + {row.newValue} + + ))} + +
+ ) + } + + async function fetchContentHistory(contentId: string) { + try { + const response = await repo.executeAction({ + idOrPath: '/Root', + name: 'LogEntries/GetTopLogsByContentId', + method: 'GET', + oDataOptions: { contentId, limit: 10 } as any, + }) + setContentHistories((prev) => ({ + ...prev, + [contentId]: response || [], + })) + } catch (error: any) { + console.error('GetTopLogsByContentId error:', error.message) + } + } + + return !hasGetLogs ? ( + + ) : ( +
+
+ {hasGetLogs && ( +
+ +

{localization.latestChanges}

+ {lastMinuteLogs.map((log, index) => { + const hasChanges = log.ExtendedProperties?.ChangedData?.length > 0 + return ( + + } + aria-controls={`panel${index}-content`} + id={`panel${index}-header`} + className={classes.accordionSummary}> + + {log.LogDate ? DateTimeFormatter({ value: log.LogDate }) : ''} + + + {log.Message.replace(/([a-z])([A-Z])/g, '$1 $2') || ''} + + {log.UserName || ''} + + + {log.ContentPath || ''} + + + + {hasChanges && ( + {getTable(log)} + )} + {canContentHistory && ( + <> + fetchContentHistory(log.ContentId)} + style={{ margin: '8px' }}> + } + aria-controls="content-history-content" + id="content-history-header" + className={''}> + {localization.contentHistory} + + + {(contentHistories[log.ContentId] || []).map((historyLog, idx) => ( +
{getTable(historyLog)}
+ ))} +
+
+ + )} +
+ ) + })} +
+ )} + + {/* {hasGetTopLogsByUser && ( +
+

My Changes

+ {myLogs.map((log, index) => { + const hasChanges = log.ExtendedProperties?.ChangedData?.length > 0 + return ( + + } + aria-controls={`panel${index}-content`} + id={`panel${index}-header`} + className={classes.accordionSummary}> + + {log.LogDate ? DateTimeFormatter({ value: log.LogDate }) : ''} + + {log.Message || ''} + {log.UserName || ''} + + + {log.ContentPath || ''} + + + + {hasChanges && ( + {getTable(log)} + )} + + ) + })} +
+ )} */} +
+
+ ) +} diff --git a/apps/sensenet/src/components/Icon.tsx b/apps/sensenet/src/components/Icon.tsx index 237efa12a6..89be9d744f 100644 --- a/apps/sensenet/src/components/Icon.tsx +++ b/apps/sensenet/src/components/Icon.tsx @@ -184,18 +184,35 @@ const getIconByName = (name: string | undefined, options: IconOptions) => { } } -const getIconByPath = (icon: string | undefined, options: IconOptions) => { - if (!icon || !icon.startsWith('/')) { - return null - } - - return -} - /* eslint-disable react/display-name */ export const defaultContentResolvers: Array> = [ { - get: (item, options) => getIconByPath(item.Icon, options), + get: (item, options) => { + let icon = item.Icon + const name = item.Name?.toLowerCase() + const type = item.Type?.toLowerCase() + const path = item.Path?.toLowerCase() + if (!icon || !type || !path) { + return null + } else if (icon.toLowerCase() === 'excel') { + icon = '/Root/System/Images/Icons/colors/csv.svg' + } else if (icon.toLowerCase() === 'word') { + icon = '/Root/System/Images/Icons/colors/word.svg' + } else if (icon.toLowerCase() === 'acrobat' || icon.toLowerCase() === 'adobe') { + icon = '/Root/System/Images/Icons/colors/pdf.svg' + } else if (name.endsWith('.xls') || name.endsWith('.xlsx') || name.endsWith('.xlsm')) { + icon = '/Root/System/Images/Icons/colors/xls.svg' + } else if (type.endsWith('file')) { + if (path.endsWith('.csv')) { + icon = '/Root/System/Images/Icons/colors/csv.svg' + } else if (path.endsWith('.svg')) { + icon = '/Root/System/Images/Icons/colors/file_img.svg' + } + } else if (!icon.startsWith('/')) { + return null + } + return + }, }, { get: (item, options) => @@ -313,10 +330,15 @@ export const IconComponent: FunctionComponent<{ ...defaultNotificationResolvers, ] const defaultIcon = props.defaultIcon || || null - const assignedResolver = resolvers.find((r) => (r.get(props.item, options) ? true : false)) - if (assignedResolver) { - return assignedResolver.get(props.item, options)! + + for (const resolver of resolvers) { + const icon = resolver.get(props.item, options) + + if (icon) { + return icon + } } + return defaultIcon } diff --git a/apps/sensenet/src/components/IconFromPath.tsx b/apps/sensenet/src/components/IconFromPath.tsx index 641e1a4d87..27c280d6cd 100644 --- a/apps/sensenet/src/components/IconFromPath.tsx +++ b/apps/sensenet/src/components/IconFromPath.tsx @@ -1,48 +1,99 @@ import { PathHelper } from '@sensenet/client-utils' -import React, { memo, useEffect, useState } from 'react' +import React, { memo, useEffect, useMemo, useState } from 'react' import { IconOptions } from './Icon' +// Global cache for icons +const iconCache = new Map() +const iconRequestCache = new Map>() + +const loadIcon = (path: string, repo: IconOptions['repo']) => { + if (iconCache.has(path)) { + return Promise.resolve(iconCache.get(path)!) + } + + const pendingRequest = iconRequestCache.get(path) + + if (pendingRequest) { + return pendingRequest + } + + const imageUrl = PathHelper.joinPaths(repo.configuration.repositoryUrl, path) + const request = (async () => { + if (!path.endsWith('.svg')) { + iconCache.set(path, imageUrl) + return imageUrl + } + + try { + const response = await repo.fetch(imageUrl, { cache: 'force-cache' }) + + if (!response.ok) { + iconCache.set(path, null) + return null + } + + const svg = await response.text() + const resizedSvg = svg.replace('width=', 'width="24px" oldwidth=').replace('height=', 'height="24px" oldheight=') + + iconCache.set(path, resizedSvg) + return resizedSvg + } catch { + iconCache.set(path, null) + return null + } + })() + + iconRequestCache.set(path, request) + request.finally(() => iconRequestCache.delete(path)) + + return request +} + const IconFromPath = ({ path, options }: { path: string; options: IconOptions }) => { - const [icon, setIcon] = useState(null) + const { repo, style } = options + const [icon, setIcon] = useState(() => iconCache.get(path) || null) useEffect(() => { - async function fetchData() { - if (options.repo.iconCache.has(path)) { - const cachedData = options.repo.iconCache.get(path) ?? '' - setIcon(cachedData) - return - } + let isMounted = true + + if (iconCache.has(path)) { + setIcon(iconCache.get(path) || null) + return + } - const imageUrl = PathHelper.joinPaths(options.repo.configuration.repositoryUrl, path) - - if (path.endsWith('.svg')) { - const fetchedSvg = await options.repo.fetch(imageUrl, { cache: 'force-cache' }) - if (!fetchedSvg.ok) { - return - } - const svg = await fetchedSvg.text().catch(() => '') - options.repo.iconCache.set(path, svg) - setIcon(svg) - return + setIcon(null) + loadIcon(path, repo).then((loadedIcon) => { + if (isMounted) { + setIcon(loadedIcon) } + }) - options.repo.iconCache.set(path, imageUrl) - setIcon(imageUrl) + return () => { + isMounted = false } - fetchData() - }, [options.repo, path]) + }, [path, repo]) - if (!icon) { - return null - } + // Memoize the rendered output to prevent unnecessary DOM updates + const renderedIcon = useMemo(() => { + if (!icon) return null - if (path.endsWith('.svg')) { - return - } + return path.endsWith('.svg') ? ( +