Files
notifications-admin/app/assets/javascripts/enhancedTextbox.js
T

88 lines
2.0 KiB
JavaScript
Raw Normal View History

(function(Modules) {
"use strict";
if (
!('oninput' in document.createElement('input'))
) return;
2016-07-12 12:48:09 +01:00
const tagPattern = /\(\(([^\)\((\?)]+)(\?\?)?([^\)\(]*)\)\)/g;
2019-10-16 15:20:05 +01:00
Modules.EnhancedTextbox = function() {
this.start = function(textarea) {
let visibleTextbox;
this.highlightPlaceholders = (
typeof textarea.data('highlightPlaceholders') === 'undefined' ||
!!textarea.data('highlightPlaceholders')
);
this.$textbox = $(textarea)
.wrap(`
<div class='textbox-highlight-wrapper' />
`)
2016-06-02 10:40:17 +01:00
.after(this.$background = $(`
<div class="textbox-highlight-background" aria-hidden="true" />
`))
.on("input", this.update);
$(window).on("resize", this.resize);
visibleTextbox = this.$textbox.clone().appendTo("body").css({
position: 'absolute',
visibility: 'hidden',
display: 'block'
});
this.initialHeight = visibleTextbox.height();
2016-03-18 08:52:29 +00:00
2016-06-02 10:40:17 +01:00
this.$background.css({
'border-width': this.$textbox.css('border-width')
});
visibleTextbox.remove();
this.$textbox
.trigger("input");
};
2019-01-14 13:30:12 +00:00
this.resize = () => {
this.$background.width(this.$textbox.width());
2019-01-14 13:30:12 +00:00
this.$textbox.height(
Math.max(
this.initialHeight,
this.$background.outerHeight()
)
);
if ('stickAtBottomWhenScrolling' in GOVUK) {
GOVUK.stickAtBottomWhenScrolling.recalculate();
}
};
2016-03-18 08:52:29 +00:00
this.contentEscaped = () => $('<div/>').text(this.$textbox.val()).html();
this.contentReplaced = () => this.contentEscaped().replace(
tagPattern, (match, name, separator, value) => value && separator ?
`<span class='placeholder-conditional'>((${name}??</span>${value}))` :
`<span class='placeholder'>((${name}${value}))</span>`
);
2016-03-18 08:52:29 +00:00
this.update = () => {
this.$background.html(
this.highlightPlaceholders ? this.contentReplaced() : this.contentEscaped()
);
this.resize();
};
};
})(window.GOVUK.Modules);