Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: Universal settings in any plugin #500

Open
ReinRaus opened this issue May 10, 2021 · 8 comments
Open

Feature request: Universal settings in any plugin #500

ReinRaus opened this issue May 10, 2021 · 8 comments

Comments

@ReinRaus
Copy link

Language: russian

Здравствуйте.
Напишу много текста, поэтому буду использовать русский язык.

Я сделал плагин Custom Settings Plugin

Он полностью работоспособен и позволяет простым способом определить значения, которые будут храниться в localStorage и могут быть легко изменены пользователем.

Для начала скриншоты.

  1. Кнопка вызова настроек.
    image

  2. Окно настроек
    image

  3. Открыли настройки одного из плагинов. На данном скриншоте настройки самого плагина CustomSettings
    image

  4. Поменяли язык интерфейса
    image

Использование данного плагина можно также посмотреть в другом моем плагине BetterClick
Это позволило сократить объём кода на 60 строк. Код теперь не реализует работу с настройками, а просто их использует.

Создать настройку в своём плагине очень легко, нужно сделать её описание:

let settings_info = {
    radius: {
        type: "string",
        default: "8",
        format: "integer(1,100)",
        title: {
            en: "Miss radius",
            ru: "Радиус промаха"
        },
        description: {
            en: "Miss radius in percents of screen size.",
            ru: "Радиус в котором будет сформирован список порталов в процентах от размера экрана."
        },
    }
}; 

Описание в большой своей части состоит из простых параметров и текста на нескольких языках.
Это простой пример, где настройка- просто строка. Более сложные примеры можно найти по поиску selfSettings в плагине.

Использование настроек:

let settingsObject = new window.USettings( pluginInfo, settingsInfo );
let settings = settingsObject.settings;
alert( settings.customValue );
let settings = ( new window.USettings( pluginInfo, settingsInfo ) ).settings; // так лучше всего

Больше описания в комментарии в плагине.

Для чего создан этот Issue

Данный плагин - это демонстрация.
Я изначально его писал с расчётом, что он станет частью IITC-CE, например так:
image
Вместо кружочка будет кнопка с показом настроек плагина, если плагин использует настройки.

Смысл в том, чтобы дать авторам плагинов универсальный инструмент, а будут они его использовать или нет - их дело.

Мне нужна помощь человека, который хорошо знает устройство IITC button, IITC-CE mobile, для того, чтобы внедрить этот плагин как часть проекта.
Кроме того, я не хочу делать внедрение в проект, если оно потом будет отклонено мейнтейнером.

P.S. На скриншоте под выбором языка написано RELOAD page to apply changes. Это устаревшая надпись. Все настройки применяются интерактивно. И язык интерфейса будет изменен сразу после выбора нового языка. Лень переделывать скриншоты.

@johnd0e
Copy link
Contributor

johnd0e commented May 10, 2021

@ReinRaus Cool, but please google-translate it to let others to participate in the discussion too

@johnd0e
Copy link
Contributor

johnd0e commented May 10, 2021

In general.

  • Certainly you can ask of assistance in iitc-button integration, but we have separate repo for it.
  • In either case, it's good idea to put more order in settings storing and handling.

But before we adopt proposed scheme for standard plugins - we should agree on data structure.
I see your sample format description is comprehensive, but may be you should allow more 'relaxed' usage too.
E.g. it could be possible to edit arbitrary localStorage key.

Also, iitc itself has some config params, currently barely reachable for general user. So this sort of plugin is really required to help with settings.

@modos189
Copy link
Contributor

It's a good idea, but it's important to provide the same customization options that exist now. For example, to be able to transfer the settings of Bookmarks plugin to settings of this plugin

@johnd0e
Copy link
Contributor

johnd0e commented May 11, 2021

I haven't seen proposed implementation, but as idea: scheme that describes the data could be separate.
So all the plugins could proceed without any changes in previous data structure.

@ReinRaus
Copy link
Author

@johnd0e
What is the existing data structure? I am aware that nowadays everyone keeps their plugin settings as best they can.

@johnd0e @modos189
I suggest the following:

  1. Develop a data schema together
  2. Implement support in IITC
  3. Old plugins will continue to work
  4. New and existing plugins use this feature
  5. For the functionality of new plugins in old versions of IITC, embed the code on the page that implements the work with the settings
    Something like:
plugin.start = function() {
     if ( window.USettings ) {
         let settings = ( new window.USettings( plugin_info, settings_info ) ).settings;
         plugin.realStart();
     } else {
         let scr = document.createElement( 'script' );
         scr.src = "https://path_to_usettings_as_plugin"; 
         scr.onload = plugin.start;
         document.head[0].appendChild( scr );
     };
};
@modos189 тоже самое без google translate

Я предлагаю следующее:

  1. Совместно разработать схему данных
  2. Реализовать поддержку в IITC
  3. Старые плагины будут продолжать работать
  4. Новые и существующие плагины используют данную возможность
  5. Для работоспособности новых плагинов в старых версиях IITC писать обертку с подгрузкой кода

@johnd0e
Copy link
Contributor

johnd0e commented May 11, 2021

I am aware that nowadays everyone keeps their plugin settings as best they can.

Exactly. And everyone can continue to use own way, but (optionally) benefit from common 'Settings control' just providing some additional metadata, describing their settings structure.

E.g. plugin use myplugin key in localStorage, storing object with keys 'lang' (string) and 'size' (number).
In order to benefit from (hypothetical) new 'Settings control' the plugin should add there some metadata (e.g. key 'settingsControl') with a scheme describing the settings.

For example it could be such (optional!) structure:

{
  'pluginName': 'myplugin',
  'pluginName:ru': 'мойплагин',
  'description': '<the purpose of the plugin>',
  // ...
  'settings': [
    {'name': 'lang', 'type': 'string'},
    {'name': 'size', 'type': 'number'},
  ]
}

You can add localized names and descriptions to every element of settings as well.

@ReinRaus
Copy link
Author

I suggest joining the data schema document.
I will continue later.
https://docs.google.com/spreadsheets/d/19JUPsVgekxOp1_hdRZnNI94XMb-Q2AKriEg8O6DRQLg/edit?usp=sharing

@ReinRaus
Copy link
Author

Finished describing the data schema as I see it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants