Skip to content

Instantly share code, notes, and snippets.

@mindplay-dk
Last active March 21, 2016 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mindplay-dk/f6d76ae9b7ff45983539 to your computer and use it in GitHub Desktop.
Save mindplay-dk/f6d76ae9b7ff45983539 to your computer and use it in GitHub Desktop.
Shared toolbars plugin for Guardian's Scribe editor
define(function () {
"use strict";
var active_scribe = null;
function create_handler_for(button) {
return function (event) {
if (!active_scribe) {
return;
}
var command_name = button.dataset["commandName"];
var command_value = button.dataset["commandValue"];
var command = active_scribe.getCommand(command_name);
event.preventDefault();
active_scribe.el.focus();
command.execute(command_value);
}
}
function update_state_of(button) {
var command_name = button.dataset["commandName"];
var command_value = button.dataset["commandValue"];
var is_active = false;
var is_enabled = false;
if (active_scribe) {
var command = active_scribe.getCommand(command_name);
var selection = new active_scribe.api.Selection();
is_active = selection.range && command.queryState(command_value);
is_enabled = selection.range && command.queryEnabled();
}
if (is_active) {
button.classList.add('is-active');
} else {
button.classList.remove('is-active');
}
if (is_enabled) {
button.removeAttribute('disabled');
} else {
button.setAttribute('disabled', 'disabled');
}
}
return function (toolbarNode) {
var buttons = toolbarNode.querySelectorAll('[data-command-name]');
for (var i=0; i<buttons.length; i++) {
buttons[i].addEventListener('mousedown', create_handler_for(buttons[i]));
}
function update_buttons() {
for (var i=0; i<buttons.length; i++) {
update_state_of(buttons[i]);
}
}
return function (scribe) {
// track the active Scribe instance:
scribe.el.addEventListener('focus', function () {
active_scribe = scribe;
update_buttons();
});
scribe.el.addEventListener('blur', function () {
active_scribe = null;
update_buttons();
});
scribe.el.addEventListener('keyup', update_buttons);
scribe.el.addEventListener('mouseup', update_buttons);
scribe.on('content-changed', update_buttons);
};
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment