I was fortunate to attend WordCamp Kathmandu 2019 last weekend in Nepal. As promised, here are my slides and the code for the “Nepali Date” block I created for my session “Your first Gutenberg Block”.
Here’s the code for the block javascript file:
// Nepali calendarFunctions() made available by loading the latest version of https://github.com/leapfrogtechnology/Nepali-Date-Picker | |
( function() { | |
const { __ } = wp.i18n; | |
const el = wp.element.createElement | |
const blockStyle = { | |
backgroundColor: '#DC143C', | |
color: '#fff', | |
padding: '20px', | |
}; | |
wp.blocks.registerBlockType( 'wcktm/nepali-date-block', { | |
title: __( 'Nepali Date', 'gutenberg-examples' ), | |
icon: 'calendar-alt', | |
category: 'widgets', | |
attributes: { | |
nepaliDate: { | |
type: 'string' | |
}, | |
englishDate: { | |
type: 'string' | |
} | |
}, | |
edit: function( { isSelected, attributes, setAttributes } ) { | |
const saveDate = function( englishDate ) { | |
const englishDateObject = new Date( englishDate ); | |
const nepaliDate = calendarFunctions.getBsDateByAdDate( | |
englishDateObject.getFullYear(), | |
englishDateObject.getMonth() + 1, | |
englishDateObject.getDay() | |
); | |
setAttributes( { | |
'englishDate': englishDate, | |
'nepaliDate' : calendarFunctions.bsDateFormat( | |
"%y-%m-%d", | |
nepaliDate.bsYear, | |
nepaliDate.bsMonth, | |
nepaliDate.bsDate | |
), | |
} ); | |
} | |
if ( isSelected ) { | |
return el( | |
wp.components.DatePicker, { | |
onChange: saveDate, | |
currentDate: typeof attributes.englishDate !== 'undefined' ? | |
new Date( attributes.englishDate ) : new Date() | |
}); | |
} else { | |
const text = typeof attributes.nepaliDate !== 'undefined' ? | |
attributes.nepaliDate : | |
__( 'Click to select a date' ); | |
return el( | |
'p', | |
{ style: blockStyle }, | |
text | |
); | |
} | |
}, | |
save: function( props ) { | |
if ( props.attributes.nepaliDate !== undefined ) { | |
return el( | |
'p', | |
{ style: blockStyle }, | |
props.attributes.nepaliDate | |
); | |
} | |
}, | |
} ); | |
} )(); |