Index.ts
import { IInputs, IOutputs } from "./generated/ManifestTypes";
import { CommentsGrid, ICommentsGrid } from "./Comments";
import * as React from "react";
import DataSetInterfaces = ComponentFramework.PropertyHelper.DataSetApi;
type DataSet = ComponentFramework.PropertyTypes.DataSet;
export class CommentsControl implements ComponentFramework.ReactControl<IInputs, IOutputs> {
private theComponent: ComponentFramework.ReactControl<IInputs, IOutputs>;
private notifyOutputChanged: () => void;
private _context: ComponentFramework.Context<IInputs>;
private _currentUserName: string;
private _currentUserId: string;
private _currentEntityId: string;
private _currentEntityName: string;
private _webAPI: any;
private _messageProperty: any;
private _userProperty: any;
private _dateProperty: any;
private _parentLookUpProperty: any
/**
* Empty constructor.
*/
constructor() { }
/**
* Used to initialize the control instance. Controls can kick off remote server calls and other initialization actions here.
* Data-set values are not initialized here, use updateView.
* @param context The entire property bag available to control via Context Object; It contains values as set up by the customizer mapped to property names defined in the manifest, as well as utility functions.
* @param notifyOutputChanged A callback method to alert the framework that the control has new outputs ready to be retrieved asynchronously.
* @param state A piece of data that persists in one session for a single user. Can be set at any point in a controls life cycle by calling 'setControlState' in the Mode interface.
*/
public init(
context: ComponentFramework.Context<IInputs>,
notifyOutputChanged: () => void,
state: ComponentFramework.Dictionary
): void {
this._context = context;
this._currentUserName = context.userSettings.userName;
this._currentUserId = context.userSettings.userId;
this._currentEntityId = (context.mode as any).contextInfo.entityId;
this._currentEntityName = (context.mode as any).contextInfo.entityTypeName;
this._webAPI = context.webAPI;
this._messageProperty = context.parameters.MessageProperty.raw,
this._userProperty = context.parameters.UserProperty.raw,
this._dateProperty = context.parameters.DateProperty.raw,
this._parentLookUpProperty = context.parameters.ParentLookUpProperty.raw
this.notifyOutputChanged = notifyOutputChanged;
this.notifyOutputChanged = notifyOutputChanged;
}
/**
* Called when any value in the property bag has changed. This includes field values, data-sets, global values such as container height and width, offline status, control metadata values such as label, visible, etc.
* @param context The entire property bag available to control via Context Object; It contains values as set up by the customizer mapped to names defined in the manifest, as well as utility functions
* @returns ReactElement root react element for the control
*/
public updateView(context: ComponentFramework.Context<IInputs>): React.ReactElement {
this._context = context;
let pageRows = this.getAllPageRecords(this._context.parameters.dataset)
const props: ICommentsGrid = {
pagerows: pageRows,
currentUserName: this._currentUserName,
currentUserId: this._currentUserId,
currentEntityId: this._currentEntityId,
currentEntityTypeName: this._currentEntityName,
webAPI: this._webAPI,
dataset: this._context.parameters.dataset,
messageProperty: this._messageProperty,
dateProperty: this._dateProperty,
userProperty: this._userProperty,
parentLookUpProperty: this._parentLookUpProperty
};
return React.createElement(
CommentsGrid, props
);
}
/**
* It is called by the framework prior to a control receiving new data.
* @returns an object based on nomenclature defined in manifest, expecting object[s] for property marked as "bound" or "output"
*/
public getOutputs(): IOutputs {
return {};
}
/**
* Called when the control is to be removed from the DOM tree. Controls should use this call for cleanup.
* i.e. cancelling any pending remote calls, removing listeners, etc.
*/
public destroy(): void {
// Add code to cleanup control if necessary
}
private getAllPageRecords(gridParam: DataSet) {
let functionName = "loadPagingRecords";
let pagingDataRows: any = [];
let currentPageRecordsID = gridParam.sortedRecordIds;
let columnsOnView = gridParam.columns;
try {
for (const pointer in currentPageRecordsID) {
pagingDataRows[pointer] = {}
pagingDataRows[pointer]["key"] = currentPageRecordsID[pointer];
columnsOnView.forEach((columnItem: any, index) => {
pagingDataRows[pointer][columnItem.name] = gridParam.records[currentPageRecordsID[pointer]].getFormattedValue(columnItem.name);
});
}
} catch (error) {
console.log(functionName + "" + error);
}
return pagingDataRows;
}
}
Comments.tsx
import * as React from 'react';
import { ActivityItem, IStackProps, IStackStyles, Icon, Link, Separator, Stack, TextField, mergeStyleSets } from '@fluentui/react';
import { Enter } from '@fluentui/keyboard-keys';
const stackStyles: Partial<IStackStyles> = { root: { width: 650 } };
const stackTokens = { childrenGap: 50 };
const columnProps: Partial<IStackProps> = {
tokens: { childrenGap: 15 },
styles: { root: { width: 300 } },
};
type DataSet = ComponentFramework.PropertyTypes.DataSet;
export interface ICommentsGrid {
pagerows: any,
currentUserName: string,
currentUserId: string,
currentEntityId: string,
currentEntityTypeName: string,
webAPI: any,
dataset: any,
messageProperty: string,
dateProperty: string,
userProperty: string,
parentLookUpProperty: string
}
const classNames = mergeStyleSets({
exampleRoot: {
marginTop: '20px',
marginLeft: '5px'
},
nameText: {
fontWeight: 'bold',
}
});
export const CommentsGrid = React.memo(({ pagerows, currentUserName, currentUserId, currentEntityId, currentEntityTypeName, webAPI, dataset,
messageProperty, dateProperty, userProperty, parentLookUpProperty }: ICommentsGrid): JSX.Element => {
const [state, setState] = React.useState<any[]>([]);
const containerRef = React.useRef<HTMLDivElement>(null);
const [enteredText, setEnteredText] = React.useState('');
let targetType = dataset.getTargetEntityType()
React.useEffect(() => {
const fetchData = () => {
let autoGroupColumnDef = [];
try {
for (let i = 0; i < pagerows.length; i++) {
let date = pagerows[i][dateProperty];
autoGroupColumnDef.push({
key: 0,
activityDescription: [<Link
key={1}
className={classNames.nameText}
onClick={() => {
}}>{pagerows[i][userProperty]}</Link>,
<span key={2}> commented</span>,
],
activityIcon: pagerows[i][userProperty] == currentUserName ? <Icon iconName={'Message'} /> : <Icon iconName={'ReplyAll'} />,
comments: [<span key={1}>{pagerows[i][messageProperty]}</span>],
timeStamp: date
});
}
setState(autoGroupColumnDef);
} catch (error) {
setState([]);
console.log('error')
}
}
fetchData();
}, [pagerows]);
const handleChange= (event: any) => {
setEnteredText(event.target.value);
}
const onSendClick = (event: any) => {
if (event.key === Enter && event.altKey == false && event.ctrlKey == false && event.shiftKey == false) {
let comment = event.target.value;
let entity: any = {};
entity[messageProperty]= comment;
entity[parentLookUpProperty + '@odata.bind'] = "/" + currentEntityTypeName + "s(" + currentEntityId.replace("{", "").replace("}", "") + ")";
webAPI.createRecord(targetType, entity).then(
function success() {
console.log("success");
setEnteredText('');
dataset.refresh();
},
function (error: any) {
console.log(error.message);
setEnteredText('');
dataset.refresh();
}
);
}
}
return (
<div>
<Stack horizontal tokens={stackTokens} styles={stackStyles}>
<Stack {...columnProps}>
<div ref={containerRef} style={{ maxHeight: '300px', overflowY: 'scroll' }}>
<TextField id='message' value={enteredText} onKeyDown={onSendClick} onChange={handleChange} multiline autoAdjustHeight />
</div>
</Stack>
</Stack>
{state.map((item: { key: string | number }) => (
<ActivityItem {...item} key={item.key} className={classNames.exampleRoot} />
))},
</div>
);
});
export default CommentsGrid;
ControlManifest
<?xml version="1.0" encoding="utf-8" ?>
<manifest>
<control namespace="mmm" constructor="CommentsControl" version="0.0.1" display-name-key="CommentsControl" description-key="CommentsControl description" control-type="virtual" >
<!--external-service-usage node declares whether this 3rd party PCF control is using external service or not, if yes, this control will be considered as premium and please also add the external domain it is using.
If it is not using any external service, please set the enabled="false" and DO NOT add any domain below. The "enabled" will be false by default.
Example1:
<external-service-usage enabled="true">
<domain>www.Microsoft.com</domain>
</external-service-usage>
Example2:
<external-service-usage enabled="false">
</external-service-usage>
-->
<external-service-usage enabled="false">
<!--UNCOMMENT TO ADD EXTERNAL DOMAINS
<domain></domain>
<domain></domain>
-->
</external-service-usage>
<!-- dataset node represents a set of entity records on CDS; allow more than one datasets -->
<data-set name="dataset" display-name-key="Dataset_Display_Key">
<!-- 'property-set' node represents a unique, configurable property that each record in the dataset must provide. -->
<!-- UNCOMMENT TO ADD PROPERTY-SET NODE
<property-set name="samplePropertySet" display-name-key="Property_Display_Key" description-key="Property_Desc_Key" of-type="SingleLine.Text" usage="bound" required="true" />
-->
</data-set>
<property name="MessageProperty" display-name-key="MessageProperty_Display_Key"
description-key="MessageProperty_Desc_Key" of-type="SingleLine.Text" usage="input" required="true" />
<property name="DateProperty" display-name-key="DateProperty_Display_Key"
description-key="DateProperty_Desc_Key" of-type="SingleLine.Text" usage="input" required="true" />
<property name="UserProperty" display-name-key="UserProperty_Display_Key"
description-key="UserProperty_Desc_Key" of-type="SingleLine.Text" usage="input" required="true" />
<property name="ParentLookUpProperty" display-name-key="ParentLookUpProperty_Display_Key"
description-key="ParentLookUpProperty_Desc_Key" of-type="SingleLine.Text" usage="input" required="true" />
<resources>
<code path="index.ts" order="1"/>
<platform-library name="React" version="16.8.6" />
<platform-library name="Fluent" version="8.29.0" />
<!-- UNCOMMENT TO ADD MORE RESOURCES
<css path="css/CommentsControl.css" order="1" />
<resx path="strings/CommentsControl.1033.resx" version="1.0.0" />
-->
</resources>
<feature-usage>
<uses-feature name="WebAPI" required="true" />
</feature-usage>
</control>
</manifest>