Sha256: 2bf511ab8541f038d40d9cddbb3ea70a5b98666d5dba8216a754c2ac34bbc848

Contents?: true

Size: 978 Bytes

Versions: 10

Compression:

Stored size: 978 Bytes

Contents

import { Controller } from "@hotwired/stimulus"

const APPLICATION_NAME = "my_application"

export default class extends Controller {
  static values = { title: String, text: String, url: String, file: String }

  connect() {
    this.element.hidden = !navigator.canShare
  }

  async share() {
    try {
      await navigator.share(await this.#getShareData())
    } catch {}
  }

  async #getShareData() {
    const data = { title: this.titleValue, text: this.textValue }

    if (this.urlValue) {
      data.url = this.urlValue
    }

    if (this.fileValue) {
      data.files = [await this.#getFileObject()]
    }

    return data
  }

  async #getFileObject() {
    const response = await fetch(this.fileValue)
    const blob = await response.blob()
    const randomPrefix = `${APPLICATION_NAME}_${Math.random().toString(36).slice(2)}`
    const fileName = `${randomPrefix}.${blob.type.split('/').pop()}`

    return new File([ blob ], fileName, { type: blob.type })
  }
}

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
css-zero-1.0.4 lib/generators/css_zero/add/templates/app/javascript/controllers/web_share_controller.js
css-zero-1.0.3 lib/generators/css_zero/add/templates/app/javascript/controllers/web_share_controller.js
css-zero-1.0.2 lib/generators/css_zero/add/templates/app/javascript/controllers/web_share_controller.js
css-zero-1.0.1 lib/generators/css_zero/add/templates/app/javascript/controllers/web_share_controller.js
css-zero-1.0.0 lib/generators/css_zero/add/templates/app/javascript/controllers/web_share_controller.js
css-zero-0.0.98 lib/generators/css_zero/add/templates/app/javascript/controllers/web_share_controller.js
css-zero-0.0.97 lib/generators/css_zero/add/templates/app/javascript/controllers/web_share_controller.js
css-zero-0.0.96 lib/generators/css_zero/add/templates/app/javascript/controllers/web_share_controller.js
css-zero-0.0.95 lib/generators/css_zero/add/templates/app/javascript/controllers/web_share_controller.js
css-zero-0.0.94 lib/generators/css_zero/add/templates/app/javascript/controllers/web_share_controller.js