Getting started in EJ2 TypeScript Smart Paste button control

7 Oct 202424 minutes to read

The Smart Paste Button is a user interface control designed to simplify and improve the experience of pasting text into form fields. It comes with smart features such as automatic text formatting, validation, and integration with various form controls. It is especially useful in applications where users frequently paste text from other sources and where data consistency is important.

This section explains how to create a simple Smart Paste button, and configure its available functionalities in TypeScript, using Essential JS 2 quickstart seed repository.

This application is integrated with the webpack.config.js configuration and uses the latest version of the webpack-cli. It requires node v14.15.0 or higher. For more information about webpack and its features, refer to the webpack documentation.

Prerequisites

To get started, ensure the following software to be installed in the machine.

Check out the download and installation section of Essential Studio JavaScript. If you are using Syncfusion CDN resources to build your web application, you can skip the Essential Studio JavaScript prerequisite.

Dependencies

The list of dependencies required to use the Smart Paste Button control in your application is given as follows:

|-- @syncfusion/ej2-buttons
    |-- @syncfusion/ej2-base

Set up development environment

Open the command prompt from the required directory, and run the following command to clone the Syncfusion JavaScript (Essential JS 2) quickstart project from GitHub.

git clone https://github.com/SyncfusionExamples/ej2-quickstart-webpack- ej2-quickstart

After cloning the application in the ej2-quickstart folder, run the following command line to navigate to the ej2-quickstart folder.

cd ej2-quickstart

Add Syncfusion JavaScript packages

Syncfusion JavaScript (Essential JS 2) packages are available on the npmjs.com public registry. You can install all Syncfusion JavaScript (Essential JS 2) controls in a single @syncfusion/ej2 package or individual packages for each control.

The quickstart application is preconfigured with the dependent @syncfusion/ej2 package in the ~/package.json file. Use the following command to install the dependent npm packages from the command prompt.

npm install

Import the Syncfusion CSS styles

To render Smart Paste Button control, need to import Button and its dependent components styles as given below in the ~/src/styles/index.css file, as shown below:

@import "../../node_modules/@syncfusion/ej2-base/styles/material.css";
@import "../../node_modules/@syncfusion/ej2-buttons/styles/material.css";

Adding Smart Paste Button to the Application

Add the HTML Button tag with ID attribute as the smart-paste-button to your index.html file.

[src/index.html]

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Essential JS 2</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
    <meta name="description" content="Essential JS 2" />
    <meta name="author" content="Syncfusion" />
    <link rel="shortcut icon" href="resources/favicon.ico" />
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
</head>

<body>
    <div>
        <!--Element to render the Smart Paste Button control-->
        <button id="smart-paste-button"></button>
    </div>

</body>

</html>

Then, import the Smart Paste Button control in your app.ts file, and initialize it with the #smart-paste-button.

The control utilizes the aiAssistHandler property, a callback function that sends a request to the AI model and updates the form with the generated content based on the AI’s response.

[src/app/app.ts]

import { SmartPasteButton } from '@syncfusion/ej2-buttons';

const serverAIRequest = async (options: ChatOptions) => {
  let output: string | null = '';
  try {
    // console.log("input:", options);
    output = await (window as any).AzureAIRequest(options) as string;
    output = output.replace('END_RESPONSE', '')
    // console.log("Success:", output);
  } catch (error) {
    console.error("Error:", error);
  }
  return output;
};

// Initialize Smart Paste Button control.
let button: SmartPasteButton = new SmartPasteButton({
  content: 'Smart Paste',
  iconCss: "e-icons e-paste",
  aiAssistHandler: serverAIRequest
});
// Render initialized Smart Paste Button.
button.appendTo('#smart-paste');

Run the application

Run the application in the browser using the following command:

npm start

The following example shows a basic Smart Paste Button control.

In our demonstration, Azure AI is used, but you can integrate any text-generative AI of your choice.

import { SmartPasteButton, ChatOptions } from "@syncfusion/ej2-buttons";
import { TextArea, TextBox } from "@syncfusion/ej2-inputs";
import { Button, ChipList, ClickEventArgs, RadioButton } from "@syncfusion/ej2-buttons";
import { ComboBox } from "@syncfusion/ej2/dropdowns";

let inputobj1: TextBox = new TextBox({
  placeholder: "What's the bug ?",
  floatLabelType: "Never",
});
inputobj1.appendTo("#bug-name");

let inputobj2: TextBox = new TextBox({
  placeholder: "Who is the reporter ?",
  floatLabelType: "Never",
});
inputobj2.appendTo("#reporter-name");

let inputobj3: TextBox = new TextBox({
  placeholder: "When it is reported ?",
  floatLabelType: "Never",
});
inputobj3.appendTo("#submitted-date");

