Тип объектов для настройки темы

Мы представляем новый тип type: objects для поддерживаемых типов настроек темы, который можно использовать для замены существующего типа json_schema, который мы планируем вскоре устареть.

Определение настройки темы типа objects

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

links: ...

Затем добавьте ключевые слова type, default и schema к настройке.

links:
  type: objects
  default: []
  schema: ...

type: objects указывает, что это настройка типа objects, а аннотация default: [] устанавливает значение по умолчанию настройки в виде пустого массива. Обратите внимание, что значение по умолчанию также может быть установлено в виде массива объектов, что мы продемонстрируем после определения schema.

Чтобы определить схему, сначала задайте name схемы следующим образом:

links:
  type: objects
  default: []
  schema:
    name: link

Далее мы добавим ключевое слово properties к схеме, которое позволит нам определить и проверить, как должен выглядеть каждый объект.

links:
  type: objects
  default: []
  schema:
    name: link
    properties:
      name: ...

В приведенном выше примере мы указываем, что объект link имеет свойство name. Чтобы определить тип ожидаемых данных, каждое свойство должно определять ключевое слово type.

links:
  type: objects
  default: []
  schema:
    name: link
    properties:
      name:
        type: string

Приведенное выше определение схемы указывает, что объект link имеет свойство name типа string, что означает, что для свойства будут приняты только строковые значения. В настоящее время поддерживаются следующие типы:

  • string: Значение свойства хранится как строка.
  • integer: Значение свойства хранится как целое число.
  • float: Значение свойства хранится как число с плавающей точкой.
  • boolean: Значение свойства равно true или false.
  • upload: Значение свойства — это URL вложения.
  • enum: Значение свойства должно быть одним из значений, определенных в ключевом слове choices.
    links:
      type: objects
      default: []
      schema:
        name: link
        properties:
          name:
            type: enum
            choices:
              - name 1
              - name 2
              - name 3
    
  • categories: Значение свойства — это массив допустимых идентификаторов категорий.
  • groups: Значение свойства — это массив допустимых идентификаторов групп.
  • tags: Значение свойства — это массив допустимых имен тегов.

После определения схемы значение по умолчанию настройки можно установить, определив массив в YAML следующим образом:

links:
  type: objects
  default:
    - name: link 1
      title: link 1 title
    - name: link 2
      title: link 2 title
  schema:
    name: link
    properties:
      name:
        type: string
      title:
        type: string

Обязательные свойства

Все определенные свойства по умолчанию являются необязательными. Чтобы пометить свойство как обязательное, просто добавьте аннотацию required: true. Свойство также можно пометить как необязательное, добавив аннотацию required: false.

links:
  type: objects
  default: []
  schema:
    name: link
    properties:
      name:
        type: string
        required: true
      title:
        type: string
        required: false

Пользовательские проверки

Для некоторых типов свойств имеется встроенная поддержка пользовательских проверок, которые можно объявить, добавив аннотацию validations к свойству.

links:
  type: objects
  default: []
  schema:
    name: link
    properties:
      name:
        type: string
        required: true
        validations:
          min: 1
          max: 2048
          url: true

Проверки для типов string

  • min_length: Минимальная длина свойства. Значение ключевого слова должно быть целым числом.
  • max_length: Максимальная длина свойства. Значение ключевого слова должно быть целым числом.
  • url: Проверяет, что свойство является допустимым URL. Значение ключевого слова может быть true или false.

Проверки для типов integer и float

  • min: Минимальное значение свойства. Значение ключевого слова должно быть целым числом.
  • max: Максимальное значение свойства. Значение ключевого слова должно быть целым числом.

Проверки для типов tags, groups и categories

  • min: Минимальное количество записей для свойства. Значение ключевого слова должно быть целым числом.
  • max: Максимальное количество записей для свойства. Значение ключевого слова должно быть целым числом.

Вложенная структура объектов

Объект также может иметь свойство, содержащее массив объектов. Чтобы создать вложенную структуру объектов, свойство можно также аннотировать как type: objects с соответствующим определением schema.

sections:
  type: objects
  default:
    - name: section 1
      links:
        - name: link 1
          url: /some/url
        - name: link 2
          url: /some/other/url
  schema:
    name: section
    properties:
      name:
        type: string
        required: true
      links:
        type: objects
        schema:
          name: link
          properties:
            name:
              type: string
            url:
              type: string

Описание настройки и локализация

Чтобы добавить описание настройки в локали en, создайте файл locales/en.yml со следующим форматом, учитывая следующую настройку темы типа objects.

