Sha256: 06c5aed4f3c909c10376a5a6f480aeb09b8ecb2c16a7633c03fad43a7773ad82

Contents?: true

Size: 1.17 KB

Versions: 26

Compression:

Stored size: 1.17 KB

Contents

export const htmlAttributes = (params: Record<string, any>) => {
  const customDataAttributes = params.data || {}
  const others = Object.keys(params).filter(key => key !== "data")

  const flattenDataAttributes = (data: Record<string, any>, prefix = "data") => {
    return Object.keys(data).reduce((acc, key) => {
      const value = data[key]
      if (typeof value === "object" && value !== null) {
        acc.push(...flattenDataAttributes(value, `${prefix}-${key}`))
      } else {
        acc.push(`${prefix}-${key}='${escapeHtml(value)}'`)
      }
      return acc
    }, [] as string[])
  }

  return [
    others.map(key => {
      if (key === "disabled") {
        if (params[key] === false) {
          return ""
        } else {
          return `${key}`
        }
      }
      return `${key}='${escapeHtml(params[key])}'`
    }).join(" "),
    flattenDataAttributes(customDataAttributes).join(" ")
  ].filter(Boolean).join(" ")
}

const escapeHtml = (unsafe: string) => {
  if (typeof unsafe !== "string") {
    return ""
  }
  return unsafe
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
}

Version data entries

26 entries across 26 versions & 1 rubygems

Version Path
clapton-0.0.26 lib/clapton/javascripts/src/html/html-attributes.ts
clapton-0.0.25 lib/clapton/javascripts/src/html/html-attributes.ts
clapton-0.0.24 lib/clapton/javascripts/src/html/html-attributes.ts
clapton-0.0.23 lib/clapton/javascripts/src/html/html-attributes.ts
clapton-0.0.22 lib/clapton/javascripts/src/html/html-attributes.ts
clapton-0.0.21 lib/clapton/javascripts/src/html/html-attributes.ts
clapton-0.0.20 lib/clapton/javascripts/src/html/html-attributes.ts
clapton-0.0.19 lib/clapton/javascripts/src/html/html-attributes.ts
clapton-0.0.18 lib/clapton/javascripts/src/html/html-attributes.ts
clapton-0.0.17 lib/clapton/javascripts/src/html/html-attributes.ts
clapton-0.0.16 lib/clapton/javascripts/src/html/html-attributes.ts
clapton-0.0.15 lib/clapton/javascripts/src/html/html-attributes.ts
clapton-0.0.14 lib/clapton/javascripts/src/html/html-attributes.ts
clapton-0.0.13 lib/clapton/javascripts/src/html/html-attributes.ts
clapton-0.0.12 lib/clapton/javascripts/src/html/html-attributes.ts
clapton-0.0.11 lib/clapton/javascripts/src/html/html-attributes.ts
clapton-0.0.10 lib/clapton/javascripts/src/html/html-attributes.ts
clapton-0.0.9 lib/clapton/javascripts/src/html/html-attributes.ts
clapton-0.0.8 lib/clapton/javascripts/src/html/html-attributes.ts
clapton-0.0.7 lib/clapton/javascripts/src/html/html-attributes.ts