let textArea1: TextArea = new TextArea({
  placeholder: "Describe a little about the bug.",
  rows: 2,
  floatLabelType: "Never",
});
textArea1.appendTo("#bug-description");

let textArea2: TextArea = new TextArea({
  placeholder: "Enter the repro steps here..",
  cols: 30,
  rows: 4,
  floatLabelType: "Never",
});
textArea2.appendTo("#reproduce-steps");

let radioButton: RadioButton = new RadioButton({
  label: "Low",
  name: "bug-priority",
  value: "low"
});
radioButton.appendTo("#radio1");

radioButton = new RadioButton({
  label: "Medium",
  name: "bug-priority",
  value: "medium",
  checked: true
});
radioButton.appendTo("#radio2");

radioButton = new RadioButton({
  label: "High",
  name: "bug-priority",
  value: "high",
});
radioButton.appendTo("#radio3");

const browserData: string[] = [
  'Chrome', 'Firefox', 'Safari'
];
let comboBoxObj: ComboBox = new ComboBox({
  popupHeight: '230px',
  dataSource: browserData,
  placeholder: 'Choose the browser',
});
comboBoxObj.appendTo('#browser');

// Initialize Button control.
let resetButton: Button = new Button({
  content: 'Reset',
  iconCss: "e-icons e-reset",
});
// Render initialized Button.
resetButton.appendTo('#reset');


const serverAIRequest = async (options: ChatOptions) => {
  let output: string | null = '';
  try {
    // console.log("input:", options);
    output = await (window as any).AzureAIRequest(options) as string;
    output = output.replace('END_RESPONSE', '')
    // console.log("Success:", output);
  } catch (error) {
    console.error("Error:", error);
  }
  return output;
};

// Initialize Smart Paste Button control.
let button: SmartPasteButton = new SmartPasteButton({
  content: 'Smart Paste',
  iconCss: "e-icons e-paste",
  aiAssistHandler: serverAIRequest
});
// Render initialized Smart Paste Button.
button.appendTo('#smart-paste');


// Property Pane Code

let bugPresets: string[] = [
  "Issue with the dropdown menu",
  "Trouble logging into the website",
  "Search functionality not working",
  "Images missing on the product page"
];

let bugReports: string[] = [
  `Hi, this is Alice. On July 3rd, I've come across a bug where the dropdown menu in the navigation bar doesn't close after selecting an item. I just navigated to the homepage, opened the dropdown menu in the navigation bar, clicked an item in the dropdown and then the issue occurred which happens only on Chrome. Though this doesn't seem like a serious/important bug, kindly look into it and resolve it. Regards, J Alice Abraham`,
  `Hey team, On May 2nd, K John Doe reported an issue where the login page refreshes instead of logging in when the user clicks the login button. This problem prevents users from accessing their accounts, making it a critical issue that needs immediate attention. The issue has been observed across all major browsers. To reproduce the issue, open any browser and navigate to the website's login page. Enter a valid username and password, then click the Login button.`,
  `Hi, Whenever I type something in the search bar and hit search, it doesn't return any results, even for items I know exist. This problem was noticed by Jane Smith on July 5th in FireFox browser. You can repro the issue by opening the site in the Firefox browser and navigate to the search bar. Type in any search term, including items that are known to exist, and click the search button. The search functionality fails to return any results, displaying an empty result set even for valid queries. This is quite important, but not urgent. Please look into it. Regards, M William Marker`,
  `Hello, When I selected the category option on the landing page and chose the electronics category, the images were missing on the product page. The placeholders are there, but no actual images are loading. This happens on all browsers. I reported this on July 3rd. It's not urgent, but it does affect the user experience. Regards, L Mike Johnson`
];

let copyContent: HTMLElement = document.getElementById('bug-report-text') as HTMLElement;
copyContent.innerHTML = bugReports[0];

let copyButton: Button = new Button({
  content: 'Copy',
  iconCss: "e-icons e-copy"
});
copyButton.appendTo('#copy-btn');

copyButton.element.onclick = async () => {

  await navigator.clipboard.writeText(copyContent.innerHTML);
  copyButton.content = "Copied";
  copyButton.iconCss = "e-icons e-check";
}

let chipList = new ChipList(
  {
    chips: bugPresets, selection: 'Single',
    selectedChips: [0],
    click: (e: ClickEventArgs) => {
      copyContent.innerHTML = bugReports[e.index as number] as string;
      chipList.selectedChips = e.index as number;
      copyButton.content = "Copy";
      copyButton.iconCss = "e-icons e-copy";
    }
  },
  '#chip-choice');
import { AzureOpenAI } from "https://cdn.jsdelivr.net/npm/[email protected]/+esm";
 
//Warning: Do not expose your API key in the client-side code. This is only for demonstration purposes.

// Replace your Azure OpenAI endpoint, apiVersion, deployment and API key here
const endpoint = "AZURE_OPENAI_ENDPOINT";
const apiKey = "AZURE_OPENAI_API_KEY";
const deployment = "DEPLOYMENT_NAME";
const apiVersion = "API_VERSION";
 
const client = new AzureOpenAI({
    endpoint,
    apiKey,
    apiVersion,
    deployment,
    dangerouslyAllowBrowser: true
});
 
window.AzureAIRequest = async function (options) {
    try {
        const result = await client.chat.completions.create({
            messages: options.messages,
            model: "",
            top_p: options.topP,
            temperature: options.temperature,
            max_tokens: options.maxTokens,
            frequency_penalty: options.frequencyPenalty,
            presence_penalty: options.presencePenalty,
            stop: options.stopSequences
        });
        return result.choices[0].message.content;
    } catch (err) {
        console.error("Error occurred:", err);
    }
}
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 Floating Action Button</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript UI Controls" />
    <meta name="author" content="Syncfusion" />
    <link href="https://cdn.syncfusion.com/ej2/28.1.33/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/28.1.33/ej2-buttons/styles/material.css" rel="stylesheet" />
    <link href="styles.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
    <script src="../azure_openai.js" type="module"></script>
    <style>
        .form-container {
            display: flex;
            flex-direction: column;
            gap: 15px;
            border: 1px solid #ddd;
            padding: 20px;
            border-radius: 5px;
            width: 49%;
            margin: 0 auto;
        }

        .form-label {
            margin-bottom: 5px;
        }

        .form-input,
        .form-textarea,
        .form-select {
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 3px;
            width: 100%;
        }

        .form-textarea {
            height: 80px;
        }


        .row-group {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
        }

        .form-footer {
            display: flex;
            margin-top: 20px;
            justify-content: right;
            gap: 15px;
        }

        .form-group {
            display: grid;
            gap: 8px;
        }

        .single-row-group {
            display: grid;
            gap: 8px;
        }

        #bug-report-text {
            padding: 10px;
            margin: 15px 0px;
            background-color: #f3f3f3;
            border: 1px solid #ddd;
            border-radius: 5px;
            line-height: 1.5;
        }

        #reset,
        #smart-paste {
            border-radius: 20px;
        }
    </style>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>

<body>
    <div id='loader'>LOADING....</div>
    <div id='container'>
        <h2>Data Form with Syncfusion Smart Paste Button</h2>
        <form class="form-container">
            <div class="single-row-group">
                <label for="bug-name" class="e-form-label">Bug Name</label>
                <input type="text" id="bug-name" name="bug-name" class="form-input" />
            </div>
    
            <div class="row-group">
                <div>
                    <label for="reporter-name" class="e-form-label">Reporter</label>
                    <input type="text" id="reporter-name" name="reporter-name" class="form-input" />
                </div>
                <div>
                    <label for="submitted-date" class="e-form-label">Submitted Date</label>
                    <input type="text" id="submitted-date" name="submit-date" class="form-input" />
                </div>
            </div>
    
            <div class="form-group">
                <label for="bug-description" class="e-form-label">Bug Description</label>
                <textarea id="bug-description" class="form-textarea"></textarea>
            </div>
    
            <div class="row-group">
                <div style="display: flex;flex-direction: column;">
                    <label for="reproduce-steps" class="e-form-label">Reproduce Steps</label>
                    <textarea id="reproduce-steps" name="reproduce-steps" class="form-textarea"></textarea>
                </div>
                <div>
                    <label class="form-label">Bug Priority</label>
                    <div class="row">
                        <input id="radio1" type="radio">
                    </div>
                    <div class="row">
                        <input id="radio2" type="radio">
                    </div>
                    <div class="row">
                        <input id="radio3" type="radio">
                    </div>
                </div>
    
            </div>
    
            <div>
                <label for="browser" class="form-label">Select the browser</label>
                <input type="text" id="browser" name="browser" />
            </div>
    
            <div class="form-footer">
                <button type="reset" id="reset" class="form-button"></button>
                <button type="button" id="smart-paste" class="form-button"></button>
            </div>
        </form>
    
        <div class="col-lg-4 property-section">
            <div class="property-panel-section">
                <div class="property-panel-content">
                    <h4> Choose a preset below </h4>
                    <div class="chip-container">
                        <div id="chip-choice" aria-label="choiceChips"></div>
                    </div>
                    <div id="bug-report-text"></div>
                    <button id="copy-btn"></button>
                </div>
            </div>
        </div>    
    </div>
</body>

</html>

smart-paste-button

Javascript Smart Paste Button Sample in github