DateTimeStamp

Can anyone tell me the best way to make a DateTimeStamp button for the Rich Text Editor?


11 Replies

BS Buvana Sathasivam Syncfusion Team August 16, 2024 04:19 AM UTC

Hi Grant,


Thank you for reaching out with your query regarding the DateTimeStamp button for the Rich Text Editor.


To implement this requirement, you can use the custom toolbar option in the Rich Text Editor. By configuring a custom toolbar item for the DateTimeStamp button, you can bind the click event to this button within the created event of the Rich Text Editor:


toolbarSettings:

{ items: [ 'Bold', 'Italic',

  {

 tooltipText: 'Date Time Stamp',

 template: '<button class="e-tbar-btn e-btn" tabindex="-1" id="custom_tbar" style="width:100%"><span class="e-input-group-icon e-date-icon e-icons" aria-label="select" role="button"></span></button>', },

],

}


For more details on configuring the custom toolbar item, you can refer to the custom toolbar documentation.

Once the button is clicked, you can utilize the executeCommand method of the Rich Text Editor to insert the current date and time at the desired location within the editor:


let dateTime = new Date(); rteObj.executeCommand('insertText', dateTime);


For more information, you can refer to the following resources:

Additionally, you can explore this sample to see how it can be implemented.


If you have any further questions or need additional assistance, please don't hesitate to contact us. We're here to help.


Regards,

Buvana S



GS Grant Symon August 16, 2024 12:07 PM UTC

Hi Buvana,

many thanks for the very helpful reply.

I've applied it as best I can and tried some variations to try to get it to work, but clicking the button selects/activates the button, but doesn't run the function.

I include a screen-video-grab, to show what happens and I include my very basic code below.  Any ideas?



<!DOCTYPE html> <html lang="en"> 
<head>
<script src="https://cdn.syncfusion.com/ej2/26.2.4/dist/ej2.min.js" type="text/javascript"> </script>
<link rel='nofollow' href="https://cdn.syncfusion.com/ej2/26.2.4/material3.css" rel="stylesheet">
<link rel='nofollow' href="https://maxcdn.bootstrapcdn.com/bootstrap/5.3.2/css/bootstrap.min.css" rel="stylesheet">


<style>
body { 
.e-rte-inline-popup{
min-width: 250px !important;
}
.e-rte-quick-popup{
max-width: 350px !important;


  .e-input-group-icon.e-date-icon {
        margin: 6px auto auto auto !important;
      }


}
</style> </head> <body>
<script> "Syncfusion Licence" </script>
<div class="e-rte-container" >
<div id="defaultRTE" >  "HTML" </div>
</div>


<script>
var selection = new ej.richtexteditor.NodeSelection();
let saveSelection;
var rteObj = new ej.richtexteditor.RichTextEditor({
        inlineMode: {
            enable: true,
            onSelection: true
},
toolbarSettings: {
            items: ['Formats', 'Bold', 'ClearFormat',  'Image' ,


{
        tooltipText: 'Date Time Stamp',
        template:
          '<button class="e-tbar-btn e-btn" tabindex="-1" id="custom_tbar"  style="width:100%"><span class="e-input-group-icon e-date-icon e-icons" aria-label="select" role="button"></span></button>',


      },


]},


        saveInterval: 1,
        change: change,
        autoSaveOnIdle: true
    });


    rteObj.appendTo("#defaultRTE");
    function change(args){        
const textPlain = defaultRTE.getText();
const textHTML = defaultRTE.getHtml();
const jsonARR = { textPlain, textHTML };
FileMaker.PerformScriptWithOption ( 'RTE-DATA', JSON.stringify(jsonARR) , '5' );
    }




let dateTime;
function create(args) {
  const customBtn = document.getElementById('custom_tbar');
  customBtn.onclick = (e) => {
    rteObj.contentModule.getEditPanel().focus();
    range = selection.getRange(document);
    saveSelection = selection.save(range, document);
    if (rteObj.formatter.getUndoRedoStack().length === 0) {
      rteObj.formatter.saveData();
    }
    saveSelection.restore();
    dateTime = new Date();
    rteObj.executeCommand('insertText', dateTime);
    rteObj.formatter.saveData();
    rteObj.formatter.enableUndo(rteObj);
  };
}




</script> </body> </html>





Attachment: GSymonvideograbSyncfusionDateTime_375735bf.zip


SS Selvakumar Subramani Syncfusion Team August 20, 2024 04:58 PM UTC

Hi Grant Symon

We have thoroughly reviewed the video reference you provided and noticed that you are using the inline mode in the Rich Text Editor. Since the toolbar opens and closes dynamically in inline mode, you'll need to use the quickToolbarOpen event to achieve your requirement. This event is triggered after the quick toolbar has opened, allowing you to bind the click event to the Date/Time stamp button when quickToolbarOpen is triggered.

 

 

var rteObj = new ej.richtexteditor.RichTextEditor({

  quickToolbarOpen: quickToolbarOpen,

  inlineMode: {

    enable: true,

    onSelection: true,

  },

 

function quickToolbarOpen(args) {

  document

    .getElementById('custom_tbar')

    .addEventListener('click'dateTimeStamp);

}

To assist you further, we've prepared a sample that demonstrates the correct implementation. We believe this sample will meet your requirements. Please take a look at the example provided below:

Sample: https://stackblitz.com/edit/mcayfl-qjs8tz?file=index.js,index.html



GS Grant Symon August 30, 2024 01:23 PM UTC

Thank you for the reply Selvakumar and apologies for my slow response. I can confirm that it now works for me using inline.

I wonder now if there is any way to 'personalise' the date format that will be pasted in?  Including the text formatting of it??  What I used for a long time with a different RTE (TinyMCE) was very useful, because it used <time> which enabled me to customise with css and to effect changes across my entire database with a single edit, but aside from that, I would ideally like to have it paste in... e.g.:  ✏️ (30-08-2023).  Would this be possible?

Regards,

Grant



VY Vinothkumar Yuvaraj Syncfusion Team September 4, 2024 12:54 PM UTC

Hi Grant Symon,


You can use the insertHTML command with the executeCommand method to insert an HTML string into the Rich Text Editor. We have formatted the time and inserted that element at the current cursor position. Please see the following code and sample for your reference.


function dateTimeStamp() {

………

  dateTime = new Date();

  const formattedDate = dateTime.toLocaleDateString('en-GB'); // Format date as DD-MM-YYYY

  const timeElement = `<time datetime="${dateTime.toISOString()}">(${formattedDate})</time>`;

  rteObj.executeCommand('insertHTML', timeElement);

  ………….

}


Video Gif:

 


Sample : https://stackblitz.com/edit/mcayfl-h9m8ew?file=index.js,index.html


Documentation : https://ej2.syncfusion.com/javascript/documentation/rich-text-editor/exec-command


Regards,
Vinothkumar



GS Grant Symon September 5, 2024 02:30 PM UTC

Hi Vinothkumar,

thank you!  This works well, but I've been a bit caught out, because it never occurred to me that changing the formatting a little bit would be complicated.  Can you further help me with what I'd need to change if I wanted to have the date as ✏️ (30-08-24) ?

(In TinyMCE I just applied python(?) as -   '✏️ (%d-%m-%Y)', )

________________________________________________________

A remaining issue, is a separate question that I've raised in a separate forum-question ... but it's relevant here too.  There's no way to activate the inline toolbar, without selecting some text. If 'Selection' is not set in the code, then there are some other situations where it doesn't work well either. So ...

Can I recommend instigating a keyboard shortcut for opening the RTE inline Toolbar when the cursor is active, but no text is selected?



SS Selvakumar Subramani Syncfusion Team September 10, 2024 05:16 AM UTC

Hi Grant Symon
Query
1:Can you further help me with what I'd need to change if I wanted to have the date as ✏️ (30-08-24) ? (In TinyMCE I just applied python(?) as - '✏️ (%d-%m-%Y)', )

We have reviewed your requirement and prepared a sample to include a new dropdown option in the toolbar for adding different date and time formats. Please check the sample provided below. We believe this sample meets your requirements.

In the sample, we used the executeCommand public method and saved/restored the selection range to insert the date and time at the cursor position.

You can view the sample here: Sample

Here is the code snippet for your reference:

var selection = new ej.richtexteditor.NodeSelection();

let saveSelection;

var rteObj = new ej.richtexteditor.RichTextEditor({

  quickToolbarOpen: quickToolbarOpen,

  inlineMode: {

    enable: true,

    onSelection: false,

  },

  toolbarSettings: {

    items: [

      'Bold',

      'Italic',

      {

        tooltipText: 'Date Time Stamp',

        template: `  <select id="dropdown">

        <option value='select'>Date Time</option>

        </select>`,

      },

    ],

  },

});

rteObj.appendTo('#defaultRTE');


function getDateTime() {

  const currentDate = new Date();

  const y_m_d = `${currentDate.getFullYear()}-${

    currentDate.getMonth() + 1

  }-${currentDate.getDate()}`;

  const d_m_Y = `${currentDate.getDate()}-${

    currentDate.getMonth() + 1

  }-${currentDate.getFullYear()}`;


  const h_m_s = `${currentDate.getHours()}-${currentDate.getMinutes()}-${currentDate.getSeconds()}`;

  const h_m_s_am = getCurrentDateTimeAMPM();

  const newOptions = [

    { value: 'h_m_s', text: h_m_s },

    { value: 'y_m_d', text: y_m_d },

    { value: 'd_m_Y', text: d_m_Y },

    { value: 'h_m_s_am', text: h_m_s_am },

  ];

  return newOptions;

}


function quickToolbarOpen(args) {

  const currentDateTime = getDateTime();

  const selectElement = document.getElementById('dropdown');


  if (document.querySelectorAll('#dropdown option').length == 1) {

    currentDateTime.forEach((e) => {

      const newOption = document.createElement('option');

      newOption.text = e.text;

      newOption.value = e.value;

      selectElement.appendChild(newOption);

    });

  } else {

    const options = document.querySelectorAll('#dropdown option');

    options.forEach((e) => {

      switch (e.value) {

        case h_m_s:

          e.text = currentDateTime.text;

          break;

        case y_m_d:

          e.text = currentDateTime.text;

          break;

        case d_m_Y:

          e.text = currentDateTime.text;

          break;

        case h_m_s_am:

          e.text = currentDateTime.text;

          break;

      }

    });

  }


  selectElement.addEventListener('change', function (event) {

    console.log('Selection changed:', event.target.text);

    rteObj.contentModule.getEditPanel().focus();

    range = selection.getRange(document);

    saveSelection = selection.save(range, document);

    if (rteObj.formatter.getUndoRedoStack().length === 0) {

      rteObj.formatter.saveData();

    }

    saveSelection.restore();

    const curDateTime = getDateTime();

    const dateTimeStamp = curDateTime.filter(

      (item) => item.value == event.target.value

    );

    rteObj.executeCommand('insertHTML', dateTimeStamp[0].text);

    rteObj.formatter.saveData();

    rteObj.formatter.enableUndo(rteObj);

  });

}



Query 2: To open the Rich Text Editor (RTE) inline toolbar when the cursor is active but no text is selected, please set the onSelection property to false. This setting will enable the toolbar to appear even if no text is highlighted.

rteObj.appendTo('#defaultRTE');Here is a code snippet to achieve this:

var rteObj = new ej.richtexteditor.RichTextEditor({

  quickToolbarOpen: quickToolbarOpen,

  inlineMode: {

    enable: true,

    onSelection: false,

  },

 toolbarSettings: {

    items: [

      'Bold',

      'Italic',

      {

        tooltipText: 'Date Time Stamp',

        template: `<select id="dropdown">

                     <option value='select'>Date Time</option>

                   </select>`,

      },

    ],

  },

});

rteObj.appendTo('#defaultRTE');


If you
have any further questions or need additional assistance, please let us know.



GS Grant Symon September 19, 2024 09:27 AM UTC

Thank you Selvakumar.  That gives me all the possibilities I could want!!  Excellent. 🙂

(I'd add my vote to this being a standard button on the Toolbar (with icon-drop-down instead of text))

_________________________

Regarding Query2 (above).  Please see my last reply to this other thread:

Regards,

Grant



YV Yaswin Vikhaash Rajaretenam Syncfusion Team September 20, 2024 02:39 PM UTC

Hi Grant Symon,


For Query 1, "Style and tag Retains when enter is pressed after time is inserted"

due to the default browser behavior, which retains the style and tag for date and time elements.

We have resolved this by removing the date and time tags when the "Enter" key is pressed, utilizing the actionComplete  event to handle the process.

We have attached a sample code and provided a link where you can run and test the solution. Please review it to ensure it resolves your issue.





here is code for your refrence

  actionComplete: function (args) {

    var range = document.getSelection().getRangeAt(0);

    var startContainer = range.startContainer;

    if (

      args.requestType === 'EnterAction' &&

      startContainer.tagName === 'TIME'

    ) {

      startContainer.remove();

    }

  }

Sample Link - https://stackblitz.com/edit/mcayfl-sqxpcd?file=index.js,index.html


For Query 2:  "the placement of the inline toolbar at the top", we are currently working on providing a suitable solution. Our team is in the process of validating the requirements, and we will reach out to you with the results once the validation is complete.

Thank you for your patience and understanding.


Regards,

Yaswin Vikhaash



GS Grant Symon September 20, 2024 06:01 PM UTC

Hi Yaswin,

thank you so much for this fix.  It does the job perfectly. 😊👍

Query 2:

I'm looking forward to a solution for this.  Many thanks for working on it.

Regards,

Grant



YV Yaswin Vikhaash Rajaretenam Syncfusion Team September 23, 2024 02:37 PM UTC

Hi Grant Symon,


Could you please refer to the forum link provided below for Query 2?

Remove the grey border from the RichTextEditor | JavaScript - EJ 2 Forums | Syncfusion


Regards,

Yaswin Vikhaash


Loader.
Up arrow icon