Skip to content

Commit

Permalink
refactor: improve code quality
Browse files Browse the repository at this point in the history
  • Loading branch information
azat-io committed Nov 12, 2024
1 parent 066cf61 commit f426f6e
Show file tree
Hide file tree
Showing 22 changed files with 113 additions and 72 deletions.
2 changes: 1 addition & 1 deletion api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,5 @@ export let picturesque = async (
body: formData,
method: 'POST',
})
return await response.json()
return (await response.json()) as Response
}
8 changes: 5 additions & 3 deletions components/code.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,22 @@
import { firstLoad, loading, code } from '~/stores/code'
import Loader from '~/components/loader.svelte'
import { shiki } from '~/stores/shiki'
$: ({ highlighter, theme } = $shiki)
</script>

<div class:loading={$loading && !$firstLoad} class="wrapper">
{#if !$firstLoad && $shiki.highlighter}
{#if !$firstLoad && highlighter}
<ShikiMagicMove
options={{
animateContainer: false,
duration: 500,
stagger: 3,
}}
highlighter={$shiki.highlighter}
theme={$shiki.theme}
{highlighter}
code={$code}
lang="scss"
{theme}
/>
{:else}
<div class="loader-container">
Expand Down
4 changes: 2 additions & 2 deletions components/copy-code.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
import Button from '~/components/button.svelte'
import { loading, code } from '~/stores/code'
let copyCode = () => {
navigator.clipboard.writeText($code)
let copyCode = async (): Promise<void> => {
await navigator.clipboard.writeText($code)
}
</script>

Expand Down
4 changes: 2 additions & 2 deletions components/download.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@
import Button from '~/components/button.svelte'
import { loading, zip } from '~/stores/zip'
$: download = () => {
let download = (): void => {
if ($zip && $partnerName) {
let url = URL.createObjectURL($zip)
let a = document.createElement('a')
a.href = url
a.download = `${$partnerName}.zip`
document.body.appendChild(a)
document.body.append(a)
a.click()
a.remove()
URL.revokeObjectURL(url)
Expand Down
22 changes: 14 additions & 8 deletions components/form.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -21,41 +21,47 @@
<div class="form-data">
<div class="form-group">
<Label htmlFor="name">Имя партнёра</Label>
<Input onChange={value => partnerName.set(value)} value={$partnerName} />
<Input
onChange={(value: string) => partnerName.set(value)}
value={$partnerName}
/>
</div>
<div class="form-group">
<Label htmlFor="name">Тип продукта</Label>
<Select
onChange={value => vertical.set(value)}
onChange={(value: string) => vertical.set(value)}
options={verticals}
value={$vertical}
/>
</div>
<div class="form-group">
<Label htmlFor="name">Использовать <code>!important</code></Label>
<Checkbox
onChange={value => useImportant.set(value)}
onChange={(value: boolean) => useImportant.set(value)}
value={$useImportant}
/>
</div>
<div class="form-group">
<Label htmlFor="name">Градиент</Label>
<Select
onChange={value => gradientDirection.set(value)}
onChange={(value: string) => gradientDirection.set(value)}
options={gradientDirections}
value={$gradientDirection}
/>
</div>
<div class="form-group">
<Label htmlFor="name">Качество</Label>
<Select
options={qualities.map(q => ({ value: q.toString(), name: `${q}%` }))}
onChange={value => quality.set(parseInt(value))}
value={$quality.toString()}
options={qualities.map(qualityValue => ({
value: qualityValue.toString(),
name: `${qualityValue}%`,
}))}
onChange={(value: string) => quality.set(Number.parseInt(value))}
value={`${$quality}`}
/>
</div>
<div>
<FileUpload onChange={value => image.set(value)}>
<FileUpload onChange={(value: File) => image.set(value)}>
Загрузить картинку
<svg
xmlns="http://www.w3.org/2000/svg"
Expand Down
7 changes: 3 additions & 4 deletions components/gradient.svelte
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
<script lang="ts">
import { gradientDirection, gradients } from '~/stores/form-data'
$: gradientDirectionValue = $gradients?.[$gradientDirection]
</script>

<div
style="background: {$gradients?.[$gradientDirection]}"
class="gradient"
></div>
<div style:background={gradientDirectionValue} class="gradient" />

<style>
.gradient {
Expand Down
2 changes: 2 additions & 0 deletions components/hr.svelte
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
<script lang="ts"></script>

<hr class="hr" />

<style>
Expand Down
4 changes: 2 additions & 2 deletions components/image.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
import { image } from '~/stores/form-data'
$: imageUrl = writable<string | null>(null)
let imageUrl = writable<string | null>(null)
$: if ($image) {
let reader = new FileReader()
reader.readAsDataURL($image)
reader.onloadend = () => {
$imageUrl = reader.result as string
imageUrl.set(reader.result as string)
}
}
</script>
Expand Down
2 changes: 1 addition & 1 deletion components/input.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
let timer: ReturnType<typeof setTimeout>
let debounce = (newValue: string) => {
let debounce = (newValue: string): void => {
clearTimeout(timer)
timer = setTimeout(() => {
onChange(newValue)
Expand Down
2 changes: 2 additions & 0 deletions components/ott-logo.svelte
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
<script lang="ts"></script>

<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 32 32"
Expand Down
2 changes: 2 additions & 0 deletions components/picturesque-logo.svelte
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
<script lang="ts"></script>

<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 139 22"
Expand Down
2 changes: 1 addition & 1 deletion components/select.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
}}
class="select"
>
{#each options as { value: optionValue, name }}
{#each options as { value: optionValue, name } (optionValue)}
<option selected={optionValue === value} value={optionValue}>
{name}
</option>
Expand Down
26 changes: 15 additions & 11 deletions components/size-status.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -11,31 +11,35 @@
}
let calculatePercent = (original: number, current: number): number =>
parseFloat((100 - (current * 100) / original).toFixed(2))
Number.parseFloat((100 - (current * 100) / original).toFixed(2))
$: originalSize = $sizes?.original ?? Number.NaN
$: desktopSize = $sizes?.desktop ?? Number.NaN
$: mobileSize = $sizes?.mobile ?? Number.NaN
</script>

{#if $sizes && !$loading}
<p
class:success={$sizes.original > $sizes.desktop}
class:error={$sizes.original < $sizes.desktop}
class:success={originalSize > desktopSize}
class:error={originalSize < desktopSize}
class="status"
>
<b>Десктоп:</b>
{convertBytes($sizes.original)}
kB → {convertBytes($sizes.desktop)} kB ({$sizes.original < $sizes.desktop
{convertBytes(originalSize)}
kB → {convertBytes(desktopSize)} kB ({originalSize < desktopSize
? '+'
: ''}{calculatePercent($sizes.original, $sizes.desktop) * -1}%)
: ''}{calculatePercent(originalSize, desktopSize) * -1}%)
</p>
<p
class:success={$sizes.original > $sizes.mobile}
class:error={$sizes.original < $sizes.mobile}
class:success={originalSize > mobileSize}
class:error={originalSize < mobileSize}
class="status"
>
<b>Мобила:</b>
{convertBytes($sizes.original)}
kB → {convertBytes($sizes.mobile)} kB ({$sizes.original < $sizes.mobile
{convertBytes(originalSize)}
kB → {convertBytes(mobileSize)} kB ({originalSize < mobileSize
? '+'
: ''}{calculatePercent($sizes.original, $sizes.mobile) * -1}%)
: ''}{calculatePercent(originalSize, mobileSize) * -1}%)
</p>
{/if}

Expand Down
2 changes: 1 addition & 1 deletion components/theme-toggle.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { toggleColorTheme, colorTheme } from '~/stores/color-theme'
</script>

<button on:click={toggleColorTheme} class="theme-toggle">
<button on:click={toggleColorTheme} class="theme-toggle" type="button">
{#if $colorTheme === 'dark'}
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" class="icon">
<path
Expand Down
2 changes: 2 additions & 0 deletions components/title.svelte
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
<script lang="ts"></script>

<h2 class="title">
<slot />
</h2>
Expand Down
64 changes: 42 additions & 22 deletions functions/picturesque.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ let parseMultipartForm = (event: HandlerEvent): Promise<Fields | null> =>
let { filename, mimeType } = info
let chunks: Buffer[] = []

file.on('data', data => {
file.on('data', (data: Buffer) => {
chunks.push(data)
})

Expand All @@ -48,8 +48,8 @@ let parseMultipartForm = (event: HandlerEvent): Promise<Fields | null> =>
resolve(fields)
})

bb.on('error', err => {
reject(err)
bb.on('error', _error => {
reject(new Error('Unable to parse form data'))
})

bb.end(Buffer.from(event.body!, 'base64'))
Expand All @@ -58,7 +58,12 @@ let parseMultipartForm = (event: HandlerEvent): Promise<Fields | null> =>
let rgbaToHex = ({ r, g, b }: { r: number; g: number; b: number }): string =>
`#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`

let generateImages = async (buffer: Buffer, quality: number) => {
let generateImages = async (
buffer: Buffer,
quality: number,
): Promise<
Record<'webp', Record<'desktop' | 'tablet' | 'mobile', string | null>>
> => {
let metadata = await sharp(buffer).metadata()
let { height, width } = metadata
let sizes = [
Expand Down Expand Up @@ -101,14 +106,19 @@ let generateImages = async (buffer: Buffer, quality: number) => {

type Images = Record<
(typeof formats)[number]['format'],
{
[key in (typeof sizes)[number]['suffix']]: string
}
Record<(typeof sizes)[number]['suffix'], string | null>
>

let images: Images = formats.reduce(
(accumulator, { format }) => ({ ...accumulator, [format]: {} }) as Images,
{} as Images,
let images: Images = formats.reduce<Images>(
(accumulator: Images, { format }) =>
({ ...accumulator, [format]: {} }) as Images,
{
webp: {
desktop: null,
tablet: null,
mobile: null,
},
},
)

for (let result of results) {
Expand All @@ -124,13 +134,21 @@ let generateImages = async (buffer: Buffer, quality: number) => {

let getSizes = async (
buffer: Buffer,
images: { desktop: string; mobile: string },
) => {
images: { desktop: string | null; mobile: string | null },
): Promise<{
original?: number
desktop: number
mobile: number
}> => {
let originalMetadata = await sharp(buffer).metadata()
let clean = (image: string) => Buffer.from(image, 'base64')
let clean = (image: string): Buffer => Buffer.from(image, 'base64')
return {
desktop: clean(images.desktop).length,
mobile: clean(images.mobile).length,
desktop: images.desktop
? clean(images.desktop).length
: originalMetadata.size!,
mobile: images.mobile
? clean(images.mobile).length
: originalMetadata.size!,
original: originalMetadata.size,
}
}
Expand All @@ -142,7 +160,7 @@ interface Gradients {
'to right': string
}

const getGradients = async (buffer: Buffer): Promise<Gradients> => {
let getGradients = async (buffer: Buffer): Promise<Gradients> => {
let img = await Jimp.read(buffer)
let { height, width } = img.bitmap

Expand Down Expand Up @@ -175,11 +193,13 @@ const getGradients = async (buffer: Buffer): Promise<Gradients> => {
>

for (let direction in points) {
let colors = points[direction as keyof typeof points].map(point =>
rgbaToHex(intToRGBA(img.getPixelColor(point.x, point.y))),
) as [string, string, string]
gradients[direction as keyof Gradients] =
`linear-gradient(${direction}, ${colors.join(', ')})`
if (direction) {
let colors = points[direction as keyof typeof points].map(point =>
rgbaToHex(intToRGBA(img.getPixelColor(point.x, point.y))),
) as [string, string, string]
gradients[direction as keyof Gradients] =
`linear-gradient(${direction}, ${colors.join(', ')})`
}
}

return gradients
Expand All @@ -204,7 +224,7 @@ export let handler: Handler = async (

let [image] = fields.image
let buffer = image.content
let quality = parseInt(fields.quality as string, 10)
let quality = Number.parseInt(fields.quality as string, 10)

/**
* Generate a gradient from the image's center points
Expand Down
5 changes: 3 additions & 2 deletions stores/code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import {
} from '~/stores/form-data'

let formatGradientString = (gradientValue: string): string => {
let parts = gradientValue.match(/(linear-gradient\()(.*)(\))/)
let parts = gradientValue.match(/linear-gradient\((?<content>.*)\)/u)

if (!parts) {
throw new Error('Invalid gradient string')
}
Expand All @@ -31,7 +32,7 @@ export let code = computed(
useImportantValue,
gradientsValue,
gradientDirectionValue,
) => {
): string => {
let important = useImportantValue ? ' !important' : ''
return `[data-wl-status="${verticalValue}_index"] .App__content:before {
background-color: ${gradientsValue ? formatGradientString(gradientsValue[gradientDirectionValue]) : '#212121'}${important};
Expand Down
Loading

0 comments on commit f426f6e

Please sign in to comment.