1.0.0 • Published 6 years ago

@westart/aide-bridge v1.0.0

Weekly downloads
-
License
ISC
Repository
-
Last release
6 years ago

WA Aide JS Bridge

Provides JS interface for static data transfer from WP back-end, as alternative for localize_scripts approach.

Functionality

// one time import, which automatically binds Bridge to window object
import "wa-aide-bridge"

// Safely get values, with default parameters
Bridge.get("global", "ajaxurl", "/wp-admin/admin-ajax.php")
// Undefined values are reported to dev console
Bridge.get("namespace", "my_value") // Warning: "Undefined value: namespace.my_value"

// Get translated strings with default value
Bridge.translate("global", "hello_{name}", "Hello {name}")

// Defaults for translation could be often skipped, 
// since WordPress gettext functions default to key anyway
Bridge.translate("global", "hello_{name}")
// en > Hello {name}!
// sv > Hej {name}!
// ?? > Hello {name}!

// Even when value is undefined, translation function will yield key instead
// and guarantees that returned value is always string,
// unless used with defined TypeScript data structure
Bridge.translate("global", "hello_{name}") // hello_{name}
Bridge.translate("global", "object_not_string") // [object Object]


// Get namespaced object
const global = Bridge.ns("global")
global.get("ajaxurl", "/wp-admin/admin-ajax.php")
global.translate("hello_{name}")
global.translate("object_not_string")

// Check values availability
Bridge.has("global", "ajaxurl") // or
global.has("ajaxurl")
Bridge.hasTranslation("global", "hello_{name}") // or
global.hasTranslation("hello_{name}")

Using TypeScript

With TypeScript, it is possible to define expected data structure

interface DataScheme extends Bridge.Scheme {
  data: {
    global: {
      things: 42,
      likes: 12
    }
  },
  i18n: {
    global: {
      greeting: "Hello!"
    }
  }
}

const bridge: Bridge<DataScheme> = Bridge

bridge.get("global", "things") // 42
bridge.get("global", "stuff") // Compile error!
bridge.get("global", "stuff", 75) // Still compile error! because undefined on compile time != undefined on runtime
bridge.ns("global").translate("greeting") // Hello!
bridge.ns("global").translate("goodbye") // Compile error!
bridge.ns("things") // Compile error!