feat: print action (#652)

* feat: print done

* fix: modify print content

* refactor: optimize the print feature

* refactor: change formRef to formBlockRef
This commit is contained in:
SemmyWong 2022-07-20 14:12:18 +08:00 committed by GitHub
parent 5d76b996ca
commit 21619f53c5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 168 additions and 108 deletions

View File

@ -39,6 +39,7 @@
"react-image-lightbox": "^5.1.4", "react-image-lightbox": "^5.1.4",
"react-quill": "^1.3.5", "react-quill": "^1.3.5",
"react-router-dom": "^5.2.0", "react-router-dom": "^5.2.0",
"react-to-print": "^2.14.7",
"use-deep-compare-effect": "^1.8.1" "use-deep-compare-effect": "^1.8.1"
}, },
"peerDependencies": { "peerDependencies": {

View File

@ -1,9 +1,8 @@
import { createForm } from '@formily/core'; import { createForm } from '@formily/core';
import { useField, useFieldSchema } from '@formily/react'; import { useField } from '@formily/react';
import { Spin } from 'antd'; import { Spin } from 'antd';
import React, { createContext, useContext, useEffect, useMemo } from 'react'; import React, { createContext, useContext, useEffect, useMemo, useRef } from 'react';
import { BlockProvider, useBlockRequestContext } from './BlockProvider'; import { BlockProvider, useBlockRequestContext } from './BlockProvider';
import { useCollectionManager } from '../collection-manager';
export const FormBlockContext = createContext<any>({}); export const FormBlockContext = createContext<any>({});
@ -18,6 +17,7 @@ const InternalFormBlockProvider = (props) => {
[], [],
); );
const { resource, service } = useBlockRequestContext(); const { resource, service } = useBlockRequestContext();
const formBlockRef = useRef();
if (service.loading) { if (service.loading) {
return <Spin />; return <Spin />;
} }
@ -30,9 +30,10 @@ const InternalFormBlockProvider = (props) => {
service, service,
resource, resource,
updateAssociationValues: [], updateAssociationValues: [],
formBlockRef,
}} }}
> >
{props.children} <div ref={formBlockRef}>{props.children}</div>
</FormBlockContext.Provider> </FormBlockContext.Provider>
); );
}; };

View File

@ -4,6 +4,7 @@ import parse from 'json-templates';
import get from 'lodash/get'; import get from 'lodash/get';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useHistory } from 'react-router-dom'; import { useHistory } from 'react-router-dom';
import { useReactToPrint } from 'react-to-print';
import { useFormBlockContext } from '../..'; import { useFormBlockContext } from '../..';
import { useAPIClient } from '../../api-client'; import { useAPIClient } from '../../api-client';
import { useCollection } from '../../collection-manager'; import { useCollection } from '../../collection-manager';
@ -398,6 +399,28 @@ export const useDestroyActionProps = () => {
}; };
}; };
export const useDetailPrintActionProps = () => {
const { formBlockRef } = useFormBlockContext();
const printHandler = useReactToPrint({
content: () => formBlockRef.current,
pageStyle: `@media print {
* {
margin: 0;
}
div.ant-formily-layout>div:first-child {
overflow: hidden; height: 0;
}
}`,
});
return {
async onClick() {
printHandler();
},
};
};
export const useBulkDestroyActionProps = () => { export const useBulkDestroyActionProps = () => {
const { field } = useBlockRequestContext(); const { field } = useBlockRequestContext();
const { resource, service } = useBlockRequestContext(); const { resource, service } = useBlockRequestContext();
@ -422,7 +445,7 @@ export const useRefreshActionProps = () => {
service?.refresh?.(); service?.refresh?.();
}, },
}; };
} };
export const useDetailsPaginationProps = () => { export const useDetailsPaginationProps = () => {
const ctx = useDetailsBlockContext(); const ctx = useDetailsBlockContext();

View File

@ -553,4 +553,5 @@ export default {
"Regular expression": "Pattern", "Regular expression": "Pattern",
"Enabled languages": "Enabled languages", "Enabled languages": "Enabled languages",
"View all plugins": "View all plugins", "View all plugins": "View all plugins",
"Print": "Print",
} }

View File

@ -649,4 +649,5 @@ export default {
"Province/city/area name": "省市区名称", "Province/city/area name": "省市区名称",
"Enabled languages": "启用的语言", "Enabled languages": "启用的语言",
"View all plugins": "查看所有插件", "View all plugins": "查看所有插件",
"Print": "打印",
} }

View File

@ -3,8 +3,8 @@ import { css } from '@emotion/css';
import { observer, RecursionField, Schema, useField, useFieldSchema } from '@formily/react'; import { observer, RecursionField, Schema, useField, useFieldSchema } from '@formily/react';
import { uid } from '@formily/shared'; import { uid } from '@formily/shared';
import cls from 'classnames'; import cls from 'classnames';
import React, { createContext, useContext, useState } from 'react'; import React, { createContext, useContext, useEffect, useRef, useState } from 'react';
import { useSchemaInitializer } from '../../../'; import { useFormBlockContext, useSchemaInitializer } from '../../../';
import { DndContext } from '../../common/dnd-context'; import { DndContext } from '../../common/dnd-context';
const GridRowContext = createContext(null); const GridRowContext = createContext(null);
@ -24,19 +24,18 @@ const ColDivider = (props) => {
backgroundColor: isOver ? 'rgba(241, 139, 98, .1)' : undefined, backgroundColor: isOver ? 'rgba(241, 139, 98, .1)' : undefined,
}; };
const dndContext = useDndContext() const dndContext = useDndContext();
const activeSchema: Schema | undefined = dndContext.active?.data.current?.schema?.parent const activeSchema: Schema | undefined = dndContext.active?.data.current?.schema?.parent;
const blocksLength: number = activeSchema ? Object.keys(activeSchema.properties).length : 0; const blocksLength: number = activeSchema ? Object.keys(activeSchema.properties).length : 0;
let visible = true;
let visible = true
if (blocksLength === 1) { if (blocksLength === 1) {
if (props.first) { if (props.first) {
visible = activeSchema !== props.cols[0] visible = activeSchema !== props.cols[0];
} else { } else {
const currentSchema = props.cols[props.index] const currentSchema = props.cols[props.index];
const downSchema = props.cols[props.index + 1] const downSchema = props.cols[props.index + 1];
visible = activeSchema !== currentSchema && downSchema !== activeSchema visible = activeSchema !== currentSchema && downSchema !== activeSchema;
} }
} }
@ -68,23 +67,25 @@ const RowDivider = (props) => {
const [active, setActive] = useState(false); const [active, setActive] = useState(false);
const dndContext = useDndContext() const dndContext = useDndContext();
const currentSchema = props.rows[props.index] const currentSchema = props.rows[props.index];
const activeSchema = dndContext.active?.data.current?.schema?.parent.parent const activeSchema = dndContext.active?.data.current?.schema?.parent.parent;
const colsLength: number = activeSchema?.mapProperties((schema) => { const colsLength: number = activeSchema
return schema['x-component'] === 'Grid.Col' ?.mapProperties((schema) => {
}).filter(Boolean).length return schema['x-component'] === 'Grid.Col';
})
.filter(Boolean).length;
let visible = true let visible = true;
// col > 1 时不需要隐藏 // col > 1 时不需要隐藏
if (colsLength === 1) { if (colsLength === 1) {
if (props.first) { if (props.first) {
visible = activeSchema !== props.rows[0] visible = activeSchema !== props.rows[0];
} else { } else {
const downSchema = props.rows[props.index + 1] const downSchema = props.rows[props.index + 1];
visible = activeSchema !== currentSchema && downSchema !== activeSchema visible = activeSchema !== currentSchema && downSchema !== activeSchema;
} }
} }
@ -196,15 +197,20 @@ export const useGridRowContext = () => {
}; };
export const Grid: any = observer((props: any) => { export const Grid: any = observer((props: any) => {
const gridRef = useRef(null);
const field = useField(); const field = useField();
const fieldSchema = useFieldSchema(); const fieldSchema = useFieldSchema();
const { render } = useSchemaInitializer(fieldSchema['x-initializer']); const { render } = useSchemaInitializer(fieldSchema['x-initializer']);
const addr = field.address.toString(); const addr = field.address.toString();
const rows = useRowProperties(); const rows = useRowProperties();
const { setPrintContent } = useFormBlockContext();
useEffect(() => {
gridRef.current && setPrintContent?.(gridRef.current);
}, [gridRef.current]);
return ( return (
<GridContext.Provider value={{ fieldSchema, renderSchemaInitializer: render }}> <GridContext.Provider value={{ ref: gridRef, fieldSchema, renderSchemaInitializer: render }}>
<div className={'nb-grid'} style={{ position: 'relative' }}> <div className={'nb-grid'} style={{ position: 'relative' }} ref={gridRef}>
<DndWrapper dndContext={props.dndContext}> <DndWrapper dndContext={props.dndContext}>
<RowDivider <RowDivider
rows={rows} rows={rows}

View File

@ -1,7 +1,7 @@
import { Field } from '@formily/core'; import { Field } from '@formily/core';
import { observer, RecursionField, useField, useFieldSchema } from '@formily/react'; import { observer, RecursionField, useField, useFieldSchema } from '@formily/react';
import { toArr } from '@formily/shared'; import { toArr } from '@formily/shared';
import React, { useRef, useState } from 'react'; import React, { Fragment, useRef, useState } from 'react';
import { BlockAssociationContext, WithoutTableFieldResource } from '../../../block-provider'; import { BlockAssociationContext, WithoutTableFieldResource } from '../../../block-provider';
import { CollectionProvider, useCollection, useCollectionManager } from '../../../collection-manager'; import { CollectionProvider, useCollection, useCollectionManager } from '../../../collection-manager';
import { RecordProvider, useRecord } from '../../../record-provider'; import { RecordProvider, useRecord } from '../../../record-provider';
@ -27,12 +27,12 @@ export const ReadPrettyRecordPicker: React.FC = observer((props: any) => {
const collectionField = getField(fieldSchema.name) || getCollectionJoinField(fieldSchema?.['x-collection-field']); const collectionField = getField(fieldSchema.name) || getCollectionJoinField(fieldSchema?.['x-collection-field']);
const [record, setRecord] = useState({}); const [record, setRecord] = useState({});
const compile = useCompile(); const compile = useCompile();
const ellipsisWithTooltipRef = useRef<IEllipsisWithTooltipRef>(); const ellipsisWithTooltipRef = useRef<IEllipsisWithTooltipRef>();
const renderRecords = () => const renderRecords = () =>
toArr(field.value).map((record, index, arr) => { toArr(field.value).map((record, index, arr) => {
return ( return (
<> <Fragment key={`${record.id}_${index}`}>
<span> <span>
<a <a
onClick={(e) => { onClick={(e) => {
@ -47,7 +47,7 @@ export const ReadPrettyRecordPicker: React.FC = observer((props: any) => {
</a> </a>
</span> </span>
{index < arr.length - 1 ? <span style={{ marginRight: 4, color: '#aaa' }}>, </span> : null} {index < arr.length - 1 ? <span style={{ marginRight: 4, color: '#aaa' }}>, </span> : null}
</> </Fragment>
); );
}); });
@ -70,16 +70,12 @@ export const ReadPrettyRecordPicker: React.FC = observer((props: any) => {
return collectionFieldNames && collectionFieldNames.length > 2 ? ( return collectionFieldNames && collectionFieldNames.length > 2 ? (
<RecordProvider record={recordCtx[collectionFieldNames[1]]}> <RecordProvider record={recordCtx[collectionFieldNames[1]]}>
<RecordProvider record={record}> <RecordProvider record={record}>{renderWithoutTableFieldResourceProvider()}</RecordProvider>
{renderWithoutTableFieldResourceProvider()}
</RecordProvider>
</RecordProvider> </RecordProvider>
) : ( ) : (
<RecordProvider record={record}> <RecordProvider record={record}>{renderWithoutTableFieldResourceProvider()}</RecordProvider>
{renderWithoutTableFieldResourceProvider()}
</RecordProvider>
); );
} };
return collectionField ? ( return collectionField ? (
<div> <div>

View File

@ -11,6 +11,6 @@ interface Options {
export const useProps = (props: any, options?: Options) => { export const useProps = (props: any, options?: Options) => {
const { useProps, ...props1 } = props; const { useProps, ...props1 } = props;
let props2 = useProps?.() || {}; let props2 = typeof useProps === 'function' ? useProps() : {};
return merge(props1 || {}, props2, options); return merge(props1 || {}, props2, options);
}; };

View File

@ -31,6 +31,15 @@ export const ReadPrettyFormActionInitializers = {
'x-decorator': 'ACLActionProvider', 'x-decorator': 'ACLActionProvider',
}, },
}, },
{
type: 'item',
title: '{{t("Print")}}',
component: 'PrintActionInitializer',
schema: {
'x-component': 'Action',
'x-decorator': 'ACLActionProvider',
},
},
], ],
}, },

View File

@ -1,6 +1,6 @@
import { FormOutlined, TableOutlined } from '@ant-design/icons'; import { FormOutlined, TableOutlined } from '@ant-design/icons';
import { FormDialog, FormLayout } from '@formily/antd'; import { FormDialog, FormLayout } from '@formily/antd';
import { ISchema, SchemaOptionsContext, useFieldSchema } from '@formily/react'; import { ISchema, SchemaOptionsContext } from '@formily/react';
import { merge } from '@formily/shared'; import { merge } from '@formily/shared';
import React, { useContext } from 'react'; import React, { useContext } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
@ -20,7 +20,7 @@ import {
createTableSelectorSchema, createTableSelectorSchema,
useCollectionDataSourceItems, useCollectionDataSourceItems,
useCurrentSchema, useCurrentSchema,
useRecordCollectionDataSourceItems useRecordCollectionDataSourceItems,
} from '../utils'; } from '../utils';
// Block // Block
@ -520,6 +520,20 @@ export const DestroyActionInitializer = (props) => {
return <ActionInitializer {...props} schema={schema} />; return <ActionInitializer {...props} schema={schema} />;
}; };
export const PrintActionInitializer = (props) => {
const schema = {
title: '{{ t("Print") }}',
'x-action': 'print',
'x-component': 'Action',
'x-designer': 'Action.Designer',
'x-component-props': {
icon: 'PrinterOutlined',
useProps: '{{ useDetailPrintActionProps }}',
},
};
return <ActionInitializer {...props} schema={schema} />;
};
export const BulkDestroyActionInitializer = (props) => { export const BulkDestroyActionInitializer = (props) => {
const schema = { const schema = {
title: '{{ t("Delete") }}', title: '{{ t("Delete") }}',
@ -688,7 +702,7 @@ export const RecordFormBlockInitializer = (props) => {
export const RecordReadPrettyFormBlockInitializer = (props) => { export const RecordReadPrettyFormBlockInitializer = (props) => {
const { onCreateBlockSchema, componentType, createBlockSchema, insert, ...others } = props; const { onCreateBlockSchema, componentType, createBlockSchema, insert, ...others } = props;
const { getTemplateSchemaByMode } = useSchemaTemplateManager(); const { getTemplateSchemaByMode } = useSchemaTemplateManager();
const collection = useCollection(); const collection = useCollection();
const association = useBlockAssociationContext(); const association = useBlockAssociationContext();
@ -749,9 +763,10 @@ export const RecordAssociationFormBlockInitializer = (props) => {
icon={<FormOutlined />} icon={<FormOutlined />}
{...others} {...others}
onClick={async ({ item }) => { onClick={async ({ item }) => {
const action = ['hasOne', 'belongsTo'].includes(field.type) ? 'get' : null; const action = ['hasOne', 'belongsTo'].includes(field.type) ? 'get' : null;
const actionInitializers = ['hasOne', 'belongsTo'].includes(field.type) ? 'UpdateFormActionInitializers' : 'CreateFormActionInitializers'; const actionInitializers = ['hasOne', 'belongsTo'].includes(field.type)
? 'UpdateFormActionInitializers'
: 'CreateFormActionInitializers';
if (item.template) { if (item.template) {
const s = await getTemplateSchemaByMode(item); const s = await getTemplateSchemaByMode(item);
@ -875,7 +890,7 @@ export const RecordAssociationDetailsBlockInitializer = (props) => {
items={useRecordCollectionDataSourceItems('Details', item, field.target, resource)} items={useRecordCollectionDataSourceItems('Details', item, field.target, resource)}
/> />
); );
} };
export const RecordAssociationCalendarBlockInitializer = (props) => { export const RecordAssociationCalendarBlockInitializer = (props) => {
const { item, onCreateBlockSchema, componentType, createBlockSchema, insert, ...others } = props; const { item, onCreateBlockSchema, componentType, createBlockSchema, insert, ...others } = props;
@ -896,75 +911,75 @@ export const RecordAssociationCalendarBlockInitializer = (props) => {
const s = await getTemplateSchemaByMode(item); const s = await getTemplateSchemaByMode(item);
insert(s); insert(s);
} else { } else {
const stringFields = collection?.fields const stringFields = collection?.fields
?.filter((field) => field.type === 'string') ?.filter((field) => field.type === 'string')
?.map((field) => { ?.map((field) => {
return { return {
label: field?.uiSchema?.title, label: field?.uiSchema?.title,
value: field.name, value: field.name,
}; };
});
const dateFields = collection?.fields
?.filter((field) => field.type === 'date')
?.map((field) => {
return {
label: field?.uiSchema?.title,
value: field.name,
};
});
const values = await FormDialog(t('Create calendar block'), () => {
return (
<SchemaComponentOptions scope={options.scope} components={{ ...options.components }}>
<FormLayout layout={'vertical'}>
<SchemaComponent
schema={{
properties: {
title: {
title: t('Title field'),
enum: stringFields,
required: true,
'x-component': 'Select',
'x-decorator': 'FormItem',
},
start: {
title: t('Start date field'),
enum: dateFields,
required: true,
default: 'createdAt',
'x-component': 'Select',
'x-decorator': 'FormItem',
},
end: {
title: t('End date field'),
enum: dateFields,
'x-component': 'Select',
'x-decorator': 'FormItem',
},
},
}}
/>
</FormLayout>
</SchemaComponentOptions>
);
}).open({
initialValues: {},
}); });
const dateFields = collection?.fields insert(
?.filter((field) => field.type === 'date') createCalendarBlockSchema({
?.map((field) => { collection: field.target,
return { resource,
label: field?.uiSchema?.title, association: resource,
value: field.name, fieldNames: {
}; ...values,
}); },
const values = await FormDialog(t('Create calendar block'), () => { }),
return (
<SchemaComponentOptions scope={options.scope} components={{ ...options.components }}>
<FormLayout layout={'vertical'}>
<SchemaComponent
schema={{
properties: {
title: {
title: t('Title field'),
enum: stringFields,
required: true,
'x-component': 'Select',
'x-decorator': 'FormItem',
},
start: {
title: t('Start date field'),
enum: dateFields,
required: true,
default: 'createdAt',
'x-component': 'Select',
'x-decorator': 'FormItem',
},
end: {
title: t('End date field'),
enum: dateFields,
'x-component': 'Select',
'x-decorator': 'FormItem',
},
},
}}
/>
</FormLayout>
</SchemaComponentOptions>
); );
}).open({
initialValues: {},
});
insert(
createCalendarBlockSchema({
collection: field.target,
resource,
association: resource,
fieldNames: {
...values,
},
}),
);
} }
}} }}
items={useRecordCollectionDataSourceItems('Calendar', item, field.target, resource)} items={useRecordCollectionDataSourceItems('Calendar', item, field.target, resource)}
/> />
); );
} };
export const RecordAssociationBlockInitializer = (props) => { export const RecordAssociationBlockInitializer = (props) => {
const { item, onCreateBlockSchema, componentType, createBlockSchema, insert, ...others } = props; const { item, onCreateBlockSchema, componentType, createBlockSchema, insert, ...others } = props;

View File

@ -17934,7 +17934,7 @@ prop-types-exact@^1.2.0:
object.assign "^4.1.0" object.assign "^4.1.0"
reflect.ownkeys "^0.2.0" reflect.ownkeys "^0.2.0"
prop-types@^15.5.10, prop-types@^15.5.8, prop-types@^15.7.1: prop-types@^15.5.10, prop-types@^15.5.8, prop-types@^15.7.1, prop-types@^15.8.1:
version "15.8.1" version "15.8.1"
resolved "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz#67d87bf1a694f48435cf332c24af10214a3140b5" resolved "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz#67d87bf1a694f48435cf332c24af10214a3140b5"
integrity sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg== integrity sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==
@ -18937,6 +18937,13 @@ react-test-renderer@^16.0.0-0, react-test-renderer@^16.13.1:
react-is "^16.8.6" react-is "^16.8.6"
scheduler "^0.19.1" scheduler "^0.19.1"
react-to-print@^2.14.7:
version "2.14.7"
resolved "https://registry.npmmirror.com/react-to-print/-/react-to-print-2.14.7.tgz#d288de0e573e6e63e203a48d4bad7a1759d18688"
integrity sha512-lWVVAs9Co25uyE0toxcWeFsmaZObwUozXrJD9WMpDPclpBgk+WIzxlt3Q3omL/BCBG/cpf0XNvhayUWa+99YGw==
dependencies:
prop-types "^15.8.1"
react@16.x, react@^16.8.6: react@16.x, react@^16.8.6:
version "16.14.0" version "16.14.0"
resolved "https://registry.npmjs.org/react/-/react-16.14.0.tgz#94d776ddd0aaa37da3eda8fc5b6b18a4c9a3114d" resolved "https://registry.npmjs.org/react/-/react-16.14.0.tgz#94d776ddd0aaa37da3eda8fc5b6b18a4c9a3114d"