Sha256: b5ec4ed7f550fa683d184dfd6f0f15327bc9ec4ac04cda0d29d7f451685010b0

Contents?: true

Size: 1 KB

Versions: 9

Compression:

Stored size: 1 KB

Contents

import { Controller } from "@hotwired/stimulus"

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

  #applicationName = 'MyApplication'

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

  async share() {
    try {
      await navigator.share(await this.#getShareData())
    } catch(error) {
      console.warn(error.message);
    }
  }

  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 = `${this.#applicationName}_${Math.random().toString(36).slice(2)}`
    const fileName = `${randomPrefix}.${blob.type.split('/').pop()}`

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

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
css-zero-0.0.44 lib/generators/css_zero/add/templates/app/javascript/controllers/web_share_controller.js
css-zero-0.0.43 lib/generators/css_zero/add/templates/app/javascript/controllers/web_share_controller.js
css-zero-0.0.42 lib/generators/css_zero/add/templates/app/javascript/controllers/web_share_controller.js
css-zero-0.0.41 lib/generators/css_zero/add/templates/app/javascript/controllers/web_share_controller.js
css-zero-0.0.40 lib/generators/css_zero/add/templates/app/javascript/controllers/web_share_controller.js
css-zero-0.0.39 lib/generators/css_zero/add/templates/app/javascript/controllers/web_share_controller.js
css-zero-0.0.38 lib/generators/css_zero/add/templates/app/javascript/controllers/web_share_controller.js
css-zero-0.0.37 lib/generators/css_zero/add/templates/app/javascript/controllers/web_share_controller.js
css-zero-0.0.36 lib/generators/css_zero/add/templates/app/javascript/controllers/web_share_controller.js