Image Compare
Tampilan sebelum dan sesudah dengan pembatas yang bisa digeser, diklik, atau dipindah lewat keyboard. Horizontal atau vertikal, isi bebas termasuk img.
@php
$frame = 'relative aspect-[8/5] w-full overflow-hidden bg-linear-to-b from-warning/35 via-warning/10 to-success/20';
$sun = 'absolute top-8 right-20 size-14 rounded-full bg-warning';
$hills = 'absolute inset-x-0 bottom-0 h-3/5 w-full';
$far = 'fill-success/50';
$near = 'fill-success';
$lake = 'fill-surface/50';
// One deterministic landscape, toned flat (before) or vivid (after).
$panels = ['before' => 'grayscale contrast-75', 'after' => 'saturate-150'];
@endphp
<x-markas.image-compare aria-label="Photo edit, before and after">
@foreach ($panels as $side => $tone)
<x-slot :name="$side">
<div class="{{ $frame }} {{ $tone }}">
<span class="{{ $sun }}"></span>
<svg class="{{ $hills }}" viewBox="0 0 480 180" preserveAspectRatio="none" aria-hidden="true">
<path class="{{ $far }}" d="M0 90 70 40l70 45 80-55 90 65 80-50 90 35v100H0Z" />
<path class="{{ $near }}" d="M0 130c80-30 150-10 230-25s170 15 250-5v80H0Z" />
<path class="{{ $lake }}" d="M0 160c120-12 360-12 480 0v20H0Z" />
</svg>
</div>
</x-slot>
@endforeach
</x-markas.image-compare>import { ImageCompare } from "@/components/markas/ImageCompare";
const frame =
"relative aspect-[8/5] w-full overflow-hidden bg-linear-to-b from-warning/35 via-warning/10 to-success/20";
const sun = "absolute top-8 right-20 size-14 rounded-full bg-warning";
const hills = "absolute inset-x-0 bottom-0 h-3/5 w-full";
const far = "fill-success/50";
const near = "fill-success";
const lake = "fill-surface/50";
/** One deterministic landscape, toned flat (before) or vivid (after). */
const scene = (tone: string) => (
<div className={`${frame} ${tone}`}>
<span className={sun}></span>
<svg
className={hills}
viewBox="0 0 480 180"
preserveAspectRatio="none"
aria-hidden="true"
>
<path
className={far}
d="M0 90 70 40l70 45 80-55 90 65 80-50 90 35v100H0Z"
/>
<path
className={near}
d="M0 130c80-30 150-10 230-25s170 15 250-5v80H0Z"
/>
<path className={lake} d="M0 160c120-12 360-12 480 0v20H0Z" />
</svg>
</div>
);
export default function ImageCompareExample() {
return (
<ImageCompare
before={scene("grayscale contrast-75")}
after={scene("saturate-150")}
aria-label="Photo edit, before and after"
/>
);
}<script setup lang="ts">
import ImageCompare from "@/components/markas/ImageCompare.vue";
const frame =
"relative aspect-[8/5] w-full overflow-hidden bg-linear-to-b from-warning/35 via-warning/10 to-success/20";
const sun = "absolute top-8 right-20 size-14 rounded-full bg-warning";
const hills = "absolute inset-x-0 bottom-0 h-3/5 w-full";
const far = "fill-success/50";
const near = "fill-success";
const lake = "fill-surface/50";
/** One deterministic landscape, toned flat (before) or vivid (after). */
const panels = [
{ slot: "before", tone: "grayscale contrast-75" },
{ slot: "after", tone: "saturate-150" },
] as const;
</script>
<template>
<ImageCompare aria-label="Photo edit, before and after">
<template v-for="panel in panels" :key="panel.slot" #[panel.slot]>
<div :class="`${frame} ${panel.tone}`">
<span :class="sun"></span>
<svg
:class="hills"
viewBox="0 0 480 180"
preserveAspectRatio="none"
aria-hidden="true"
>
<path
:class="far"
d="M0 90 70 40l70 45 80-55 90 65 80-50 90 35v100H0Z"
/>
<path
:class="near"
d="M0 130c80-30 150-10 230-25s170 15 250-5v80H0Z"
/>
<path :class="lake" d="M0 160c120-12 360-12 480 0v20H0Z" />
</svg>
</div>
</template>
</ImageCompare>
</template><script lang="ts">
import ImageCompare from "$lib/components/markas/ImageCompare.svelte";
const frame =
"relative aspect-[8/5] w-full overflow-hidden bg-linear-to-b from-warning/35 via-warning/10 to-success/20";
const sun = "absolute top-8 right-20 size-14 rounded-full bg-warning";
const hills = "absolute inset-x-0 bottom-0 h-3/5 w-full";
const far = "fill-success/50";
const near = "fill-success";
const lake = "fill-surface/50";
</script>
<!-- One deterministic landscape, toned flat (before) or vivid (after). -->
{#snippet scene(tone: string)}
<div class={`${frame} ${tone}`}>
<span class={sun}></span>
<svg
class={hills}
viewBox="0 0 480 180"
preserveAspectRatio="none"
aria-hidden="true"
>
<path class={far} d="M0 90 70 40l70 45 80-55 90 65 80-50 90 35v100H0Z" />
<path class={near} d="M0 130c80-30 150-10 230-25s170 15 250-5v80H0Z" />
<path class={lake} d="M0 160c120-12 360-12 480 0v20H0Z" />
</svg>
</div>
{/snippet}
<ImageCompare aria-label="Photo edit, before and after">
{#snippet before()}{@render scene("grayscale contrast-75")}{/snippet}
{#snippet after()}{@render scene("saturate-150")}{/snippet}
</ImageCompare>---
import ImageCompare from "@/components/markas/ImageCompare.astro";
const frame =
"relative aspect-[8/5] w-full overflow-hidden bg-linear-to-b from-warning/35 via-warning/10 to-success/20";
const sun = "absolute top-8 right-20 size-14 rounded-full bg-warning";
const hills = "absolute inset-x-0 bottom-0 h-3/5 w-full";
const far = "fill-success/50";
const near = "fill-success";
const lake = "fill-surface/50";
/** One deterministic landscape, toned flat (before) or vivid (after). */
const panels = [
{ slot: "before", tone: "grayscale contrast-75" },
{ slot: "after", tone: "saturate-150" },
];
---
<ImageCompare aria-label="Photo edit, before and after">
{
panels.map((panel) => (
<div slot={panel.slot} class={`${frame} ${panel.tone}`}>
<span class={sun}></span>
<svg
class={hills}
viewBox="0 0 480 180"
preserveAspectRatio="none"
aria-hidden="true"
>
<path class={far} d="M0 90 70 40l70 45 80-55 90 65 80-50 90 35v100H0Z"></path>
<path class={near} d="M0 130c80-30 150-10 230-25s170 15 250-5v80H0Z"></path>
<path class={lake} d="M0 160c120-12 360-12 480 0v20H0Z"></path>
</svg>
</div>
))
}
</ImageCompare>import { Component } from "@angular/core";
import { ImageCompare } from "./markas/image-compare.component";
@Component({
selector: "markas-example",
imports: [ImageCompare],
template: `
<!-- One deterministic landscape, toned flat (before) or vivid (after). -->
<markas-image-compare aria-label="Photo edit, before and after">
<div before [class]="frame + ' contrast-75 grayscale'">
<span [class]="sun"></span>
<svg
[class]="hills"
viewBox="0 0 480 180"
preserveAspectRatio="none"
aria-hidden="true"
>
<path
[class]="far"
d="M0 90 70 40l70 45 80-55 90 65 80-50 90 35v100H0Z"
/>
<path
[class]="near"
d="M0 130c80-30 150-10 230-25s170 15 250-5v80H0Z"
/>
<path [class]="lake" d="M0 160c120-12 360-12 480 0v20H0Z" />
</svg>
</div>
<div after [class]="frame + ' saturate-150'">
<span [class]="sun"></span>
<svg
[class]="hills"
viewBox="0 0 480 180"
preserveAspectRatio="none"
aria-hidden="true"
>
<path
[class]="far"
d="M0 90 70 40l70 45 80-55 90 65 80-50 90 35v100H0Z"
/>
<path
[class]="near"
d="M0 130c80-30 150-10 230-25s170 15 250-5v80H0Z"
/>
<path [class]="lake" d="M0 160c120-12 360-12 480 0v20H0Z" />
</svg>
</div>
</markas-image-compare>
`,
})
export default class ImageCompareExample {
protected readonly frame =
"relative aspect-[8/5] w-full overflow-hidden bg-linear-to-b from-warning/35 via-warning/10 to-success/20";
protected readonly sun =
"absolute top-8 right-20 size-14 rounded-full bg-warning";
protected readonly hills = "absolute inset-x-0 bottom-0 h-3/5 w-full";
protected readonly far = "fill-success/50";
protected readonly near = "fill-success";
protected readonly lake = "fill-surface/50";
}Contoh
Desain ulang
Revenue this month
$48,210 +12%
Revenue: 48210 USD
Revenue this month
$48,210 +12%
Revenue: 48210 USD
Revenue this month
$48,210 +12%
Revenue: 48210 USD
Revenue this month
$48,210 +12%
Revenue: 48210 USD
Revenue this month
$48,210 +12%
Revenue: 48210 USD
@php
$oldPanel = 'grid h-60 content-start gap-3 bg-subtle px-5 pt-14';
$oldText = 'text-sm text-muted';
$oldCards = 'grid grid-cols-3 gap-2';
$oldCard = 'h-12 border border-line bg-surface';
$oldChart = 'flex h-16 items-end gap-1';
$oldBar = 'w-6 bg-faint/40';
$newPanel = 'grid h-60 content-start gap-5 bg-surface px-5 pt-14';
$newHeader = 'flex items-baseline justify-between gap-4';
$newLabel = 'text-sm text-muted';
$newValue = 'flex items-baseline gap-2 text-2xl font-semibold text-ink';
$newBadge = 'text-sm font-medium text-success';
$newChart = 'flex h-20 items-end gap-2';
$newBar = 'flex-1 rounded-t-md bg-primary/80';
$newLast = 'flex-1 rounded-t-md bg-success';
$bars = ['h-[40%]', 'h-[65%]', 'h-[50%]', 'h-[80%]', 'h-[60%]', 'h-[90%]'];
@endphp
<x-markas.image-compare aria-label="Revenue widget redesign" before-label="Old" after-label="New">
<x-slot:before>
<div class="{{ $oldPanel }}">
<p class="{{ $oldText }}">Revenue: 48210 USD</p>
<div class="{{ $oldCards }}">
<div class="{{ $oldCard }}"></div>
<div class="{{ $oldCard }}"></div>
<div class="{{ $oldCard }}"></div>
</div>
<div class="{{ $oldChart }}">
@foreach ($bars as $height)
<div class="{{ $oldBar }} {{ $height }}"></div>
@endforeach
</div>
</div>
</x-slot:before>
<x-slot:after>
<div class="{{ $newPanel }}">
<div class="{{ $newHeader }}">
<p class="{{ $newLabel }}">Revenue this month</p>
<p class="{{ $newValue }}">$48,210 <span class="{{ $newBadge }}">+12%</span></p>
</div>
<div class="{{ $newChart }}">
@foreach ($bars as $index => $height)
<div class="{{ $index === count($bars) - 1 ? $newLast : $newBar }} {{ $height }}"></div>
@endforeach
</div>
</div>
</x-slot:after>
</x-markas.image-compare>import { ImageCompare } from "@/components/markas/ImageCompare";
const oldPanel = "grid h-60 content-start gap-3 bg-subtle px-5 pt-14";
const oldText = "text-sm text-muted";
const oldCards = "grid grid-cols-3 gap-2";
const oldCard = "h-12 border border-line bg-surface";
const oldChart = "flex h-16 items-end gap-1";
const oldBar = "w-6 bg-faint/40";
const newPanel = "grid h-60 content-start gap-5 bg-surface px-5 pt-14";
const newHeader = "flex items-baseline justify-between gap-4";
const newLabel = "text-sm text-muted";
const newValue = "flex items-baseline gap-2 text-2xl font-semibold text-ink";
const newBadge = "text-sm font-medium text-success";
const newChart = "flex h-20 items-end gap-2";
const newBar = "flex-1 rounded-t-md bg-primary/80";
const newLast = "flex-1 rounded-t-md bg-success";
const bars = ["h-[40%]", "h-[65%]", "h-[50%]", "h-[80%]", "h-[60%]", "h-[90%]"];
export default function Example() {
return (
<ImageCompare
aria-label="Revenue widget redesign"
beforeLabel="Old"
afterLabel="New"
before={
<div className={oldPanel}>
<p className={oldText}>Revenue: 48210 USD</p>
<div className={oldCards}>
<div className={oldCard}></div>
<div className={oldCard}></div>
<div className={oldCard}></div>
</div>
<div className={oldChart}>
{bars.map((height) => (
<div key={height} className={`${oldBar} ${height}`}></div>
))}
</div>
</div>
}
after={
<div className={newPanel}>
<div className={newHeader}>
<p className={newLabel}>Revenue this month</p>
<p className={newValue}>
$48,210 <span className={newBadge}>+12%</span>
</p>
</div>
<div className={newChart}>
{bars.map((height, index) => (
<div
key={height}
className={`${index === bars.length - 1 ? newLast : newBar} ${height}`}
></div>
))}
</div>
</div>
}
/>
);
}<script setup lang="ts">
import ImageCompare from "@/components/markas/ImageCompare.vue";
const oldPanel = "grid h-60 content-start gap-3 bg-subtle px-5 pt-14";
const oldText = "text-sm text-muted";
const oldCards = "grid grid-cols-3 gap-2";
const oldCard = "h-12 border border-line bg-surface";
const oldChart = "flex h-16 items-end gap-1";
const oldBar = "w-6 bg-faint/40";
const newPanel = "grid h-60 content-start gap-5 bg-surface px-5 pt-14";
const newHeader = "flex items-baseline justify-between gap-4";
const newLabel = "text-sm text-muted";
const newValue = "flex items-baseline gap-2 text-2xl font-semibold text-ink";
const newBadge = "text-sm font-medium text-success";
const newChart = "flex h-20 items-end gap-2";
const newBar = "flex-1 rounded-t-md bg-primary/80";
const newLast = "flex-1 rounded-t-md bg-success";
const bars = ["h-[40%]", "h-[65%]", "h-[50%]", "h-[80%]", "h-[60%]", "h-[90%]"];
</script>
<template>
<ImageCompare
aria-label="Revenue widget redesign"
before-label="Old"
after-label="New"
>
<template #before>
<div :class="oldPanel">
<p :class="oldText">Revenue: 48210 USD</p>
<div :class="oldCards">
<div :class="oldCard"></div>
<div :class="oldCard"></div>
<div :class="oldCard"></div>
</div>
<div :class="oldChart">
<div
v-for="height in bars"
:key="height"
:class="`${oldBar} ${height}`"
></div>
</div>
</div>
</template>
<template #after>
<div :class="newPanel">
<div :class="newHeader">
<p :class="newLabel">Revenue this month</p>
<p :class="newValue">$48,210 <span :class="newBadge">+12%</span></p>
</div>
<div :class="newChart">
<div
v-for="(height, index) in bars"
:key="height"
:class="`${index === bars.length - 1 ? newLast : newBar} ${height}`"
></div>
</div>
</div>
</template>
</ImageCompare>
</template><script lang="ts">
import ImageCompare from "$lib/components/markas/ImageCompare.svelte";
const oldPanel = "grid h-60 content-start gap-3 bg-subtle px-5 pt-14";
const oldText = "text-sm text-muted";
const oldCards = "grid grid-cols-3 gap-2";
const oldCard = "h-12 border border-line bg-surface";
const oldChart = "flex h-16 items-end gap-1";
const oldBar = "w-6 bg-faint/40";
const newPanel = "grid h-60 content-start gap-5 bg-surface px-5 pt-14";
const newHeader = "flex items-baseline justify-between gap-4";
const newLabel = "text-sm text-muted";
const newValue = "flex items-baseline gap-2 text-2xl font-semibold text-ink";
const newBadge = "text-sm font-medium text-success";
const newChart = "flex h-20 items-end gap-2";
const newBar = "flex-1 rounded-t-md bg-primary/80";
const newLast = "flex-1 rounded-t-md bg-success";
const bars = [
"h-[40%]",
"h-[65%]",
"h-[50%]",
"h-[80%]",
"h-[60%]",
"h-[90%]",
];
</script>
<ImageCompare
aria-label="Revenue widget redesign"
beforeLabel="Old"
afterLabel="New"
>
{#snippet before()}
<div class={oldPanel}>
<p class={oldText}>Revenue: 48210 USD</p>
<div class={oldCards}>
<div class={oldCard}></div>
<div class={oldCard}></div>
<div class={oldCard}></div>
</div>
<div class={oldChart}>
{#each bars as height (height)}<div
class={`${oldBar} ${height}`}
></div>{/each}
</div>
</div>
{/snippet}
{#snippet after()}
<div class={newPanel}>
<div class={newHeader}>
<p class={newLabel}>Revenue this month</p>
<p class={newValue}>$48,210 <span class={newBadge}>+12%</span></p>
</div>
<div class={newChart}>
{#each bars as height, index (height)}<div
class={`${index === bars.length - 1 ? newLast : newBar} ${height}`}
></div>{/each}
</div>
</div>
{/snippet}
</ImageCompare>---
import ImageCompare from "@/components/markas/ImageCompare.astro";
const oldPanel = "grid h-60 content-start gap-3 bg-subtle px-5 pt-14";
const oldText = "text-sm text-muted";
const oldCards = "grid grid-cols-3 gap-2";
const oldCard = "h-12 border border-line bg-surface";
const oldChart = "flex h-16 items-end gap-1";
const oldBar = "w-6 bg-faint/40";
const newPanel = "grid h-60 content-start gap-5 bg-surface px-5 pt-14";
const newHeader = "flex items-baseline justify-between gap-4";
const newLabel = "text-sm text-muted";
const newValue = "flex items-baseline gap-2 text-2xl font-semibold text-ink";
const newBadge = "text-sm font-medium text-success";
const newChart = "flex h-20 items-end gap-2";
const newBar = "flex-1 rounded-t-md bg-primary/80";
const newLast = "flex-1 rounded-t-md bg-success";
const bars = ["h-[40%]", "h-[65%]", "h-[50%]", "h-[80%]", "h-[60%]", "h-[90%]"];
---
<ImageCompare aria-label="Revenue widget redesign" beforeLabel="Old" afterLabel="New">
<Fragment slot="before">
<div class={oldPanel}>
<p class={oldText}>Revenue: 48210 USD</p>
<div class={oldCards}>
<div class={oldCard}></div>
<div class={oldCard}></div>
<div class={oldCard}></div>
</div>
<div class={oldChart}>
{bars.map((height) => (<div class={`${oldBar} ${height}`}></div>))}
</div>
</div>
</Fragment>
<Fragment slot="after">
<div class={newPanel}>
<div class={newHeader}>
<p class={newLabel}>Revenue this month</p>
<p class={newValue}>$48,210 <span class={newBadge}>+12%</span></p>
</div>
<div class={newChart}>
{bars.map((height, index) => (<div class={`${index === bars.length - 1 ? newLast : newBar} ${height}`}></div>))}
</div>
</div>
</Fragment>
</ImageCompare>import { Component } from "@angular/core";
import { ImageCompare } from "./markas/image-compare.component";
@Component({
selector: "markas-example",
imports: [ImageCompare],
template: `
<markas-image-compare
aria-label="Revenue widget redesign"
beforeLabel="Old"
afterLabel="New"
>
<ng-container before>
<div [class]="oldPanel">
<p [class]="oldText">Revenue: 48210 USD</p>
<div [class]="oldCards">
<div [class]="oldCard"></div>
<div [class]="oldCard"></div>
<div [class]="oldCard"></div>
</div>
<div [class]="oldChart">
@for (height of bars; track height) {
<div [class]="\`\${oldBar} \${height}\`"></div>
}
</div>
</div>
</ng-container>
<ng-container after>
<div [class]="newPanel">
<div [class]="newHeader">
<p [class]="newLabel">Revenue this month</p>
<p [class]="newValue">
$48,210 <span [class]="newBadge">+12%</span>
</p>
</div>
<div [class]="newChart">
@for (height of bars; track height; let index = $index) {
<div
[class]="\`\${index === bars.length - 1 ? newLast : newBar} \${height}\`"
></div>
}
</div>
</div>
</ng-container>
</markas-image-compare>
`,
})
export default class ImageCompareRedesignExample {
protected readonly oldPanel =
"grid h-60 content-start gap-3 bg-subtle px-5 pt-14";
protected readonly oldText = "text-sm text-muted";
protected readonly oldCards = "grid grid-cols-3 gap-2";
protected readonly oldCard = "h-12 border border-line bg-surface";
protected readonly oldChart = "flex h-16 items-end gap-1";
protected readonly oldBar = "w-6 bg-faint/40";
protected readonly newPanel =
"grid h-60 content-start gap-5 bg-surface px-5 pt-14";
protected readonly newHeader = "flex items-baseline justify-between gap-4";
protected readonly newLabel = "text-sm text-muted";
protected readonly newValue =
"flex items-baseline gap-2 text-2xl font-semibold text-ink";
protected readonly newBadge = "text-sm font-medium text-success";
protected readonly newChart = "flex h-20 items-end gap-2";
protected readonly newBar = "flex-1 rounded-t-md bg-primary/80";
protected readonly newLast = "flex-1 rounded-t-md bg-success";
protected readonly bars = [
"h-[40%]",
"h-[65%]",
"h-[50%]",
"h-[80%]",
"h-[60%]",
"h-[90%]",
];
}Pembagian vertikal
Ceramic pour-over
Hand glazed, holds 600 ml.
$34
Add to cartCeramic pour-over
Hand glazed, holds 600 ml.
$34
Add to cartCeramic pour-over
Hand glazed, holds 600 ml.
$34
Add to cartCeramic pour-over
Hand glazed, holds 600 ml.
$34
Add to cartCeramic pour-over
Hand glazed, holds 600 ml.
$34
Add to cart@php
$panel = 'flex h-64 items-center gap-5 bg-surface p-6';
$sketchImage = 'aspect-square w-28 shrink-0 rounded-lg border-2 border-dashed border-line';
$sketchBody = 'grid flex-1 gap-2.5';
$sketchLine = 'h-3 rounded-sm border-2 border-dashed border-line';
$sketchButton = 'mt-2 h-9 w-28 rounded-lg border-2 border-dashed border-line';
$image = 'grid aspect-square w-28 shrink-0 place-items-center rounded-lg bg-linear-to-br from-warning/40 to-danger/25 text-ink';
$icon = 'size-10';
$body = 'grid flex-1 gap-1';
$title = 'text-base font-semibold text-ink';
$text = 'text-sm text-muted';
$price = 'mt-1 text-sm font-semibold text-ink';
$button = 'mt-2 inline-flex h-9 w-28 items-center justify-center rounded-lg bg-primary text-sm font-medium text-on-primary';
@endphp
<x-markas.image-compare orientation="vertical" :position="45" aria-label="Product card, wireframe and final design" before-label="Wireframe" after-label="Final">
<x-slot:before>
<div class="{{ $panel }}">
<div class="{{ $sketchImage }}"></div>
<div class="{{ $sketchBody }}">
<div class="{{ $sketchLine }} w-3/4"></div>
<div class="{{ $sketchLine }} w-full"></div>
<div class="{{ $sketchLine }} w-1/3"></div>
<div class="{{ $sketchButton }}"></div>
</div>
</div>
</x-slot:before>
<x-slot:after>
<div class="{{ $panel }}">
<div class="{{ $image }}">
<svg class="{{ $icon }}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 8h11v6a5 5 0 0 1-5 5h-1a5 5 0 0 1-5-5zM16 10h1.5a2.5 2.5 0 0 1 0 5H16M8 2v3M11 2v3" /></svg>
</div>
<div class="{{ $body }}">
<p class="{{ $title }}">Ceramic pour-over</p>
<p class="{{ $text }}">Hand glazed, holds 600 ml.</p>
<p class="{{ $price }}">$34</p>
<span class="{{ $button }}">Add to cart</span>
</div>
</div>
</x-slot:after>
</x-markas.image-compare>import { ImageCompare } from "@/components/markas/ImageCompare";
const panel = "flex h-64 items-center gap-5 bg-surface p-6";
const sketchImage =
"aspect-square w-28 shrink-0 rounded-lg border-2 border-dashed border-line";
const sketchBody = "grid flex-1 gap-2.5";
const sketchLine = "h-3 rounded-sm border-2 border-dashed border-line";
const sketchButton =
"mt-2 h-9 w-28 rounded-lg border-2 border-dashed border-line";
const image =
"grid aspect-square w-28 shrink-0 place-items-center rounded-lg bg-linear-to-br from-warning/40 to-danger/25 text-ink";
const icon = "size-10";
const body = "grid flex-1 gap-1";
const title = "text-base font-semibold text-ink";
const text = "text-sm text-muted";
const price = "mt-1 text-sm font-semibold text-ink";
const button =
"mt-2 inline-flex h-9 w-28 items-center justify-center rounded-lg bg-primary text-sm font-medium text-on-primary";
export default function Example() {
return (
<ImageCompare
orientation="vertical"
defaultPosition={45}
aria-label="Product card, wireframe and final design"
beforeLabel="Wireframe"
afterLabel="Final"
before={
<div className={panel}>
<div className={sketchImage}></div>
<div className={sketchBody}>
<div className={`${sketchLine} w-3/4`}></div>
<div className={`${sketchLine} w-full`}></div>
<div className={`${sketchLine} w-1/3`}></div>
<div className={sketchButton}></div>
</div>
</div>
}
after={
<div className={panel}>
<div className={image}>
<svg
className={icon}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
<path d="M5 8h11v6a5 5 0 0 1-5 5h-1a5 5 0 0 1-5-5zM16 10h1.5a2.5 2.5 0 0 1 0 5H16M8 2v3M11 2v3" />
</svg>
</div>
<div className={body}>
<p className={title}>Ceramic pour-over</p>
<p className={text}>Hand glazed, holds 600 ml.</p>
<p className={price}>$34</p>
<span className={button}>Add to cart</span>
</div>
</div>
}
/>
);
}<script setup lang="ts">
import ImageCompare from "@/components/markas/ImageCompare.vue";
const panel = "flex h-64 items-center gap-5 bg-surface p-6";
const sketchImage =
"aspect-square w-28 shrink-0 rounded-lg border-2 border-dashed border-line";
const sketchBody = "grid flex-1 gap-2.5";
const sketchLine = "h-3 rounded-sm border-2 border-dashed border-line";
const sketchButton =
"mt-2 h-9 w-28 rounded-lg border-2 border-dashed border-line";
const image =
"grid aspect-square w-28 shrink-0 place-items-center rounded-lg bg-linear-to-br from-warning/40 to-danger/25 text-ink";
const icon = "size-10";
const body = "grid flex-1 gap-1";
const title = "text-base font-semibold text-ink";
const text = "text-sm text-muted";
const price = "mt-1 text-sm font-semibold text-ink";
const button =
"mt-2 inline-flex h-9 w-28 items-center justify-center rounded-lg bg-primary text-sm font-medium text-on-primary";
</script>
<template>
<ImageCompare
orientation="vertical"
:position="45"
aria-label="Product card, wireframe and final design"
before-label="Wireframe"
after-label="Final"
>
<template #before>
<div :class="panel">
<div :class="sketchImage"></div>
<div :class="sketchBody">
<div :class="`${sketchLine} w-3/4`"></div>
<div :class="`${sketchLine} w-full`"></div>
<div :class="`${sketchLine} w-1/3`"></div>
<div :class="sketchButton"></div>
</div>
</div>
</template>
<template #after>
<div :class="panel">
<div :class="image">
<svg
:class="icon"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path
d="M5 8h11v6a5 5 0 0 1-5 5h-1a5 5 0 0 1-5-5zM16 10h1.5a2.5 2.5 0 0 1 0 5H16M8 2v3M11 2v3"
/>
</svg>
</div>
<div :class="body">
<p :class="title">Ceramic pour-over</p>
<p :class="text">Hand glazed, holds 600 ml.</p>
<p :class="price">$34</p>
<span :class="button">Add to cart</span>
</div>
</div>
</template>
</ImageCompare>
</template><script lang="ts">
import ImageCompare from "$lib/components/markas/ImageCompare.svelte";
const panel = "flex h-64 items-center gap-5 bg-surface p-6";
const sketchImage =
"aspect-square w-28 shrink-0 rounded-lg border-2 border-dashed border-line";
const sketchBody = "grid flex-1 gap-2.5";
const sketchLine = "h-3 rounded-sm border-2 border-dashed border-line";
const sketchButton =
"mt-2 h-9 w-28 rounded-lg border-2 border-dashed border-line";
const image =
"grid aspect-square w-28 shrink-0 place-items-center rounded-lg bg-linear-to-br from-warning/40 to-danger/25 text-ink";
const icon = "size-10";
const body = "grid flex-1 gap-1";
const title = "text-base font-semibold text-ink";
const text = "text-sm text-muted";
const price = "mt-1 text-sm font-semibold text-ink";
const button =
"mt-2 inline-flex h-9 w-28 items-center justify-center rounded-lg bg-primary text-sm font-medium text-on-primary";
</script>
<ImageCompare
orientation="vertical"
position={45}
aria-label="Product card, wireframe and final design"
beforeLabel="Wireframe"
afterLabel="Final"
>
{#snippet before()}
<div class={panel}>
<div class={sketchImage}></div>
<div class={sketchBody}>
<div class={`${sketchLine} w-3/4`}></div>
<div class={`${sketchLine} w-full`}></div>
<div class={`${sketchLine} w-1/3`}></div>
<div class={sketchButton}></div>
</div>
</div>
{/snippet}
{#snippet after()}
<div class={panel}>
<div class={image}>
<svg
class={icon}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path
d="M5 8h11v6a5 5 0 0 1-5 5h-1a5 5 0 0 1-5-5zM16 10h1.5a2.5 2.5 0 0 1 0 5H16M8 2v3M11 2v3"
/>
</svg>
</div>
<div class={body}>
<p class={title}>Ceramic pour-over</p>
<p class={text}>Hand glazed, holds 600 ml.</p>
<p class={price}>$34</p>
<span class={button}>Add to cart</span>
</div>
</div>
{/snippet}
</ImageCompare>---
import ImageCompare from "@/components/markas/ImageCompare.astro";
const panel = "flex h-64 items-center gap-5 bg-surface p-6";
const sketchImage =
"aspect-square w-28 shrink-0 rounded-lg border-2 border-dashed border-line";
const sketchBody = "grid flex-1 gap-2.5";
const sketchLine = "h-3 rounded-sm border-2 border-dashed border-line";
const sketchButton =
"mt-2 h-9 w-28 rounded-lg border-2 border-dashed border-line";
const image =
"grid aspect-square w-28 shrink-0 place-items-center rounded-lg bg-linear-to-br from-warning/40 to-danger/25 text-ink";
const icon = "size-10";
const body = "grid flex-1 gap-1";
const title = "text-base font-semibold text-ink";
const text = "text-sm text-muted";
const price = "mt-1 text-sm font-semibold text-ink";
const button =
"mt-2 inline-flex h-9 w-28 items-center justify-center rounded-lg bg-primary text-sm font-medium text-on-primary";
---
<ImageCompare orientation="vertical" position={45} aria-label="Product card, wireframe and final design" beforeLabel="Wireframe" afterLabel="Final">
<Fragment slot="before">
<div class={panel}>
<div class={sketchImage}></div>
<div class={sketchBody}>
<div class={`${sketchLine} w-3/4`}></div>
<div class={`${sketchLine} w-full`}></div>
<div class={`${sketchLine} w-1/3`}></div>
<div class={sketchButton}></div>
</div>
</div>
</Fragment>
<Fragment slot="after">
<div class={panel}>
<div class={image}>
<svg class={icon} viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M5 8h11v6a5 5 0 0 1-5 5h-1a5 5 0 0 1-5-5zM16 10h1.5a2.5 2.5 0 0 1 0 5H16M8 2v3M11 2v3" />
</svg>
</div>
<div class={body}>
<p class={title}>Ceramic pour-over</p>
<p class={text}>Hand glazed, holds 600 ml.</p>
<p class={price}>$34</p>
<span class={button}>Add to cart</span>
</div>
</div>
</Fragment>
</ImageCompare>import { Component } from "@angular/core";
import { ImageCompare } from "./markas/image-compare.component";
@Component({
selector: "markas-example",
imports: [ImageCompare],
template: `
<markas-image-compare
orientation="vertical"
[position]="45"
aria-label="Product card, wireframe and final design"
beforeLabel="Wireframe"
afterLabel="Final"
>
<ng-container before>
<div [class]="panel">
<div [class]="sketchImage"></div>
<div [class]="sketchBody">
<div [class]="\`\${sketchLine} w-3/4\`"></div>
<div [class]="\`\${sketchLine} w-full\`"></div>
<div [class]="\`\${sketchLine} w-1/3\`"></div>
<div [class]="sketchButton"></div>
</div>
</div>
</ng-container>
<ng-container after>
<div [class]="panel">
<div [class]="image">
<svg
[class]="icon"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path
d="M5 8h11v6a5 5 0 0 1-5 5h-1a5 5 0 0 1-5-5zM16 10h1.5a2.5 2.5 0 0 1 0 5H16M8 2v3M11 2v3"
/>
</svg>
</div>
<div [class]="body">
<p [class]="title">Ceramic pour-over</p>
<p [class]="text">Hand glazed, holds 600 ml.</p>
<p [class]="price">$34</p>
<span [class]="button">Add to cart</span>
</div>
</div>
</ng-container>
</markas-image-compare>
`,
})
export default class ImageCompareVerticalExample {
protected readonly panel = "flex h-64 items-center gap-5 bg-surface p-6";
protected readonly sketchImage =
"aspect-square w-28 shrink-0 rounded-lg border-2 border-dashed border-line";
protected readonly sketchBody = "grid flex-1 gap-2.5";
protected readonly sketchLine =
"h-3 rounded-sm border-2 border-dashed border-line";
protected readonly sketchButton =
"mt-2 h-9 w-28 rounded-lg border-2 border-dashed border-line";
protected readonly image =
"grid aspect-square w-28 shrink-0 place-items-center rounded-lg bg-linear-to-br from-warning/40 to-danger/25 text-ink";
protected readonly icon = "size-10";
protected readonly body = "grid flex-1 gap-1";
protected readonly title = "text-base font-semibold text-ink";
protected readonly text = "text-sm text-muted";
protected readonly price = "mt-1 text-sm font-semibold text-ink";
protected readonly button =
"mt-2 inline-flex h-9 w-28 items-center justify-center rounded-lg bg-primary text-sm font-medium text-on-primary";
}Retus foto dengan keterangan
@php
$figure = 'grid gap-2';
$caption = 'text-sm text-muted';
$frame = 'relative grid aspect-[3/2] w-full place-items-center bg-linear-to-br from-primary-soft via-surface to-warning/25';
$shadow = 'absolute bottom-7 h-3 w-28 rounded-full bg-ink/15 blur-sm';
$bottle = 'relative mt-6 h-40 w-20 rounded-t-[2.5rem] rounded-b-2xl bg-linear-to-b from-success/70 to-success';
$cap = 'absolute -top-5 left-1/2 h-6 w-8 -translate-x-1/2 rounded-md bg-ink';
$label = 'absolute inset-x-2 top-14 rounded-md bg-surface/90 py-2.5 text-center text-xs font-semibold text-ink';
// One deterministic product shot, flat and soft (before) or crisp (after).
$shots = ['before' => 'blur-[1.5px] brightness-90 grayscale-[0.6]', 'after' => ''];
@endphp
<figure class="{{ $figure }}">
<x-markas.image-compare aria-label="Product photo, original and retouched" before-label="Original" after-label="Retouched">
@foreach ($shots as $side => $tone)
<x-slot :name="$side">
<div class="{{ $frame }} {{ $tone }}">
<span class="{{ $shadow }}"></span>
<div class="{{ $bottle }}">
<span class="{{ $cap }}"></span>
<span class="{{ $label }}">Calm</span>
</div>
</div>
</x-slot>
@endforeach
</x-markas.image-compare>
<figcaption class="{{ $caption }}">Drag the handle to compare the studio retouch.</figcaption>
</figure>import { ImageCompare } from "@/components/markas/ImageCompare";
const figure = "grid gap-2";
const caption = "text-sm text-muted";
const frame =
"relative grid aspect-[3/2] w-full place-items-center bg-linear-to-br from-primary-soft via-surface to-warning/25";
const shadow = "absolute bottom-7 h-3 w-28 rounded-full bg-ink/15 blur-sm";
const bottle =
"relative mt-6 h-40 w-20 rounded-t-[2.5rem] rounded-b-2xl bg-linear-to-b from-success/70 to-success";
const cap =
"absolute -top-5 left-1/2 h-6 w-8 -translate-x-1/2 rounded-md bg-ink";
const label =
"absolute inset-x-2 top-14 rounded-md bg-surface/90 py-2.5 text-center text-xs font-semibold text-ink";
/** One deterministic product shot, flat and soft (before) or crisp (after). */
const shot = (tone: string) => (
<div className={`${frame} ${tone}`}>
<span className={shadow}></span>
<div className={bottle}>
<span className={cap}></span>
<span className={label}>Calm</span>
</div>
</div>
);
export default function Example() {
return (
<figure className={figure}>
<ImageCompare
aria-label="Product photo, original and retouched"
beforeLabel="Original"
afterLabel="Retouched"
before={shot("blur-[1.5px] brightness-90 grayscale-[0.6]")}
after={shot("")}
/>
<figcaption className={caption}>
Drag the handle to compare the studio retouch.
</figcaption>
</figure>
);
}<script setup lang="ts">
import ImageCompare from "@/components/markas/ImageCompare.vue";
const figure = "grid gap-2";
const caption = "text-sm text-muted";
const frame =
"relative grid aspect-[3/2] w-full place-items-center bg-linear-to-br from-primary-soft via-surface to-warning/25";
const shadow = "absolute bottom-7 h-3 w-28 rounded-full bg-ink/15 blur-sm";
const bottle =
"relative mt-6 h-40 w-20 rounded-t-[2.5rem] rounded-b-2xl bg-linear-to-b from-success/70 to-success";
const cap =
"absolute -top-5 left-1/2 h-6 w-8 -translate-x-1/2 rounded-md bg-ink";
const label =
"absolute inset-x-2 top-14 rounded-md bg-surface/90 py-2.5 text-center text-xs font-semibold text-ink";
/** One deterministic product shot, flat and soft (before) or crisp (after). */
const shots = [
{ slot: "before", tone: "blur-[1.5px] brightness-90 grayscale-[0.6]" },
{ slot: "after", tone: "" },
] as const;
</script>
<template>
<figure :class="figure">
<ImageCompare
aria-label="Product photo, original and retouched"
before-label="Original"
after-label="Retouched"
>
<template v-for="shot in shots" :key="shot.slot" #[shot.slot]>
<div :class="`${frame} ${shot.tone}`">
<span :class="shadow"></span>
<div :class="bottle">
<span :class="cap"></span>
<span :class="label">Calm</span>
</div>
</div>
</template>
</ImageCompare>
<figcaption :class="caption">
Drag the handle to compare the studio retouch.
</figcaption>
</figure>
</template><script lang="ts">
import ImageCompare from "$lib/components/markas/ImageCompare.svelte";
const figure = "grid gap-2";
const caption = "text-sm text-muted";
const frame =
"relative grid aspect-[3/2] w-full place-items-center bg-linear-to-br from-primary-soft via-surface to-warning/25";
const shadow = "absolute bottom-7 h-3 w-28 rounded-full bg-ink/15 blur-sm";
const bottle =
"relative mt-6 h-40 w-20 rounded-t-[2.5rem] rounded-b-2xl bg-linear-to-b from-success/70 to-success";
const cap =
"absolute -top-5 left-1/2 h-6 w-8 -translate-x-1/2 rounded-md bg-ink";
const label =
"absolute inset-x-2 top-14 rounded-md bg-surface/90 py-2.5 text-center text-xs font-semibold text-ink";
</script>
<!-- One deterministic product shot, flat and soft (before) or crisp (after). -->
{#snippet shot(tone: string)}
<div class={`${frame} ${tone}`}>
<span class={shadow}></span>
<div class={bottle}>
<span class={cap}></span>
<span class={label}>Calm</span>
</div>
</div>
{/snippet}
<figure class={figure}>
<ImageCompare
aria-label="Product photo, original and retouched"
beforeLabel="Original"
afterLabel="Retouched"
>
{#snippet before()}{@render shot(
"blur-[1.5px] brightness-90 grayscale-[0.6]",
)}{/snippet}
{#snippet after()}{@render shot("")}{/snippet}
</ImageCompare>
<figcaption class={caption}>
Drag the handle to compare the studio retouch.
</figcaption>
</figure>---
import ImageCompare from "@/components/markas/ImageCompare.astro";
const figure = "grid gap-2";
const caption = "text-sm text-muted";
const frame =
"relative grid aspect-[3/2] w-full place-items-center bg-linear-to-br from-primary-soft via-surface to-warning/25";
const shadow = "absolute bottom-7 h-3 w-28 rounded-full bg-ink/15 blur-sm";
const bottle =
"relative mt-6 h-40 w-20 rounded-t-[2.5rem] rounded-b-2xl bg-linear-to-b from-success/70 to-success";
const cap =
"absolute -top-5 left-1/2 h-6 w-8 -translate-x-1/2 rounded-md bg-ink";
const label =
"absolute inset-x-2 top-14 rounded-md bg-surface/90 py-2.5 text-center text-xs font-semibold text-ink";
/** One deterministic product shot, flat and soft (before) or crisp (after). */
const shots = [
{ slot: "before", tone: "blur-[1.5px] brightness-90 grayscale-[0.6]" },
{ slot: "after", tone: "" },
];
---
<figure class={figure}>
<ImageCompare
aria-label="Product photo, original and retouched"
beforeLabel="Original"
afterLabel="Retouched"
>
{
shots.map((shot) => (
<div slot={shot.slot} class={`${frame} ${shot.tone}`}>
<span class={shadow}></span>
<div class={bottle}>
<span class={cap}></span>
<span class={label}>Calm</span>
</div>
</div>
))
}
</ImageCompare>
<figcaption class={caption}>
Drag the handle to compare the studio retouch.
</figcaption>
</figure>import { Component } from "@angular/core";
import { ImageCompare } from "./markas/image-compare.component";
@Component({
selector: "markas-example",
imports: [ImageCompare],
template: `
<figure [class]="figure">
<markas-image-compare
aria-label="Product photo, original and retouched"
beforeLabel="Original"
afterLabel="Retouched"
>
<!-- One deterministic product shot, flat and soft (before) or crisp (after). -->
<div
before
[class]="frame + ' blur-[1.5px] brightness-90 grayscale-[0.6]'"
>
<span [class]="shadow"></span>
<div [class]="bottle">
<span [class]="cap"></span>
<span [class]="label">Calm</span>
</div>
</div>
<div after [class]="frame + ' '">
<span [class]="shadow"></span>
<div [class]="bottle">
<span [class]="cap"></span>
<span [class]="label">Calm</span>
</div>
</div>
</markas-image-compare>
<figcaption [class]="caption">
Drag the handle to compare the studio retouch.
</figcaption>
</figure>
`,
})
export default class ImageCompareRetouchExample {
protected readonly figure = "grid gap-2";
protected readonly caption = "text-sm text-muted";
protected readonly frame =
"relative grid aspect-[3/2] w-full place-items-center bg-linear-to-br from-primary-soft via-surface to-warning/25";
protected readonly shadow =
"absolute bottom-7 h-3 w-28 rounded-full bg-ink/15 blur-sm";
protected readonly bottle =
"relative mt-6 h-40 w-20 rounded-t-[2.5rem] rounded-b-2xl bg-linear-to-b from-success/70 to-success";
protected readonly cap =
"absolute -top-5 left-1/2 h-6 w-8 -translate-x-1/2 rounded-md bg-ink";
protected readonly label =
"absolute inset-x-2 top-14 rounded-md bg-surface/90 py-2.5 text-center text-xs font-semibold text-ink";
}Instalasi
npx markasui@latest add image-comparepnpm dlx markasui@latest add image-compareyarn dlx markasui@latest add image-comparebunx --bun markasui@latest add image-compare- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Pasang dependensi:
npm install alpinejs - Salin source komponen di bawah ini ke
resources/views/components/markas/image-compare.blade.php.
@props([
'orientation' => 'horizontal',
'position' => 50,
'step' => 5,
'beforeLabel' => 'Before',
'afterLabel' => 'After',
'sliderLabel' => 'Comparison position',
])
@php
$root = 'group/compare relative isolate grid overflow-hidden rounded-xl select-none [&_img]:pointer-events-none';
$layer = 'relative col-start-1 row-start-1 min-w-0 bg-surface';
$motion = 'duration-200 ease-out group-data-dragging/compare:transition-none motion-reduce:transition-none';
$label = 'pointer-events-none absolute rounded-full border border-line bg-surface/85 px-2.5 py-1 text-xs font-medium text-ink backdrop-blur-sm';
$divider = 'pointer-events-none absolute z-10 bg-surface';
$handle = 'pointer-events-auto absolute top-1/2 left-1/2 grid size-10 -translate-1/2 place-items-center rounded-full border border-line bg-surface text-ink shadow-overlay transition-[scale] duration-150 ease-out group-data-dragging/compare:scale-110 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none';
$iconClass = 'size-5';
$orientations = [
'horizontal' => [
'root' => 'cursor-ew-resize touch-pan-y',
'clip' => '[clip-path:inset(0_calc(100%_-_var(--position))_0_0)] transition-[clip-path]',
'divider' => 'inset-y-0 left-(--position) w-0.5 -translate-x-1/2 transition-[left]',
'before' => 'top-3 left-3',
'after' => 'top-3 right-3',
'icon' => '',
],
'vertical' => [
'root' => 'cursor-ns-resize touch-pan-x',
'clip' => '[clip-path:inset(0_0_calc(100%_-_var(--position))_0)] transition-[clip-path]',
'divider' => 'inset-x-0 top-(--position) h-0.5 -translate-y-1/2 transition-[top]',
'before' => 'top-3 left-3',
'after' => 'bottom-3 left-3',
'icon' => 'rotate-90',
],
];
$o = $orientations[$orientation] ?? $orientations['horizontal'];
$orientation = isset($orientations[$orientation]) ? $orientation : 'horizontal';
$position = min(100, max(0, (float) $position));
$cx = fn (string ...$classes) => implode(' ', array_filter($classes));
@endphp
{{-- Drag anywhere, click a spot, or use the arrow keys, Page Up/Down, Home, and End on the handle. --}}
<div
x-data="{
position: {{ $position }},
step: {{ (float) $step }},
vertical: {{ $orientation === 'vertical' ? 'true' : 'false' }},
pressed: false,
dragging: false,
move(next) {
this.position = Math.min(100, Math.max(0, next));
this.$dispatch('position-change', this.position);
},
fromPointer(event) {
const rect = this.$root.getBoundingClientRect();
this.move(this.vertical ? ((event.clientY - rect.top) / rect.height) * 100 : ((event.clientX - rect.left) / rect.width) * 100);
},
down(event) {
if (event.button !== 0) return;
event.preventDefault();
this.pressed = true;
this.$refs.handle.focus({ preventScroll: true });
this.$root.setPointerCapture?.(event.pointerId);
this.fromPointer(event);
},
drag(event) {
if (! this.pressed) return;
this.dragging = true;
this.fromPointer(event);
},
release() {
this.pressed = false;
this.dragging = false;
},
key(event) {
const flip = this.vertical ? -1 : 1;
const at = this.position;
const moves = { ArrowRight: at + this.step, ArrowLeft: at - this.step, ArrowUp: at + this.step * flip, ArrowDown: at - this.step * flip, PageUp: at + 10, PageDown: at - 10, Home: 0, End: 100 };
const next = moves[event.key];
if (next === undefined) return;
event.preventDefault();
this.move(next);
},
}"
data-orientation="{{ $orientation }}"
x-bind:data-dragging="dragging ? '' : null"
x-bind:style="{ '--position': position + '%' }"
x-on:pointerdown="down($event)"
x-on:pointermove="drag($event)"
x-on:pointerup="release()"
x-on:pointercancel="release()"
{{ $attributes->merge(['role' => 'group', 'style' => '--position: '.$position.'%'])->class([$root, $o['root']]) }}
>
<div class="{{ $layer }}">
{{ $__laravel_slots['after'] ?? '' }}
<span class="{{ $cx($label, $o['after']) }}">{{ $afterLabel }}</span>
</div>
<div class="{{ $cx($layer, $o['clip'], $motion) }}">
{{ $__laravel_slots['before'] ?? '' }}
<span class="{{ $cx($label, $o['before']) }}">{{ $beforeLabel }}</span>
</div>
<div class="{{ $cx($divider, $o['divider'], $motion) }}">
<div
x-ref="handle"
role="slider"
tabindex="0"
aria-label="{{ $sliderLabel }}"
aria-orientation="{{ $orientation }}"
aria-valuemin="0"
aria-valuemax="100"
aria-valuenow="{{ round($position) }}"
aria-valuetext="{{ round($position) }}%"
x-bind:aria-valuenow="Math.round(position)"
x-bind:aria-valuetext="Math.round(position) + '%'"
x-on:keydown="key($event)"
class="{{ $handle }}"
>
<svg class="{{ $cx($iconClass, $o['icon']) }}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 7-5 5 5 5M15 7l5 5-5 5" /></svg>
</div>
</div>
</div>- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
src/components/markas/ImageCompare.tsx.
"use client";
import {
useRef,
useState,
type ComponentProps,
type CSSProperties,
type KeyboardEvent,
type PointerEvent,
type ReactNode,
} from "react";
const root =
"group/compare relative isolate grid overflow-hidden rounded-xl select-none [&_img]:pointer-events-none";
const layer = "relative col-start-1 row-start-1 min-w-0 bg-surface";
const motion =
"duration-200 ease-out group-data-dragging/compare:transition-none motion-reduce:transition-none";
const label =
"pointer-events-none absolute rounded-full border border-line bg-surface/85 px-2.5 py-1 text-xs font-medium text-ink backdrop-blur-sm";
const divider = "pointer-events-none absolute z-10 bg-surface";
const handle =
"pointer-events-auto absolute top-1/2 left-1/2 grid size-10 -translate-1/2 place-items-center rounded-full border border-line bg-surface text-ink shadow-overlay transition-[scale] duration-150 ease-out group-data-dragging/compare:scale-110 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const iconClass = "size-5";
const orientations = {
horizontal: {
root: "cursor-ew-resize touch-pan-y",
clip: "[clip-path:inset(0_calc(100%_-_var(--position))_0_0)] transition-[clip-path]",
divider:
"inset-y-0 left-(--position) w-0.5 -translate-x-1/2 transition-[left]",
before: "top-3 left-3",
after: "top-3 right-3",
icon: "",
},
vertical: {
root: "cursor-ns-resize touch-pan-x",
clip: "[clip-path:inset(0_0_calc(100%_-_var(--position))_0)] transition-[clip-path]",
divider:
"inset-x-0 top-(--position) h-0.5 -translate-y-1/2 transition-[top]",
before: "top-3 left-3",
after: "bottom-3 left-3",
icon: "rotate-90",
},
};
const PAGE_STEP = 10;
const cx = (...c: (string | false | null | undefined)[]) =>
c.filter(Boolean).join(" ");
const clamp = (value: number) => Math.min(100, Math.max(0, value));
export type ImageCompareProps = Omit<ComponentProps<"div">, "children"> & {
/** Content shown on the start side (left or top): an img, svg, or any markup. */
before: ReactNode;
/** Content shown on the end side (right or bottom). */
after: ReactNode;
orientation?: keyof typeof orientations;
/** Starting divider position in percent. */
defaultPosition?: number;
/** Percent moved per arrow key press. */
step?: number;
onPositionChange?: (position: number) => void;
beforeLabel?: string;
afterLabel?: string;
sliderLabel?: string;
};
export function ImageCompare({
before,
after,
orientation = "horizontal",
defaultPosition = 50,
step = 5,
onPositionChange,
beforeLabel = "Before",
afterLabel = "After",
sliderLabel = "Comparison position",
className,
style,
...props
}: ImageCompareProps) {
const o = orientations[orientation];
const vertical = orientation === "vertical";
const [position, setPosition] = useState(clamp(defaultPosition));
const [dragging, setDragging] = useState(false);
const pressed = useRef(false);
const handleRef = useRef<HTMLDivElement>(null);
const move = (next: number) => {
const value = clamp(next);
setPosition(value);
onPositionChange?.(value);
};
const fromPointer = (event: PointerEvent<HTMLDivElement>) => {
const rect = event.currentTarget.getBoundingClientRect();
move(
vertical
? ((event.clientY - rect.top) / rect.height) * 100
: ((event.clientX - rect.left) / rect.width) * 100,
);
};
const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {
if (event.button !== 0) return;
event.preventDefault();
pressed.current = true;
handleRef.current?.focus({ preventScroll: true });
event.currentTarget.setPointerCapture?.(event.pointerId);
fromPointer(event);
};
const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
if (!pressed.current) return;
setDragging(true);
fromPointer(event);
};
const release = () => {
pressed.current = false;
setDragging(false);
};
const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
const flip = vertical ? -1 : 1;
const moves: Record<string, number> = {
ArrowRight: position + step,
ArrowLeft: position - step,
ArrowUp: position + step * flip,
ArrowDown: position - step * flip,
PageUp: position + PAGE_STEP,
PageDown: position - PAGE_STEP,
Home: 0,
End: 100,
};
const next = moves[event.key];
if (next === undefined) return;
event.preventDefault();
move(next);
};
return (
<div
role="group"
{...props}
data-orientation={orientation}
data-dragging={dragging ? "" : undefined}
className={cx(root, o.root, className)}
style={{ ...style, "--position": `${position}%` } as CSSProperties}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={release}
onPointerCancel={release}
>
<div className={layer}>
{after}
<span className={cx(label, o.after)}>{afterLabel}</span>
</div>
<div className={cx(layer, o.clip, motion)}>
{before}
<span className={cx(label, o.before)}>{beforeLabel}</span>
</div>
<div className={cx(divider, o.divider, motion)}>
<div
ref={handleRef}
role="slider"
tabIndex={0}
aria-label={sliderLabel}
aria-orientation={orientation}
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={Math.round(position)}
aria-valuetext={`${Math.round(position)}%`}
className={handle}
onKeyDown={onKeyDown}
>
<svg
className={cx(iconClass, o.icon)}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
<path d="m9 7-5 5 5 5M15 7l5 5-5 5" />
</svg>
</div>
</div>
</div>
);
}- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
src/components/markas/ImageCompare.vue.
<script setup lang="ts">
import { computed, ref } from "vue";
const props = withDefaults(
defineProps<{
orientation?: "horizontal" | "vertical";
/** Percent moved per arrow key press. */
step?: number;
beforeLabel?: string;
afterLabel?: string;
sliderLabel?: string;
}>(),
{
orientation: "horizontal",
step: 5,
beforeLabel: "Before",
afterLabel: "After",
sliderLabel: "Comparison position",
},
);
/** Divider position in percent, measured from the start (left or top). */
const position = defineModel<number>("position", { default: 50 });
defineSlots<{ before?: () => unknown; after?: () => unknown }>();
const root =
"group/compare relative isolate grid overflow-hidden rounded-xl select-none [&_img]:pointer-events-none";
const layer = "relative col-start-1 row-start-1 min-w-0 bg-surface";
const motion =
"duration-200 ease-out group-data-dragging/compare:transition-none motion-reduce:transition-none";
const label =
"pointer-events-none absolute rounded-full border border-line bg-surface/85 px-2.5 py-1 text-xs font-medium text-ink backdrop-blur-sm";
const divider = "pointer-events-none absolute z-10 bg-surface";
const handle =
"pointer-events-auto absolute top-1/2 left-1/2 grid size-10 -translate-1/2 place-items-center rounded-full border border-line bg-surface text-ink shadow-overlay transition-[scale] duration-150 ease-out group-data-dragging/compare:scale-110 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const iconClass = "size-5";
const orientations = {
horizontal: {
root: "cursor-ew-resize touch-pan-y",
clip: "[clip-path:inset(0_calc(100%_-_var(--position))_0_0)] transition-[clip-path]",
divider:
"inset-y-0 left-(--position) w-0.5 -translate-x-1/2 transition-[left]",
before: "top-3 left-3",
after: "top-3 right-3",
icon: "",
},
vertical: {
root: "cursor-ns-resize touch-pan-x",
clip: "[clip-path:inset(0_0_calc(100%_-_var(--position))_0)] transition-[clip-path]",
divider:
"inset-x-0 top-(--position) h-0.5 -translate-y-1/2 transition-[top]",
before: "top-3 left-3",
after: "bottom-3 left-3",
icon: "rotate-90",
},
};
const PAGE_STEP = 10;
const cx = (...c: (string | false | null | undefined)[]) =>
c.filter(Boolean).join(" ");
const clamp = (value: number) => Math.min(100, Math.max(0, value));
const o = computed(() => orientations[props.orientation]);
const vertical = computed(() => props.orientation === "vertical");
const current = computed(() => clamp(position.value));
const dragging = ref(false);
const handleEl = ref<HTMLElement>();
let pressed = false;
const move = (next: number) => {
position.value = clamp(next);
};
function fromPointer(event: PointerEvent) {
const rect = (event.currentTarget as HTMLElement).getBoundingClientRect();
move(
vertical.value
? ((event.clientY - rect.top) / rect.height) * 100
: ((event.clientX - rect.left) / rect.width) * 100,
);
}
function onPointerdown(event: PointerEvent) {
if (event.button !== 0) return;
event.preventDefault();
pressed = true;
handleEl.value?.focus({ preventScroll: true });
(event.currentTarget as HTMLElement).setPointerCapture?.(event.pointerId);
fromPointer(event);
}
function onPointermove(event: PointerEvent) {
if (!pressed) return;
dragging.value = true;
fromPointer(event);
}
function release() {
pressed = false;
dragging.value = false;
}
function onKeydown(event: KeyboardEvent) {
const flip = vertical.value ? -1 : 1;
const at = current.value;
const moves: Record<string, number> = {
ArrowRight: at + props.step,
ArrowLeft: at - props.step,
ArrowUp: at + props.step * flip,
ArrowDown: at - props.step * flip,
PageUp: at + PAGE_STEP,
PageDown: at - PAGE_STEP,
Home: 0,
End: 100,
};
const next = moves[event.key];
if (next === undefined) return;
event.preventDefault();
move(next);
}
</script>
<template>
<div
role="group"
:data-orientation="props.orientation"
:data-dragging="dragging ? '' : undefined"
:class="cx(root, o.root)"
:style="{ '--position': `${current}%` }"
@pointerdown="onPointerdown"
@pointermove="onPointermove"
@pointerup="release"
@pointercancel="release"
>
<div :class="layer">
<slot name="after" />
<span :class="cx(label, o.after)">{{ props.afterLabel }}</span>
</div>
<div :class="cx(layer, o.clip, motion)">
<slot name="before" />
<span :class="cx(label, o.before)">{{ props.beforeLabel }}</span>
</div>
<div :class="cx(divider, o.divider, motion)">
<div
ref="handleEl"
role="slider"
tabindex="0"
:aria-label="props.sliderLabel"
:aria-orientation="props.orientation"
aria-valuemin="0"
aria-valuemax="100"
:aria-valuenow="Math.round(current)"
:aria-valuetext="`${Math.round(current)}%`"
:class="handle"
@keydown="onKeydown"
>
<svg
:class="cx(iconClass, o.icon)"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m9 7-5 5 5 5M15 7l5 5-5 5" />
</svg>
</div>
</div>
</div>
</template>- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
src/lib/components/markas/ImageCompare.svelte.
<script lang="ts">
import type { Snippet } from "svelte";
import type { HTMLAttributes } from "svelte/elements";
const root =
"group/compare relative isolate grid overflow-hidden rounded-xl select-none [&_img]:pointer-events-none";
const layer = "relative col-start-1 row-start-1 min-w-0 bg-surface";
const motion =
"duration-200 ease-out group-data-dragging/compare:transition-none motion-reduce:transition-none";
const label =
"pointer-events-none absolute rounded-full border border-line bg-surface/85 px-2.5 py-1 text-xs font-medium text-ink backdrop-blur-sm";
const divider = "pointer-events-none absolute z-10 bg-surface";
const handle =
"pointer-events-auto absolute top-1/2 left-1/2 grid size-10 -translate-1/2 place-items-center rounded-full border border-line bg-surface text-ink shadow-overlay transition-[scale] duration-150 ease-out group-data-dragging/compare:scale-110 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const iconClass = "size-5";
const orientations = {
horizontal: {
root: "cursor-ew-resize touch-pan-y",
clip: "[clip-path:inset(0_calc(100%_-_var(--position))_0_0)] transition-[clip-path]",
divider:
"inset-y-0 left-(--position) w-0.5 -translate-x-1/2 transition-[left]",
before: "top-3 left-3",
after: "top-3 right-3",
icon: "",
},
vertical: {
root: "cursor-ns-resize touch-pan-x",
clip: "[clip-path:inset(0_0_calc(100%_-_var(--position))_0)] transition-[clip-path]",
divider:
"inset-x-0 top-(--position) h-0.5 -translate-y-1/2 transition-[top]",
before: "top-3 left-3",
after: "bottom-3 left-3",
icon: "rotate-90",
},
};
const PAGE_STEP = 10;
const clamp = (value: number) => Math.min(100, Math.max(0, value));
type Props = Omit<HTMLAttributes<HTMLDivElement>, "children"> & {
/** Content shown on the start side (left or top): an img, svg, or any markup. */
before?: Snippet;
/** Content shown on the end side (right or bottom). */
after?: Snippet;
orientation?: keyof typeof orientations;
/** Divider position in percent, bindable with bind:position. */
position?: number;
/** Percent moved per arrow key press. */
step?: number;
onPositionChange?: (position: number) => void;
beforeLabel?: string;
afterLabel?: string;
sliderLabel?: string;
};
let {
before,
after,
orientation = "horizontal",
position = $bindable(50),
step = 5,
onPositionChange,
beforeLabel = "Before",
afterLabel = "After",
sliderLabel = "Comparison position",
class: className,
style,
...rest
}: Props = $props();
const o = $derived(orientations[orientation]);
const vertical = $derived(orientation === "vertical");
const current = $derived(clamp(position));
let dragging = $state(false);
let handleEl = $state<HTMLDivElement>();
let pressed = false;
function move(next: number) {
position = clamp(next);
onPositionChange?.(position);
}
function fromPointer(
event: PointerEvent & { currentTarget: EventTarget & HTMLDivElement },
) {
const rect = event.currentTarget.getBoundingClientRect();
move(
vertical
? ((event.clientY - rect.top) / rect.height) * 100
: ((event.clientX - rect.left) / rect.width) * 100,
);
}
function onpointerdown(
event: PointerEvent & { currentTarget: EventTarget & HTMLDivElement },
) {
if (event.button !== 0) return;
event.preventDefault();
pressed = true;
handleEl?.focus({ preventScroll: true });
event.currentTarget.setPointerCapture?.(event.pointerId);
fromPointer(event);
}
function onpointermove(
event: PointerEvent & { currentTarget: EventTarget & HTMLDivElement },
) {
if (!pressed) return;
dragging = true;
fromPointer(event);
}
function release() {
pressed = false;
dragging = false;
}
function onkeydown(event: KeyboardEvent) {
const flip = vertical ? -1 : 1;
const at = current;
const moves: Record<string, number> = {
ArrowRight: at + step,
ArrowLeft: at - step,
ArrowUp: at + step * flip,
ArrowDown: at - step * flip,
PageUp: at + PAGE_STEP,
PageDown: at - PAGE_STEP,
Home: 0,
End: 100,
};
const next = moves[event.key];
if (next === undefined) return;
event.preventDefault();
move(next);
}
</script>
<div
role="group"
{...rest}
data-orientation={orientation}
data-dragging={dragging ? "" : undefined}
class={[root, o.root, className]}
style={`${style ? `${style}; ` : ""}--position: ${current}%`}
{onpointerdown}
{onpointermove}
onpointerup={release}
onpointercancel={release}
>
<div class={layer}>
{@render after?.()}
<span class={[label, o.after]}>{afterLabel}</span>
</div>
<div class={[layer, o.clip, motion]}>
{@render before?.()}
<span class={[label, o.before]}>{beforeLabel}</span>
</div>
<div class={[divider, o.divider, motion]}>
<div
bind:this={handleEl}
role="slider"
tabindex="0"
aria-label={sliderLabel}
aria-orientation={orientation}
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={Math.round(current)}
aria-valuetext={`${Math.round(current)}%`}
class={handle}
{onkeydown}
>
<svg
class={[iconClass, o.icon]}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m9 7-5 5 5 5M15 7l5 5-5 5" />
</svg>
</div>
</div>
</div>- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
src/components/markas/ImageCompare.astro.
---
import type { HTMLAttributes } from "astro/types";
const root =
"group/compare relative isolate grid overflow-hidden rounded-xl select-none [&_img]:pointer-events-none";
const layer = "relative col-start-1 row-start-1 min-w-0 bg-surface";
const motion =
"duration-200 ease-out group-data-dragging/compare:transition-none motion-reduce:transition-none";
const label =
"pointer-events-none absolute rounded-full border border-line bg-surface/85 px-2.5 py-1 text-xs font-medium text-ink backdrop-blur-sm";
const divider = "pointer-events-none absolute z-10 bg-surface";
const handle =
"pointer-events-auto absolute top-1/2 left-1/2 grid size-10 -translate-1/2 place-items-center rounded-full border border-line bg-surface text-ink shadow-overlay transition-[scale] duration-150 ease-out group-data-dragging/compare:scale-110 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const iconClass = "size-5";
const orientations = {
horizontal: {
root: "cursor-ew-resize touch-pan-y",
clip: "[clip-path:inset(0_calc(100%_-_var(--position))_0_0)] transition-[clip-path]",
divider:
"inset-y-0 left-(--position) w-0.5 -translate-x-1/2 transition-[left]",
before: "top-3 left-3",
after: "top-3 right-3",
icon: "",
},
vertical: {
root: "cursor-ns-resize touch-pan-x",
clip: "[clip-path:inset(0_0_calc(100%_-_var(--position))_0)] transition-[clip-path]",
divider:
"inset-x-0 top-(--position) h-0.5 -translate-y-1/2 transition-[top]",
before: "top-3 left-3",
after: "bottom-3 left-3",
icon: "rotate-90",
},
};
type Props = HTMLAttributes<"div"> & {
orientation?: keyof typeof orientations;
/** Starting divider position in percent. */
position?: number;
/** Percent moved per arrow key press. */
step?: number;
beforeLabel?: string;
afterLabel?: string;
sliderLabel?: string;
};
const {
orientation = "horizontal",
position: start = 50,
step = 5,
beforeLabel = "Before",
afterLabel = "After",
sliderLabel = "Comparison position",
class: className,
style,
...rest
} = Astro.props;
const o = orientations[orientation];
const position = Math.min(100, Math.max(0, Number(start)));
const userStyle = typeof style === "string" && style ? `${style}; ` : "";
---
<div
role="group"
{...rest}
data-markas-image-compare
data-step={Number(step)}
data-orientation={orientation}
class:list={[root, o.root, className]}
style={`${userStyle}--position: ${position}%`}
>
<div class={layer}>
<slot name="after" />
<span class:list={[label, o.after]}>{afterLabel}</span>
</div>
<div class:list={[layer, o.clip, motion]}>
<slot name="before" />
<span class:list={[label, o.before]}>{beforeLabel}</span>
</div>
<div class:list={[divider, o.divider, motion]}>
<div
role="slider"
tabindex="0"
aria-label={sliderLabel}
aria-orientation={orientation}
aria-valuemin="0"
aria-valuemax="100"
aria-valuenow={Math.round(position)}
aria-valuetext={`${Math.round(position)}%`}
class={handle}
>
<svg
class:list={[iconClass, o.icon]}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m9 7-5 5 5 5M15 7l5 5-5 5"></path>
</svg>
</div>
</div>
</div>
<script>
const PAGE_STEP = 10;
const pressed = new WeakSet<HTMLElement>();
const compareOf = (target: EventTarget | null) =>
target instanceof Element
? target.closest<HTMLElement>("[data-markas-image-compare]")
: null;
const positionOf = (root: HTMLElement) =>
parseFloat(root.style.getPropertyValue("--position")) || 0;
/** Move the divider, update the slider value, and announce it with a position-change event. */
function move(root: HTMLElement, next: number) {
const value = Math.min(100, Math.max(0, next));
root.style.setProperty("--position", `${value}%`);
const slider = root.querySelector("[role=slider]");
slider?.setAttribute("aria-valuenow", String(Math.round(value)));
slider?.setAttribute("aria-valuetext", `${Math.round(value)}%`);
root.dispatchEvent(
new CustomEvent("position-change", { detail: value, bubbles: true }),
);
}
function fromPointer(root: HTMLElement, event: PointerEvent) {
const rect = root.getBoundingClientRect();
move(
root,
root.dataset.orientation === "vertical"
? ((event.clientY - rect.top) / rect.height) * 100
: ((event.clientX - rect.left) / rect.width) * 100,
);
}
function release(event: Event) {
const root = compareOf(event.target);
if (!root) return;
pressed.delete(root);
delete root.dataset.dragging;
}
// One set of listeners per page serves every comparison: drag anywhere, click a spot, or use the
// arrow keys, Page Up/Down, Home, and End on the handle.
document.addEventListener("pointerdown", (event) => {
const root = compareOf(event.target);
if (!root || event.button !== 0) return;
event.preventDefault();
pressed.add(root);
root.querySelector<HTMLElement>("[role=slider]")?.focus({
preventScroll: true,
});
root.setPointerCapture?.(event.pointerId);
fromPointer(root, event);
});
document.addEventListener("pointermove", (event) => {
const root = compareOf(event.target);
if (!root || !pressed.has(root)) return;
root.dataset.dragging = "";
fromPointer(root, event);
});
document.addEventListener("pointerup", release);
document.addEventListener("pointercancel", release);
document.addEventListener("keydown", (event) => {
const target = event.target;
const root = compareOf(target);
if (!root || !(target instanceof Element) || target.getAttribute("role") !== "slider")
return;
const step = Number(root.dataset.step) || 0;
const flip = root.dataset.orientation === "vertical" ? -1 : 1;
const at = positionOf(root);
const moves: Record<string, number> = {
ArrowRight: at + step,
ArrowLeft: at - step,
ArrowUp: at + step * flip,
ArrowDown: at - step * flip,
PageUp: at + PAGE_STEP,
PageDown: at - PAGE_STEP,
Home: 0,
End: 100,
};
const next = moves[event.key];
if (next === undefined) return;
event.preventDefault();
move(root, next);
});
</script>- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
src/app/markas/image-compare.component.ts.
import {
ChangeDetectionStrategy,
Component,
computed,
type ElementRef,
input,
linkedSignal,
numberAttribute,
output,
signal,
viewChild,
} from "@angular/core";
const root =
"group/compare relative isolate grid overflow-hidden rounded-xl select-none [&_img]:pointer-events-none";
const layer = "relative col-start-1 row-start-1 min-w-0 bg-surface";
const motion =
"duration-200 ease-out group-data-dragging/compare:transition-none motion-reduce:transition-none";
const label =
"pointer-events-none absolute rounded-full border border-line bg-surface/85 px-2.5 py-1 text-xs font-medium text-ink backdrop-blur-sm";
const divider = "pointer-events-none absolute z-10 bg-surface";
const handle =
"pointer-events-auto absolute top-1/2 left-1/2 grid size-10 -translate-1/2 place-items-center rounded-full border border-line bg-surface text-ink shadow-overlay transition-[scale] duration-150 ease-out group-data-dragging/compare:scale-110 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const iconClass = "size-5";
const orientations = {
horizontal: {
root: "cursor-ew-resize touch-pan-y",
clip: "[clip-path:inset(0_calc(100%_-_var(--position))_0_0)] transition-[clip-path]",
divider:
"inset-y-0 left-(--position) w-0.5 -translate-x-1/2 transition-[left]",
before: "top-3 left-3",
after: "top-3 right-3",
icon: "",
},
vertical: {
root: "cursor-ns-resize touch-pan-x",
clip: "[clip-path:inset(0_0_calc(100%_-_var(--position))_0)] transition-[clip-path]",
divider:
"inset-x-0 top-(--position) h-0.5 -translate-y-1/2 transition-[top]",
before: "top-3 left-3",
after: "bottom-3 left-3",
icon: "rotate-90",
},
};
const PAGE_STEP = 10;
const cx = (...c: (string | false | null | undefined)[]) =>
c.filter(Boolean).join(" ");
const clamp = (value: number) => Math.min(100, Math.max(0, value));
export type ImageCompareOrientation = keyof typeof orientations;
/**
* Slots: an element with the `before` attribute fills the start side (left or top), one with
* `after` the end side. Supports [(position)]. The host stays out of layout; the user's class
* lands on the group.
*/
@Component({
selector: "markas-image-compare",
changeDetection: ChangeDetectionStrategy.OnPush,
host: { class: "contents", "[attr.aria-label]": "null" },
template: `
<div
role="group"
[attr.aria-label]="ariaLabel()"
[attr.data-orientation]="orientation()"
[attr.data-dragging]="dragging() ? '' : null"
[class]="classes()"
[style.--position]="current() + '%'"
(pointerdown)="onPointerDown($event)"
(pointermove)="onPointerMove($event)"
(pointerup)="release()"
(pointercancel)="release()"
>
<div [class]="layer">
<ng-content select="[after]" />
<span [class]="afterClass()">{{ afterLabel() }}</span>
</div>
<div [class]="clipClass()">
<ng-content select="[before]" />
<span [class]="beforeClass()">{{ beforeLabel() }}</span>
</div>
<div [class]="dividerClass()">
<div
#handleEl
role="slider"
tabindex="0"
[attr.aria-label]="sliderLabel()"
[attr.aria-orientation]="orientation()"
aria-valuemin="0"
aria-valuemax="100"
[attr.aria-valuenow]="rounded()"
[attr.aria-valuetext]="rounded() + '%'"
[class]="handle"
(keydown)="onKeyDown($event)"
>
<svg
[class]="iconClasses()"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m9 7-5 5 5 5M15 7l5 5-5 5" />
</svg>
</div>
</div>
</div>
`,
})
export class ImageCompare {
readonly orientation = input<ImageCompareOrientation>("horizontal");
/** Divider position in percent, measured from the start (left or top). */
readonly position = input(50, { transform: numberAttribute });
/** Percent moved per arrow key press. */
readonly step = input(5, { transform: numberAttribute });
readonly beforeLabel = input("Before");
readonly afterLabel = input("After");
readonly sliderLabel = input("Comparison position");
readonly ariaLabel = input<string>(undefined, { alias: "aria-label" });
readonly userClass = input("", { alias: "class" });
readonly positionChange = output<number>();
protected readonly layer = layer;
protected readonly handle = handle;
protected readonly current = linkedSignal(() => clamp(this.position()));
protected readonly rounded = computed(() => Math.round(this.current()));
protected readonly dragging = signal(false);
private readonly o = computed(() => orientations[this.orientation()]);
protected readonly classes = computed(() =>
cx(root, this.o().root, this.userClass()),
);
protected readonly afterClass = computed(() => cx(label, this.o().after));
protected readonly beforeClass = computed(() => cx(label, this.o().before));
protected readonly clipClass = computed(() =>
cx(layer, this.o().clip, motion),
);
protected readonly dividerClass = computed(() =>
cx(divider, this.o().divider, motion),
);
protected readonly iconClasses = computed(() => cx(iconClass, this.o().icon));
private readonly handleEl =
viewChild.required<ElementRef<HTMLDivElement>>("handleEl");
private pressed = false;
private move(next: number) {
const value = clamp(next);
this.current.set(value);
this.positionChange.emit(value);
}
private fromPointer(event: PointerEvent) {
const rect = (event.currentTarget as HTMLElement).getBoundingClientRect();
this.move(
this.orientation() === "vertical"
? ((event.clientY - rect.top) / rect.height) * 100
: ((event.clientX - rect.left) / rect.width) * 100,
);
}
protected onPointerDown(event: PointerEvent) {
if (event.button !== 0) return;
event.preventDefault();
this.pressed = true;
this.handleEl().nativeElement.focus({ preventScroll: true });
(event.currentTarget as HTMLElement).setPointerCapture?.(event.pointerId);
this.fromPointer(event);
}
protected onPointerMove(event: PointerEvent) {
if (!this.pressed) return;
this.dragging.set(true);
this.fromPointer(event);
}
protected release() {
this.pressed = false;
this.dragging.set(false);
}
protected onKeyDown(event: KeyboardEvent) {
const flip = this.orientation() === "vertical" ? -1 : 1;
const at = this.current();
const step = this.step();
const moves: Record<string, number> = {
ArrowRight: at + step,
ArrowLeft: at - step,
ArrowUp: at + step * flip,
ArrowDown: at - step * flip,
PageUp: at + PAGE_STEP,
PageDown: at - PAGE_STEP,
Home: 0,
End: 100,
};
const next = moves[event.key];
if (next === undefined) return;
event.preventDefault();
this.move(next);
}
}Pemakaian
<x-markas.image-compare aria-label="Renovasi ruang tamu" :position="40" before-label="Sebelum" after-label="Sesudah" slider-label="Posisi perbandingan">
<x-slot:before>
<img src="/img/before.jpg" alt="Ruang tamu sebelum renovasi" class="aspect-video size-full object-cover" />
</x-slot:before>
<x-slot:after>
<img src="/img/after.jpg" alt="Ruang tamu sesudah renovasi" class="aspect-video size-full object-cover" />
</x-slot:after>
</x-markas.image-compare>Butuh Alpine.js. Komponen mengirim event position-change berisi persen baru.
import { ImageCompare } from "@/components/markas/ImageCompare";
<ImageCompare
aria-label="Renovasi ruang tamu"
defaultPosition={40}
beforeLabel="Sebelum"
afterLabel="Sesudah"
sliderLabel="Posisi perbandingan"
before={<img src="/img/before.jpg" alt="Ruang tamu sebelum renovasi" />}
after={<img src="/img/after.jpg" alt="Ruang tamu sesudah renovasi" />}
/>;<template>
<ImageCompare
v-model:position="posisi"
aria-label="Renovasi ruang tamu"
before-label="Sebelum"
after-label="Sesudah"
slider-label="Posisi perbandingan"
>
<template #before
><img src="/img/before.jpg" alt="Ruang tamu sebelum renovasi"
/></template>
<template #after
><img src="/img/after.jpg" alt="Ruang tamu sesudah renovasi"
/></template>
</ImageCompare>
</template><script lang="ts">
import ImageCompare from "$lib/components/markas/ImageCompare.svelte";
let position = $state(50);
</script>
<ImageCompare bind:position aria-label="Kitchen renovation">
{#snippet before()}<img src="/img/kitchen-old.webp" alt="" />{/snippet}
{#snippet after()}<img src="/img/kitchen-new.webp" alt="" />{/snippet}
</ImageCompare>---
import ImageCompare from "@/components/markas/ImageCompare.astro";
---
<ImageCompare aria-label="Kitchen renovation">
<img slot="before" src="/img/kitchen-old.webp" alt="" />
<img slot="after" src="/img/kitchen-new.webp" alt="" />
</ImageCompare>Satu script kecil yang dibundel melayani semua perbandingan di halaman dan memancarkan position-change.
import { Component, signal } from "@angular/core";
import { ImageCompare } from "./markas/image-compare.component";
@Component({
selector: "app-renovation",
imports: [ImageCompare],
template: `
<markas-image-compare
[(position)]="position"
aria-label="Kitchen renovation"
>
<img before src="/img/kitchen-old.webp" alt="" />
<img after src="/img/kitchen-new.webp" alt="" />
</markas-image-compare>
`,
})
export class Renovation {
readonly position = signal(50);
}- Before di kiri (atau atas dengan
orientation="vertical"), after di kanan (atau bawah). Beri ukuran yang sama. - Geser di mana saja, klik satu titik, atau fokus pegangan lalu pakai tombol panah, Page Up/Down, Home, dan End.
- Isi apa pun bisa: img, picture, svg, atau markup biasa seperti UI lama dan baru.
- Atribut dan
classjatuh ke elemen luar.
Props
| Nama | Tipe | Default | Keterangan |
|---|---|---|---|
before / after | ReactNode / slot | - | Dua tampilan. Before di sisi awal (kiri atau atas), after di sisi akhir. Keduanya mengisi kotak yang sama, jadi beri ukuran yang sama. |
orientation | 'horizontal' | 'vertical' | horizontal | Horizontal membagi kiri dan kanan dengan pembatas vertikal. Vertical membagi atas dan bawah. |
position / defaultPosition / v-model:position | number | 50 | Posisi awal pembatas dalam persen dari sisi awal. Blade memakai position, React memakai defaultPosition dengan onPositionChange, Vue memakai v-model:position. |
step | number | 5 | Persen yang dipindah per tombol panah. Page Up dan Page Down memindah 10. |
beforeLabel | string | Before | Teks chip di sisi before. |
afterLabel | string | After | Teks chip di sisi after. |
sliderLabel | string | Comparison position | Nama aksesibel pegangan pembatas. |
positionChange | output<number> | - | Khusus Angular. Memancarkan posisi baru dalam persen; mendukung [(position)]. Svelte memakai bind:position atau onPositionChange, Astro memancarkan position-change. |
Aksesibilitas
- Pegangan adalah role slider yang bisa difokus dengan aria-valuenow, aria-valuetext dalam persen, dan aria-orientation.
- Tombol panah memindah sebesar step, Page Up dan Page Down sebesar 10, Home dan End melompat ke tepi.
- Menekan di mana pun pada gambar memindah pembatas ke sana dan memfokus pegangan, sehingga keyboard bisa melanjutkan.
- Pembatas meluncur ke titik yang diklik; dengan reduced motion pembatas langsung melompat.
Komponen terkait
Komponen markasui lain dengan class yang sama di setiap framework.
- Bottom NavigationBar bawah gaya aplikasi mobile. Pill meluncur ke item terpilih, labelnya muncul, dan bar bisa menciut jadi ikon saat konten discroll.
- Card StackTumpukan kartu bertingkat. Geser, tombol panah, atau tombol navigasi membuang kartu teratas lalu kartu berikutnya naik. Berputar, dengan indikator posisi.
- Chat MessagePesan dalam percakapan AI. Gelembung user di kanan, balasan asisten dengan avatar, aksi saat hover, indikator mengetik, dan efek streaming token opsional.
- Currency InputKolom uang yang memformat saat mengetik (Rp 12.500.000), menjaga posisi kursor, dan mengirim angka murni. Opsional chip nominal cepat.
- DockDock ala macOS. Ikon membesar halus mengikuti kursor atau fokus, label muncul di atas, item terbuka bertitik, dan memantul saat dibuka.
- Drag ElementsArea kartu atau stiker yang bisa diseret dengan momentum ringan di dalam batasnya. Panah menggeser item yang fokus, Escape mengembalikannya.