diff --git a/Dockerfile b/Dockerfile index d2c04299d..b52196de9 100644 --- a/Dockerfile +++ b/Dockerfile @@ -13,10 +13,7 @@ COPY . . # Install dependencies RUN yarn install -# Build packages (required for the app to work) -RUN yarn build - -# Build the app bundle in production mode (avoids runtime webpack rebuild) +# 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 diff --git a/apps/sensenet/README.md b/apps/sensenet/README.md index 34ec0099e..24f73527c 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. diff --git a/apps/sensenet/content-types/AUIApplication.xml b/apps/sensenet/content-types/AUIApplication.xml new file mode 100644 index 000000000..f5382c4a8 --- /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 000000000..e5afe50aa --- /dev/null +++ b/apps/sensenet/docs/auiapplications.md @@ -0,0 +1,348 @@ +# 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 + } + 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 +} +``` + +Requests are restricted to the current repository origin. Cross-repository and arbitrary external requests are rejected by the parent Admin UI. + +## 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 || new URL(document.referrer).origin +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 000000000..f2b6ff2d5 --- /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 000000000..d8a1eb055 --- /dev/null +++ b/apps/sensenet/examples/auiapplication-banner-images.html @@ -0,0 +1,278 @@ +
+
+

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/src/components/BatchActions.tsx b/apps/sensenet/src/components/BatchActions.tsx index 6e8ab84ff..15b45ae58 100644 --- a/apps/sensenet/src/components/BatchActions.tsx +++ b/apps/sensenet/src/components/BatchActions.tsx @@ -1,11 +1,16 @@ -import { createStyles, IconButton, makeStyles, Theme, Tooltip } from '@material-ui/core' +import { CircularProgress, createStyles, IconButton, makeStyles, Theme, Tooltip } from '@material-ui/core' +import ArchiveIcon from '@material-ui/icons/Archive' +import AppsIcon from '@material-ui/icons/Apps' import DeleteIcon from '@material-ui/icons/Delete' import FileCopyIcon from '@material-ui/icons/FileCopy' import FileCopyOutlinedIcon from '@material-ui/icons/FileCopyOutlined' -import { CurrentContentContext } from '@sensenet/hooks-react' +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) => @@ -36,7 +41,11 @@ export const BatchActions = () => { 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(() => { @@ -49,8 +58,96 @@ export const BatchActions = () => { } }, [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 ? : } + + + 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 index 558076674..69dbefe4b 100644 --- a/apps/sensenet/src/components/Home.tsx +++ b/apps/sensenet/src/components/Home.tsx @@ -16,12 +16,16 @@ 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 { 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: { @@ -178,7 +182,7 @@ export const Home = () => { const classes = useStyles() const repo = useRepository() const localization = useLocalization().home - // const { user } = useAuth() + const { user } = useAuth() const [lastMinuteLogs, setLastMinuteLogs] = useState([]) // const [myLogs, setMyLogs] = useState([]) @@ -200,10 +204,17 @@ export const Home = () => { setHasGetLogs(canGetLogs) // setHasGetTopLogsByUser(canGetUserLogs) - if (canGetLogs) await getLatestChanges() + 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([]) } } @@ -214,8 +225,9 @@ export const Home = () => { name: 'LogEntries/GetLogsForLastMinutes', method: 'GET', oDataOptions: { - top: 100, - minutes: 600, + limit: latestChangesLimit, + minutes: latestChangesWindowInMinutes, + top: latestChangesLimit, } as any, }) @@ -327,6 +339,11 @@ export const Home = () => {
{hasGetLogs && (
+

{localization.latestChanges}

{lastMinuteLogs.map((log, index) => { const hasChanges = log.ExtendedProperties?.ChangedData?.length > 0 diff --git a/apps/sensenet/src/components/Icon.tsx b/apps/sensenet/src/components/Icon.tsx index 4bfc42af6..89be9d744 100644 --- a/apps/sensenet/src/components/Icon.tsx +++ b/apps/sensenet/src/components/Icon.tsx @@ -330,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 2528cd91c..27c280d6c 100644 --- a/apps/sensenet/src/components/IconFromPath.tsx +++ b/apps/sensenet/src/components/IconFromPath.tsx @@ -3,68 +3,86 @@ import React, { memo, useEffect, useMemo, useState } from 'react' import { IconOptions } from './Icon' // Global cache for icons -const iconCache = new Map() +const iconCache = new Map() +const iconRequestCache = new Map>() -const IconFromPath = ({ path, options }: { path: string; options: IconOptions }) => { - const [icon, setIcon] = useState(iconCache.get(path) || null) +const loadIcon = (path: string, repo: IconOptions['repo']) => { + if (iconCache.has(path)) { + return Promise.resolve(iconCache.get(path)!) + } - useEffect(() => { - const controller = new AbortController() - const { signal } = controller - - const fetchIcon = async () => { - // Check cache first - if (iconCache.has(path)) { - setIcon(iconCache.get(path)!) - return - } + const pendingRequest = iconRequestCache.get(path) - const imageUrl = PathHelper.joinPaths(options.repo.configuration.repositoryUrl, path) - - if (path.endsWith('.svg')) { - try { - const response = await options.repo.fetch(imageUrl, { cache: 'force-cache', signal }) - if (!response.ok) return - const svg = await response.text() - const resizedSvg = svg - .replace('width=', 'width="24px" oldwidth=') - .replace('height=', 'height="24px" oldheight=') - if (!signal.aborted) { - iconCache.set(path, resizedSvg) // Store in cache - setIcon(resizedSvg) - } - } catch (err) { - if ((err as any).name !== 'AbortError') { - console.error('Failed to load SVG:', err) - } - } - } else { - if (!signal.aborted) { - iconCache.set(path, imageUrl) // Store in cache - setIcon(imageUrl) - } + 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 } + })() - if (!icon) { - fetchIcon() + iconRequestCache.set(path, request) + request.finally(() => iconRequestCache.delete(path)) + + return request +} + +const IconFromPath = ({ path, options }: { path: string; options: IconOptions }) => { + const { repo, style } = options + const [icon, setIcon] = useState(() => iconCache.get(path) || null) + + useEffect(() => { + let isMounted = true + + if (iconCache.has(path)) { + setIcon(iconCache.get(path) || null) + return } + setIcon(null) + loadIcon(path, repo).then((loadedIcon) => { + if (isMounted) { + setIcon(loadedIcon) + } + }) + return () => { - controller.abort() + isMounted = false } - }, [path, options.repo, icon]) + }, [path, repo]) // Memoize the rendered output to prevent unnecessary DOM updates const renderedIcon = useMemo(() => { if (!icon) return null return path.endsWith('.svg') ? ( -