|
1 | 1 | import { Component, Part } from '@pictogrammers/element'; |
2 | 2 | import PgInputPixelEditor from '../../inputPixelEditor'; |
| 3 | +import { maskToBitmap } from '../../utils/maskToBitmap'; |
3 | 4 |
|
4 | 5 | import template from './basic.html'; |
5 | 6 | import style from './basic.css'; |
@@ -33,6 +34,9 @@ export default class XPgInputPixelEditorBasic extends HTMLElement { |
33 | 34 | @Part() $save: HTMLButtonElement; |
34 | 35 | @Part() $open: HTMLButtonElement; |
35 | 36 | @Part() $output: HTMLPreElement; |
| 37 | + @Part() $file: HTMLInputElement; |
| 38 | + @Part() $saveSvg: HTMLInputElement; |
| 39 | + @Part() $savePng: HTMLInputElement; |
36 | 40 |
|
37 | 41 | @Part() $colors: HTMLPreElement; |
38 | 42 | @Part() $layers: HTMLPreElement; |
@@ -83,6 +87,53 @@ export default class XPgInputPixelEditorBasic extends HTMLElement { |
83 | 87 | const json = JSON.parse(this.$output.textContent || ''); |
84 | 88 | this.$input.open(json as any); |
85 | 89 | }); |
| 90 | + this.$file.addEventListener('change', this.handleFile.bind(this)); |
| 91 | + this.$saveSvg.addEventListener('click', async () => { |
| 92 | + // @ts-ignore |
| 93 | + const handle = await window.showSaveFilePicker({ |
| 94 | + suggestedName: 'CanvasName', |
| 95 | + types: [{ |
| 96 | + description: 'SVG Document', |
| 97 | + accept: {'image/svg+xml': ['.svg']}, |
| 98 | + }], |
| 99 | + }); |
| 100 | + const writable = await handle.createWritable(); |
| 101 | + await writable.write('something'); |
| 102 | + await writable.close(); |
| 103 | + }); |
| 104 | + this.$savePng.addEventListener('click', () => { |
| 105 | + |
| 106 | + }); |
| 107 | + } |
| 108 | + |
| 109 | + handleFile(e) { |
| 110 | + const { files } = e.currentTarget; |
| 111 | + if (files.length !== 1) { |
| 112 | + throw new Error('select only 1 file'); |
| 113 | + } |
| 114 | + switch(files[0].type) { |
| 115 | + case 'image/svg+xml': |
| 116 | + // Read the file |
| 117 | + const reader = new FileReader(); |
| 118 | + reader.onload = () => { |
| 119 | + const content = reader.result as string; |
| 120 | + const size = content.match(/viewBox="\d+ \d+ (\d+) (\d+)"/) as string[]; |
| 121 | + const width = parseInt(size[1], 10); |
| 122 | + const height = parseInt(size[2], 10); |
| 123 | + const path = (content.match(/d="([^"]+)"/) as string[])[1]; |
| 124 | + // Render path |
| 125 | + console.log(path, size[1], size[2]); |
| 126 | + this.$input.applyTemplate(maskToBitmap(path, width, height)); |
| 127 | + ; |
| 128 | + }; |
| 129 | + reader.onerror = () => { |
| 130 | + throw new Error("Error reading the file. Please try again."); |
| 131 | + }; |
| 132 | + reader.readAsText(files[0]); |
| 133 | + break; |
| 134 | + default: |
| 135 | + throw new Error('Unsupported format.'); |
| 136 | + } |
86 | 137 | } |
87 | 138 |
|
88 | 139 | handleChange(e: CustomEvent) { |
|
0 commit comments