mirror of
https://github.com/penpot/penpot-plugins.git
synced 2025-02-08 08:09:18 -05:00
feat(poc-state-plugin): add example uploading files
This commit is contained in:
parent
7ce2cae2b9
commit
7a521e1b16
2 changed files with 41 additions and 0 deletions
|
@ -90,6 +90,8 @@ import type { PenpotShape } from '@penpot/plugin-types';
|
|||
>
|
||||
Rotate
|
||||
</button>
|
||||
|
||||
<input type="file" class="file-upload" (change)="uploadImage($event)" />
|
||||
</div>
|
||||
|
||||
<p>
|
||||
|
@ -216,6 +218,24 @@ export class AppComponent {
|
|||
this.#sendMessage({ content: 'rotate-selection' });
|
||||
}
|
||||
|
||||
async uploadImage(event: Event) {
|
||||
const input = event.target as HTMLInputElement;
|
||||
if (input?.files?.length) {
|
||||
const file = input?.files[0];
|
||||
|
||||
if (file) {
|
||||
const buff = await file.arrayBuffer();
|
||||
const data = new Uint8Array(buff);
|
||||
const mimeType = file.type;
|
||||
this.#sendMessage({
|
||||
content: 'create-image-data',
|
||||
data: { data, mimeType },
|
||||
});
|
||||
input.value = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#sendMessage(message: unknown) {
|
||||
parent.postMessage(message, '*');
|
||||
}
|
||||
|
|
|
@ -36,6 +36,12 @@ penpot.ui.onMessage<{ content: string; data: unknown }>((message) => {
|
|||
wordStyles();
|
||||
} else if (message.content === 'rotate-selection') {
|
||||
rotateSelection();
|
||||
} else if (message.content === 'create-image-data') {
|
||||
const { data, mimeType } = message.data as {
|
||||
data: Uint8Array;
|
||||
mimeType: string;
|
||||
};
|
||||
createImage(data, mimeType);
|
||||
}
|
||||
});
|
||||
|
||||
|
@ -395,3 +401,18 @@ function rotateSelection() {
|
|||
shape.rotate(10, center);
|
||||
});
|
||||
}
|
||||
|
||||
function createImage(data: Uint8Array, mimeType: string) {
|
||||
penpot
|
||||
.uploadMediaData('image', data, mimeType)
|
||||
.then((data) => {
|
||||
const shape = penpot.createRectangle();
|
||||
const x = penpot.viewport.center.x - data.width / 2;
|
||||
const y = penpot.viewport.center.y - data.height / 2;
|
||||
shape.resize(data.width, data.height);
|
||||
shape.x = x;
|
||||
shape.y = y;
|
||||
shape.fills = [{ fillOpacity: 1, fillImage: data }];
|
||||
})
|
||||
.catch((err) => console.error(err));
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue