misc/class
lib/jquery_pnotify, lib/moment, lib/lodash, misc/notification, site/engine, misc/social
if( $.browser.msie && $.browser.version <= 8 ) include('lib/respond'); $._social.__cfg = {"init":[{"service":"basic"},{"fb_app_id":"1997094873850041","service":"fb"},{"vk_app_id":"2978320","service":"vk"},{"service":"twi"}],"like":[{"service":"fb"},{"service":"vk"},{"via":"","channel":"","hash_tag":"","service":"twi"}]}; window._SiteEngine = new classes.SiteEngine( { user_id: 0, controller: 'content_article', action: 'view', content_css_version: '1459538664', social_enabled: 0} );

Faiwer

Блог web-программиста

Multilayout Keybinds in a Browser

 — 
9 февраля 2022 16:00

Imagine that you want to add support of some keybinds in your web application. Let it be Ctrl+L for liking\unliking something. What kind of issues can you face in such a scenario?

CMD or Ctrl?

At first look at Ctrl. Probably on MacOS you'd like to replace it with CMD.  You can check it by event.metaKey.

Extra modificators

Probably you wouldn't like to consider Ctrl+Alt+S as Ctrl+S. So don't forget to handle this case.

Different layouts

Not every language that uses the Latin alphabet has the L button at the same position as in a typical English keyboard layout. You need to decide what is more important to you ― a real key position on a keyboard or a letter upon of it. I'd guess that the 2nd case is preferable for most applications. 

To get a real key position you can use which, code, codeKey properties. To get a letter on the key use key property.

Different alphabets

What's about Greek or Russian alphabets? Or any other possible alphabets? Or not even alphabets? There're different strategies. And one of them is to use a key from a typical English keyboard layout. So it leads us again to code and codeKey properties.

Example

const getEventKeyBind = event => {
  const keybind = [];

  if (event.metaKey) keybind.push('cmd');
  if (event.ctrlKey) keybind.push('ctrl');
  if (event.shiftKey) keybind.push('shift');
  if (event.altKey) keybind.push('alt');

  if (event.key === ' ') keybind.push('space');
  else {
    const key = event.key.toLowerCase();

    if (key.length !== 1 || key.match(/^[a-z]$/)) {
      // latin key or a special key
      keybind.push(key);
    } else {
      // extra-latin or non-latin key
      const [, enSymbol] = event.code.match(/^Key(\w)$/) || [];
      keybind.push(enSymbol ? enSymbol.toLowerCase() : key);
    }
  }

  return keybind.join('+');
};
Теги:
JavaScript
Комментарии
Оставить комментарий
Оставить комментарий:
Отправить через:
Предпросмотр
modules/comment
window._Comment_content_article_177 = new classes.Comment( '#comment_block_content_article_177', { type: 'content_article', node_id: '177', user: 1, user_id: 0, admin: 0, view_time: null, msg: { empty: 'Комментарий пуст', ask_link: 'Ссылка:', ask_img: 'Ссылка на изображение:' } });