sections:
  type: objects
  default:
    - name: section 1
      links:
        - name: link 1
          url: /some/url
        - name: link 2
          url: /some/other/url
  schema:
    name: section
    properties:
      name:
        type: string
        required: true
      links:
        type: objects
        schema:
          name: link
          properties:
            name:
              type: string
            url:
              type: string
en:
  theme_metadata:
    settings:
      sections:
        description: Это описание для настройки темы sections
        schema:
          properties:
            name:
              label: Имя
              description: Описание свойства
            links:
              name:
                label: Имя
                description: Описание свойства
              url:
                label: URL
                description: Описание свойства

Этот документ находится под контролем версий — предложите изменения на GitHub.

16 лайков

I remain to be convinced deprecation of the json schema style is a good idea.

Whilst these can get pretty complex and aren’t the most “developer friendly” of formats (so this is a great change in that regard), there are online tools to validate json schemas which is a really useful way to validate both the schema and against any default data.

e.g. https://www.jsonschemavalidator.net/

How will that work in this new world?

2 лайка

When uploading a theme, we will be validating the default data against the defined schema. That being said, we are not validating that the schema definition is valid now but it wouldn’t be hard for us to do so. Even for the json schema setting right now, I don’t think we are validating the default data against the defined schema.

Our current implementation of json schema type settings is kind of broken in many ways with the most obvious being the editor in the admin interface. We discussed this internally and decided that it is much easier for us to maintain a limited schema format defined by us instead of allowing all the possibilities that comes along with json schema.

2 лайка

Some cool features here:

  • you can get rid of JSON.parse and access the setting directly to the get object which is really nice.

  • the url validator!

:chefs_kiss: :chefs_kiss:

5 лайков

Is there any way for multiple lines to be respected in the editor?

This default works:

- name: markdown
  value: > 
    ## Heading
      * first bullet
      * second bullet

But once you edit this, the carriage returns are lost

Moreover, it would be nice to have a “text” type that could store more long-form data and perhaps expose a larger “text-area” editor

5 лайков

Here are some feedbacks:

2 лайка

I noticed this and it has been fixed in

1 лайк

Will we be able to re-order items on the interface?

E.g. that’s the object settings editor on the easy footer theme component. I can’t re-arrange any items right now:

image

4 лайка

I wanted to request this feature as well! :+1:


On a side note, it would be helpful if the first post contained information about the identifier property.

Before looking at Nolo’s image above, I thought replacing the default child label with a property value was impossible. After looking at the code, I found the identifier property.

4 лайка

Reordering is certainly something that has been brought up internally as well. I’ll try to land that this week.

Noted. I’ll update the first post about the identifier property.

5 лайков

Yep to replace the (soon to be legacy?) json system it needs to match or exceed the old interface:

image

including the ordering.

1 лайк

Hi, are there any plans to support other field types soon?

For example;

  • a long_string with markdown format; perhaps with customizable toolbar,
  • a date field (with validation rules),
  • a color field (with validation rules)?
1 лайк

There’s no current plan, though I agree that it would be useful. I’d like an icon field myself.

8 лайков

In my experience, it seems to be working like saved presets. In this example the first 2 entries could benefit from these presets, but anything after that all new entries will come up blank initially.

This also means we cannot set default values for each field. for example, if I want to have a checkbox, to start at checked state I cannot have it.

links:
  type: objects
  default:
    - name: link 1
      title: link 1 title
    - name: link 2
      title: link 2 title
  schema:
    name: link
    properties:
      is_active:
        type: boolean
        default: true 

default: true will not work in there as expected.

Could there be a way to set the default values per field, for each entries that are created?

Is there a way to import object properties to variables in Sass?

You can always parse the string, but that doesn’t sound like a great idea to promote this way. :sweat_smile:

1 лайк

Thank you for sharing the example! Though yeah… it doesn’t look that tempting :upside_down_face:

1 лайк

Out of interest, without spending too much time looking, where are we with this?

2 лайка

Yes, it isn’t very good, don’t do it. :smile:. It was more of an attempt to see if it was possible, but not a reasonable approach.
I agree with you; it would be nice to have a direct way! :+1:

I would like to know, too!
Also, if I’m right, that would be the only missing feature parity with the json_schema.

2 лайка

I was looking for the upload type to be available, but it’s not.
A quick look at the core shows that the topic, post, and upload types have been implemented server-side but not in the front end. Is there a specific reason for that? :thinking: