ficusjs / ficusjs-i18n

Functions for managing translations and localization in FicusJS components
MIT License
1 stars 1 forks source link

Automatically maintaining the 'lang' attribute on components with reactive i18n #56

Closed mesr closed 1 year ago

mesr commented 1 year ago

I would like to propose and, if approved, offer to implement a new feature on components with reactive i18n that would automatically maintain the lang attribute where appropriate.

Given that lang is a well-defined global attribute that should not be used for other purposes, and that the i18n extension is implemented as a global singleton, it seems to me that on localized reactive components this attribute could — and probably should — be automatically updated in reaction to locale changes. This would have the double benefits of better adhering to the HTML guidelines, as well as improving accessibility at no additional cost for users.

This is a first draft of what the proposed changes could look like (file src/with-i18n.mjs):

export function withI18nReactive (i18n, options) {
  return withI18n(i18n, {

    /* ... */

    updated () {

      // Function that returns an array of all ancestor elements
      const getAncestorElements = elem => elem.parentElement
        ? [elem.parentElement].concat(getAncestorElements(elem.parentElement)) : []

      // Read the locale of the nearest ancestor with a 'lang' attribute, or
      // `undefined` if none exists
      const contextLocale = getAncestorElements(this)
        .find(elem => elem.hasAttribute('lang'))?.getAttribute('lang')

      // Set the 'lang' attribute on this element if not already set and if
      // different than the context's
      const currentLocale = this.getLocale()
      if (!this.getAttribute('lang') && currentLocale !== contextLocale) {
        this.setAttribute('lang', currentLocale)
      }

      if (options.updated) options.updated.call(this)
    }
  })
}

Tests and documentation would be updated accordingly.

mlevy-liftoff commented 1 year ago

Thank you @mesr for your proposal. I would like to see that feature included. As you mentioned, it better aligns with HTML standards and that is one of the main goals for FicusJS 😎

mesr commented 1 year ago

Submitted PR #58