Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/Create.md
Original file line number Diff line number Diff line change
Expand Up @@ -623,7 +623,9 @@ const CreateRelatedCommentButton = () => {
<CreateButton
resource="comments"
to={{
search: `?source=${JSON.stringify({ post_id: record.id })}`,
search: `?source=${encodeURIComponent(
JSON.stringify({ post_id: record.id })
)}`,
}}
/>
);
Expand Down
4 changes: 3 additions & 1 deletion docs/FilteringTutorial.md
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,9 @@ const LinkToRelatedProducts = () => {
component={LinkBase}
to={{
pathname: '/posts',
search: `filter=${JSON.stringify({ category_id: record.id })}`,
search: `filter=${encodeURIComponent(
JSON.stringify({ category_id: record.id })
)}`,
}}
>
All posts with the category {record.name} ;
Expand Down
2 changes: 1 addition & 1 deletion docs/List.md
Original file line number Diff line number Diff line change
Expand Up @@ -627,7 +627,7 @@ By default, clicking this button will:
2. Transform the result into a CSV string,
3. Download the CSV file.

The columns of the CSV file match all the fields of the records in the `dataProvider` response. That means that the export doesn't take into account the selection and ordering of fields in your `<List>` via `Field` components. If you want to customize the result, pass a custom `exporter` function to the `<List>`. This function will receive the data from the `dataProvider` (after step 1) and replace steps 2-3 (i.e. it's in charge of transforming, converting, and downloading the file).
The columns of the CSV file match all the fields of the records in the `dataProvider` response. That means that the export doesn't take into account the selection and ordering of fields in your `<List>` via `Field` components. Every cell is enclosed in double quotes, and text values starting with `=`, `+`, `-`, `@`, a tab or a carriage return (except signed numbers) are prefixed with a single quote, so that spreadsheet applications display them as text. If you want to customize the result, pass a custom `exporter` function to the `<List>`. This function will receive the data from the `dataProvider` (after step 1) and replace steps 2-3 (i.e. it's in charge of transforming, converting, and downloading the file).

**Tip**: For CSV conversion, you can import [jsonexport](https://github.com/kauegimenes/jsonexport#browser-import-examples), a JSON to CSV converter which is already a react-admin dependency. And for CSV download, take advantage of react-admin's `downloadCSV` function.

Expand Down
6 changes: 5 additions & 1 deletion docs_headless/src/content/docs/CreateBase.md
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,11 @@ const CreateRelatedCommentButton = () => {
const navigate = useNavigate();

const handleClick = () => {
navigate(`/comments/create?source=${JSON.stringify({ post_id: record.id })}`);
navigate(
`/comments/create?source=${encodeURIComponent(
JSON.stringify({ post_id: record.id })
)}`
);
};

return (
Expand Down
4 changes: 3 additions & 1 deletion docs_headless/src/content/docs/FilteringTutorial.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@ const LinkToRelatedProducts = () => {
<Link
to={{
pathname: '/posts',
search: `filter=${JSON.stringify({ category_id: record.id })}`,
search: `filter=${encodeURIComponent(
JSON.stringify({ category_id: record.id })
)}`,
}}
>
All posts with the category {record.name}
Expand Down
2 changes: 1 addition & 1 deletion docs_headless/src/content/docs/ListBase.md
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ By default, clicking an export button will:
2. Transform the result into a CSV string,
3. Download the CSV file.

The columns of the CSV file match all the fields of the records in the `dataProvider` response. If you want to customize the result, pass a custom `exporter` function to the `<ListBase>`. This function will receive the data from the `dataProvider` and is in charge of transforming, converting, and downloading the file.
The columns of the CSV file match all the fields of the records in the `dataProvider` response. Every cell is enclosed in double quotes, and text values starting with `=`, `+`, `-`, `@`, a tab or a carriage return (except signed numbers) are prefixed with a single quote, so that spreadsheet applications display them as text. If you want to customize the result, pass a custom `exporter` function to the `<ListBase>`. This function will receive the data from the `dataProvider` and is in charge of transforming, converting, and downloading the file.

**Tip**: For CSV conversion, you can import [jsonexport](https://github.com/kauegimenes/jsonexport#browser-import-examples), a JSON to CSV converter which is already a ra-core dependency. And for CSV download, take advantage of ra-core's `downloadCSV` function.

Expand Down
69 changes: 69 additions & 0 deletions packages/ra-core/src/export/defaultExporter.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { defaultExporter } from './defaultExporter';
import { downloadCSV } from './downloadCSV';

jest.mock('./downloadCSV', () => ({ downloadCSV: jest.fn() }));

const exportToCsv = (records: any[]): string => {
(downloadCSV as jest.Mock).mockClear();
defaultExporter(records, jest.fn(), {} as any, 'posts');
return (downloadCSV as jest.Mock).mock.calls[0][0];
};

describe('defaultExporter', () => {
it('should export records as CSV', () => {
expect(
exportToCsv([
{ id: 1, title: 'Hello', views: -5, price: '-1.5' },
{ id: 2, title: 'World, "quoted"', views: 3, price: '+2' },
])
).toEqual(
'"id","title","views","price"\n"1","Hello","-5","-1.5"\n"2","World, ""quoted""","3","+2"'
);
expect((downloadCSV as jest.Mock).mock.calls[0][1]).toEqual('posts');
});

it('should prefix with a quote the values and headers starting with =, +, -, @ or a tab', () => {
expect(
exportToCsv([
{
id: 1,
name: '== Title ==',
phone: '+33 6 12 34 56 78',
handle: '@alice',
'-note': '\t-x',
},
]).split('\n')
).toEqual([
`"id","name","phone","handle","'-note"`,
`"1","'== Title ==","'+33 6 12 34 56 78","'@alice","'\t-x"`,
]);
});

it('should quote the values containing another separator', () => {
expect(exportToCsv([{ id: 1, name: 'foo;=bar' }])).toEqual(
'"id","name"\n"1","foo;=bar"'
);
});

it('should quote the values containing a lone carriage return', () => {
expect(exportToCsv([{ id: 1, name: 'Bob\r2', role: 'admin' }])).toEqual(
'"id","name","role"\n"1","Bob\r2","admin"'
);
});

it('should quote the column headers coming from record keys', () => {
const csv = exportToCsv([
{
id: 1,
title: 'Hello',
meta: { 'x\ny,z': true, 'a,b': 1 },
'say "hi"': 3,
},
]);
expect(csv.split('\n')).toEqual([
'"id","title","meta.x',
'y,z","meta.a,b","say ""hi"""',
'"1","Hello","true","1","3"',
]);
});
});
25 changes: 24 additions & 1 deletion packages/ra-core/src/export/defaultExporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,28 @@ import jsonExport from 'jsonexport/dist/index.js';
import { downloadCSV } from './downloadCSV';
import { Exporter } from '../types';

// Spreadsheets read a cell starting with one of these characters as a formula,
// so it is prefixed with a single quote to be displayed as text.
// Signed numbers are kept as is.
const escapeFormula = (value: string) =>
/^[=+\-@\t\r]/.test(value) && !/^[+-]?\d+([.,]\d+)?$/.test(value)
? `'${value}`
: value;
Comment thread
ThieryMichel marked this conversation as resolved.
Resolved

// With forceTextDelimiter, jsonexport wraps the headers in quotes before
// calling mapHeaders, without escaping the quotes they contain
const escapeHeader = (header: string) =>
`"${escapeFormula(header.slice(1, -1)).replace(/"/g, '""')}"`;

export const defaultExporter: Exporter = (data, _, __, resource) =>
jsonExport(data, (err, csv) => downloadCSV(csv, resource));
jsonExport(
data,
{
typeHandlers: { String: escapeFormula },
mapHeaders: escapeHeader,
// spreadsheets using another separator (e.g. ; in some locales)
// would otherwise split cells inside unquoted values
forceTextDelimiter: true,
},
(err, csv) => downloadCSV(csv, resource)
);
25 changes: 25 additions & 0 deletions packages/ra-ui-materialui/src/field/EmailField.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,31 @@ describe('<EmailField />', () => {
expect(link.innerHTML).toEqual(halUrl);
});

it('should encode the mailto delimiters in the value', () => {
const email = 'alice%40example.com?subject=hello&cc=bob@example.com';
const record = { id: 123, email };
const { getByText } = render(
<EmailField record={record} source="email" />
);
const link = getByText(email) as HTMLAnchorElement;
expect(link.href).toEqual(
'mailto:alice%2540example.com%3Fsubject%3Dhello%26cc%3Dbob@example.com'
);
expect(link.search).toEqual('');
expect(link.hash).toEqual('');
expect(decodeURIComponent(link.pathname)).toEqual(email);
});

it('should keep several addresses in the mailto link', () => {
const emails = 'foo@bar.com,baz@bar.com;qux@bar.com';
const record = { id: 123, email: emails };
const { getByText } = render(
<EmailField record={record} source="email" />
);
const link = getByText(emails) as HTMLAnchorElement;
expect(link.href).toEqual(`mailto:${emails}`);
});

it('should use custom className', () => {
const { getByText } = render(
<EmailField
Expand Down
12 changes: 11 additions & 1 deletion packages/ra-ui-materialui/src/field/EmailField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ const EmailFieldImpl = <
return (
<StyledLink
className={className}
href={`mailto:${value}`}
href={getMailtoUrl(value)}
onClick={stopPropagation}
variant="body2"
{...sanitizeFieldRestProps(rest)}
Expand All @@ -59,6 +59,16 @@ export interface EmailFieldProps<
> extends FieldProps<RecordType>,
Omit<LinkProps, 'textAlign'> {}

// "?", "&", "=", "#" and "%" are legal in an email address but are delimiters
// in a mailto: URL, so they are percent-encoded. "," and ";" are kept to
// separate several addresses.
// @see https://www.rfc-editor.org/rfc/rfc6068#section-2
const getMailtoUrl = (value: any) =>
`mailto:${String(value).replace(
/[^\w@.+\-,;\u0080-\uffff]/g,
encodeURIComponent
)}`;

// useful to prevent click bubbling in a Datagrid with rowClick
const stopPropagation = e => e.stopPropagation();

Expand Down
27 changes: 27 additions & 0 deletions packages/ra-ui-materialui/src/field/ReferenceManyCount.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,33 @@ describe('<ReferenceManyCount />', () => {
).toHaveAttribute('href', '/comments?filter={"post_id":1}');
});

it('should encode the record value in the link', async () => {
render(
<Wrapper
dataProvider={{
getManyReference: () =>
Promise.resolve({ data: [], total: 3 }),
}}
>
<ReferenceManyCount
record={{ id: 'c++#&perPage=1%22' }}
reference="comments"
target="post_id"
link
/>
</Wrapper>
);
const href = (
await screen.findByRole('link', { name: '3' })
).getAttribute('href') as string;
const { searchParams, hash } = new URL(href, 'http://localhost');
expect(hash).toEqual('');
expect(Array.from(searchParams.keys())).toEqual(['filter']);
expect(JSON.parse(searchParams.get('filter') as string)).toEqual({
post_id: 'c++#&perPage=1%22',
});
});

it('should render an error icon when the request fails', async () => {
jest.spyOn(console, 'error').mockImplementation(() => {});
render(<ErrorState />);
Expand Down
5 changes: 3 additions & 2 deletions packages/ra-ui-materialui/src/field/ReferenceManyCount.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { FieldProps } from './types';
import { sanitizeFieldRestProps } from './sanitizeFieldRestProps';
import { Link } from '../Link';
import { Offline } from '../Offline';
import { getFilterSearch } from '../list/getFilterSearch';

/**
* Fetch and render the number of records related to the current one
Expand Down Expand Up @@ -85,10 +86,10 @@ export const ReferenceManyCount = <RecordType extends RaRecord = RaRecord>(
resource: reference,
type: 'list',
}),
search: `filter=${JSON.stringify({
search: getFilterSearch({
...(filter || {}),
[target]: get(record, source),
})}`,
}),
}}
onClick={e => e.stopPropagation()}
>
Expand Down
24 changes: 24 additions & 0 deletions packages/ra-ui-materialui/src/list/Count.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,28 @@ describe('<Count />', () => {
signal: undefined,
});
});
it('should encode the filter in the link', async () => {
render(
<Wrapper
dataProvider={{
getList: () => Promise.resolve({ data: [], total: 3 }),
}}
>
<Count
resource="posts"
filter={{ tag: 'c++#&perPage=1' }}
link
/>
</Wrapper>
);
const href = (
await screen.findByRole('link', { name: '3' })
).getAttribute('href') as string;
const { searchParams, hash } = new URL(href, 'http://localhost');
expect(hash).toEqual('');
expect(Array.from(searchParams.keys())).toEqual(['filter']);
expect(JSON.parse(searchParams.get('filter') as string)).toEqual({
tag: 'c++#&perPage=1',
});
});
});
3 changes: 2 additions & 1 deletion packages/ra-ui-materialui/src/list/Count.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { Typography, TypographyProps, CircularProgress } from '@mui/material';
import ErrorIcon from '@mui/icons-material/Error';

import { Link } from '../Link';
import { getFilterSearch } from './getFilterSearch';

/**
* Fetch and render the number of records of a given resource
Expand Down Expand Up @@ -71,7 +72,7 @@ export const Count = (props: CountProps) => {
<Link
to={{
pathname: createPath({ resource, type: 'list' }),
search: filter ? `filter=${JSON.stringify(filter)}` : undefined,
search: filter ? getFilterSearch(filter) : undefined,
}}
variant="body2"
onClick={e => e.stopPropagation()}
Expand Down
4 changes: 4 additions & 0 deletions packages/ra-ui-materialui/src/list/getFilterSearch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// Only the characters that the list can't read back are percent-encoded
// ("%", "&" and "+" for query-string, "#" for react-router), so that the URL stays readable
export const getFilterSearch = (filter: object) =>
`filter=${JSON.stringify(filter).replace(/[%&#+]/g, encodeURIComponent)}`;
Loading