11import { Controller } from 'stimulus' ;
22import domtoimage from 'dom-to-image' ;
3+ import axios from 'axios'
34
45export default class extends Controller {
56 static targets = [ 'code' ]
67
7- capture ( ) {
8- const scale = 2 ;
9- const node = this . codeTarget
10- const options = {
11- height : node . offsetHeight * scale ,
12- width : node . offsetWidth * scale ,
13- style : {
14- transform : "scale(" + scale + ")" ,
15- transformOrigin : "top left" ,
16- width : node . offsetWidth + "px" ,
17- height : node . offsetHeight + "px"
18- }
19- }
8+ initialize ( ) {
9+ const csrfToken = document . querySelector ( "meta[name=csrf-token]" ) . content
10+ axios . defaults . headers . common [ 'X-CSRF-Token' ] = csrfToken
11+ }
2012
21- domtoimage . toJpeg ( node , options )
22- . then ( this . downloadImage )
23- . catch ( console . error )
13+ toDataUrl ( ) {
14+ return domtoimage . toPng ( this . codeTarget , this . imageConfig )
2415 }
2516
17+ toBlob ( ) {
18+ return domtoimage . toBlob ( this . codeTarget , this . imageConfig )
19+ }
20+
21+ tweet ( ) {
22+ this . toBlob ( )
23+ . then ( this . tweetImage )
24+ . catch ( console . error )
25+ }
26+
27+ download ( ) {
28+ this . toDataUrl ( )
29+ . then ( this . downloadImage )
30+ . catch ( console . error )
31+ }
32+
33+ tweetImage ( blob ) {
34+ let fd = new FormData ( ) ;
35+ fd . append ( 'fname' , 'tweet.png' ) ;
36+ fd . append ( 'data' , blob ) ;
37+
38+ const headers = { 'Content-Type' : `multipart/form-data` }
39+
40+ axios . post ( `/tweets` , fd , { headers } )
41+ . then ( res => {
42+ console . log ( 'tweeted!' )
43+ // create the twet intent with the created media url in it
44+ } )
45+ . catch ( console . error )
46+ }
47+
2648 downloadImage ( dataUrl ) {
2749 let link = document . createElement ( 'a' )
2850
29- link . setAttribute ( 'download' , 'snippetsafe.jpeg ' ) ;
51+ link . setAttribute ( 'download' , 'snippetsafe.png ' ) ;
3052 link . setAttribute ( 'href' , dataUrl ) ;
3153 link . click ( ) ;
3254 link . remove ( )
3355 }
56+
57+ get imageConfig ( ) {
58+ const scale = 2 ;
59+
60+ return {
61+ height : this . codeTarget . offsetHeight * scale ,
62+ width : this . codeTarget . offsetWidth * scale ,
63+ style : {
64+ transform : "scale(" + scale + ")" ,
65+ transformOrigin : "top left" ,
66+ width : this . codeTarget . offsetWidth + "px" ,
67+ height : this . codeTarget . offsetHeight + "px"
68+ }
69+ }
70+ }
3471}
0 commit comments