Spaces:
Running
Running
Download src/ui.ts from Chunte/hugging-space: direct link, hf CLI and curl.
- Browser
- Download file 15.6 kB
-
https://huggingface.co/spaces/Chunte/hugging-space/resolve/main/src/ui.ts
- Command line
-
hf download hf://spaces/Chunte/hugging-space/src/ui.ts
-
curl -L -o ui.ts https://huggingface.co/spaces/Chunte/hugging-space/resolve/main/src/ui.ts
15.6 kB
| // Page chrome behaviour: export menu, "Advanced tweaking" sheet, first-use hint and toasts. | |
| // The scene and its controls are wired in main.ts; this only opens / closes the chrome. | |
| export {}; | |
| const $ = <T extends HTMLElement>(id: string) => document.getElementById(id) as T; | |
| // ----- Export menu (anchored to its button; closes on choice, outside click or Esc) ----- | |
| const exportBtn = $<HTMLButtonElement>('exportBtn'); | |
| const exportMenu = $<HTMLDivElement>('exportMenu'); | |
| function setMenu(open: boolean) { | |
| exportMenu.hidden = !open; | |
| exportBtn.setAttribute('aria-expanded', String(open)); | |
| if (open) exportMenu.querySelector<HTMLButtonElement>('.menu-item')?.focus({ preventScroll: true }); | |
| } | |
| exportBtn.addEventListener('click', (e) => { | |
| e.stopPropagation(); | |
| setMenu(exportMenu.hidden); | |
| }); | |
| exportMenu.addEventListener('click', () => setMenu(false)); | |
| document.addEventListener('pointerdown', (e) => { | |
| if (!exportMenu.hidden && !(e.target as Element).closest('.menu-anchor')) setMenu(false); | |
| }); | |
| // ----- Advanced tweaking sheet: an iOS-style grabber expands / collapses it ----- | |
| // Desktop: the sheet sits on the right and, when collapsed, slides off-screen leaving its | |
| // vertical grabber peeking at the edge. Small screens: it comes up from the bottom with a | |
| // horizontal grabber. Click the grabber (or the toolbar's Advanced button) to toggle, or drag | |
| // it: the sheet follows the pointer 1:1 and settles by release velocity / position. | |
| const advancedBtn = $<HTMLButtonElement>('advancedBtn'); | |
| const advanced = $<HTMLElement>('advanced'); | |
| const handle = $<HTMLButtonElement>('sheetHandle'); | |
| const inner = Array.from(advanced.querySelectorAll<HTMLElement>('.sheet-head, .sheet-body')); | |
| const small = window.matchMedia('(max-width: 760px)'); | |
| const isOpen = () => !advanced.classList.contains('collapsed'); | |
| function setSheet(open: boolean) { | |
| advanced.classList.toggle('collapsed', !open); | |
| advancedBtn.setAttribute('aria-expanded', String(open)); | |
| advancedBtn.classList.toggle('active', open); | |
| handle.setAttribute('aria-expanded', String(open)); | |
| handle.setAttribute('aria-label', open ? 'Collapse advanced tweaking' : 'Expand advanced tweaking'); | |
| document.body.classList.toggle('sheet-open', open); | |
| for (const el of inner) el.inert = !open; // collapsed content isn't focusable | |
| window.dispatchEvent(new Event('layoutchange')); // the scene re-fits beside / above it | |
| } | |
| setSheet(false); | |
| advancedBtn.addEventListener('click', () => setSheet(!isOpen())); | |
| // Drag the grabber. | |
| let drag: { id: number; start: number; from: number; full: number; last: number; t: number; v: number; moved: boolean } | null = null; | |
| const along = (e: PointerEvent) => (small.matches ? e.clientY : e.clientX); | |
| const travel = () => (small.matches ? advanced.offsetHeight + 16 : advanced.offsetWidth + 12); | |
| const place = (offset: number) => { | |
| advanced.style.transform = small.matches ? `translateY(${offset}px)` : `translateX(${offset}px)`; | |
| }; | |
| handle.addEventListener('pointerdown', (e) => { | |
| const full = travel(); | |
| drag = { id: e.pointerId, start: along(e), from: isOpen() ? 0 : full, full, last: along(e), t: e.timeStamp, v: 0, moved: false }; | |
| try { | |
| handle.setPointerCapture(e.pointerId); | |
| } catch { | |
| /* synthetic pointers */ | |
| } | |
| }); | |
| handle.addEventListener('pointermove', (e) => { | |
| if (!drag || e.pointerId !== drag.id) return; | |
| const p = along(e); | |
| const d = p - drag.start; | |
| if (!drag.moved && Math.abs(d) < 4) return; | |
| if (!drag.moved) { | |
| drag.moved = true; | |
| advanced.classList.add('dragging'); | |
| if (!isOpen()) setSheet(true); // show the content while it's being pulled out | |
| } | |
| const dt = Math.max(1, e.timeStamp - drag.t); | |
| drag.v = 0.7 * drag.v + 0.3 * ((p - drag.last) / dt); // px per ms, smoothed | |
| drag.last = p; | |
| drag.t = e.timeStamp; | |
| // Follow 1:1 inside the travel, with a little resistance past fully open. | |
| let off = drag.from + d; | |
| if (off < 0) off = off * 0.25; | |
| place(Math.min(drag.full, off)); | |
| }); | |
| const release = (e: PointerEvent) => { | |
| if (!drag || e.pointerId !== drag.id) return; | |
| const { moved, v, from, start, full } = drag; | |
| drag = null; | |
| advanced.classList.remove('dragging'); | |
| advanced.style.transform = ''; | |
| if (!moved) { | |
| setSheet(!isOpen()); | |
| return; | |
| } | |
| const off = from + (along(e) - start); | |
| // A flick decides by its direction; a slow drag by where it was let go. | |
| const collapse = Math.abs(v) > 0.3 ? v > 0 : off > full / 2; | |
| setSheet(!collapse); | |
| }; | |
| handle.addEventListener('pointerup', release); | |
| handle.addEventListener('pointercancel', release); | |
| // ----- Toolbar: Examples is always a dropdown; Adjust is inline when it fits, else a dropdown ----- | |
| const toolbar = $<HTMLDivElement>('toolbar'); | |
| const groups = Array.from(toolbar.querySelectorAll<HTMLElement>('.tgroup')); | |
| const adjustGroup = toolbar.querySelector<HTMLElement>('[data-group="adjust"]')!; | |
| function setGroup(g: HTMLElement | null) { | |
| for (const x of groups) { | |
| const open = x === g; | |
| x.classList.toggle('open', open); | |
| x.querySelector('.tg-btn')?.setAttribute('aria-expanded', String(open)); | |
| } | |
| if (g) syncSliders(); | |
| } | |
| for (const g of groups) { | |
| g.querySelector('.tg-btn')!.addEventListener('click', (e) => { | |
| e.stopPropagation(); | |
| setGroup(g.classList.contains('open') ? null : g); | |
| }); | |
| } | |
| // Picking an example closes its list; any click outside closes an open group. | |
| toolbar.querySelector('.examples')!.addEventListener('click', (e) => { | |
| if ((e.target as Element).closest('.chip')) setGroup(null); | |
| }); | |
| // The Examples button names the logo on stage ("Examples: Pydantic"); none for an upload. | |
| const samplesEl = $<HTMLElement>('samples'); | |
| const currentExample = $<HTMLSpanElement>('currentExample'); | |
| function updateCurrentExample() { | |
| const on = samplesEl.querySelector<HTMLButtonElement>('.chip[aria-pressed="true"]'); | |
| currentExample.textContent = on?.textContent ?? ''; | |
| currentExample.hidden = !on; | |
| } | |
| new MutationObserver(updateCurrentExample).observe(samplesEl, { | |
| subtree: true, | |
| childList: true, | |
| attributes: true, | |
| attributeFilter: ['aria-pressed'], | |
| }); | |
| document.addEventListener('pointerdown', (e) => { | |
| if (!(e.target as Element).closest('.tgroup')) setGroup(null); | |
| }); | |
| // Compact when the full toolbar doesn't fit the room it has (next to the sheet, if open). | |
| let compactRaf = 0; | |
| function updateCompact() { | |
| cancelAnimationFrame(compactRaf); | |
| compactRaf = requestAnimationFrame(() => { | |
| const was = toolbar.classList.contains('compact'); | |
| toolbar.classList.remove('compact'); | |
| adjustGroup.classList.remove('dropdown'); | |
| const stage = $<HTMLElement>('stage').getBoundingClientRect(); | |
| const sheetRoom = document.body.classList.contains('sheet-open') && !small.matches ? 364 : 0; | |
| const room = stage.width - sheetRoom - 24; | |
| const compact = toolbar.scrollWidth > room; | |
| toolbar.classList.toggle('compact', compact); | |
| adjustGroup.classList.toggle('dropdown', compact); | |
| if (!compact && adjustGroup.classList.contains('open')) setGroup(null); | |
| if (compact !== was) window.dispatchEvent(new Event('layoutchange')); | |
| }); | |
| } | |
| window.addEventListener('resize', updateCompact); | |
| window.addEventListener('layoutchange', () => { | |
| if (!compactRaf) updateCompact(); | |
| }); | |
| new ResizeObserver(updateCompact).observe($<HTMLElement>('samples')); // chips arrive later | |
| updateCompact(); | |
| // ----- Vertical sliders (Control Center style) driving the Size / Rotate inputs ----- | |
| const vsliders = Array.from(toolbar.querySelectorAll<HTMLElement>('.vs')); | |
| function syncSliders() { | |
| for (const vs of vsliders) { | |
| const input = $<HTMLInputElement>(vs.dataset.for!); | |
| const min = Number(input.min); | |
| const max = Number(input.max); | |
| const v = Number(input.value); | |
| const t = (v - min) / (max - min); | |
| (vs.querySelector('.vs-fill') as HTMLElement).style.height = `${(t * 100).toFixed(1)}%`; | |
| (vs.querySelector('.vs-value') as HTMLElement).textContent = `${Math.round(v)}${vs.dataset.unit ?? ''}`; | |
| vs.setAttribute('aria-valuemin', String(min)); | |
| vs.setAttribute('aria-valuemax', String(max)); | |
| vs.setAttribute('aria-valuenow', String(Math.round(v))); | |
| } | |
| } | |
| function setInput(input: HTMLInputElement, v: number) { | |
| const min = Number(input.min); | |
| const max = Number(input.max); | |
| input.value = String(Math.round(Math.max(min, Math.min(max, v)))); | |
| input.dispatchEvent(new Event('input', { bubbles: true })); | |
| syncSliders(); | |
| } | |
| for (const vs of vsliders) { | |
| const input = $<HTMLInputElement>(vs.dataset.for!); | |
| const track = vs.querySelector<HTMLElement>('.vs-track')!; | |
| let dragging: number | null = null; | |
| const fromPointer = (e: PointerEvent) => { | |
| const r = track.getBoundingClientRect(); | |
| const t = Math.max(0, Math.min(1, 1 - (e.clientY - r.top) / r.height)); | |
| setInput(input, Number(input.min) + t * (Number(input.max) - Number(input.min))); | |
| }; | |
| track.addEventListener('pointerdown', (e) => { | |
| dragging = e.pointerId; | |
| try { | |
| track.setPointerCapture(e.pointerId); | |
| } catch { | |
| /* synthetic pointers */ | |
| } | |
| fromPointer(e); | |
| }); | |
| track.addEventListener('pointermove', (e) => { | |
| if (dragging === e.pointerId) fromPointer(e); | |
| }); | |
| const end = (e: PointerEvent) => { | |
| if (dragging === e.pointerId) dragging = null; | |
| }; | |
| track.addEventListener('pointerup', end); | |
| track.addEventListener('pointercancel', end); | |
| vs.addEventListener('keydown', (e) => { | |
| const step = (Number(input.max) - Number(input.min)) / 36; | |
| const d = e.key === 'ArrowUp' || e.key === 'ArrowRight' ? step : e.key === 'ArrowDown' || e.key === 'ArrowLeft' ? -step : 0; | |
| if (!d) return; | |
| e.preventDefault(); | |
| setInput(input, Number(input.value) + d); | |
| }); | |
| } | |
| // ----- Slider handles: a person that grows with Size, a dial that turns with Rotate ----- | |
| // Human figure: Material Design Icons "human-handsdown" (Pictogrammers, Apache 2.0). | |
| const PERSON = | |
| 'M12 1a2 2 0 0 0-2 2c0 1.11.89 2 2 2s2-.89 2-2a2 2 0 0 0-2-2m-2 5c-.27 0-.5.11-.69.28H9.3L4 11.59L5.42 13L9 9.41V22h2v-7h2v7h2V9.41L18.58 13L20 11.59l-5.3-5.31c-.2-.17-.43-.28-.7-.28'; | |
| const coarse = window.matchMedia('(pointer: coarse)'); | |
| // Comfortable handle sizes (px): small enough to sit in the toolbar, big enough to grab. | |
| const personRange = () => (coarse.matches ? [20, 46] : [16, 40]); | |
| const svgUrl = (svg: string) => `url("data:image/svg+xml,${encodeURIComponent(svg)}")`; | |
| /** The figure drawn for a handle of `px` pixels: ink fill, 2 px white outline, 1 px 0-blur | |
| * shadow ring. Stroke widths are converted to the icon's units so they stay true at any size. */ | |
| function personSvg(px: number, fill = '#1d1d1f', ring = 'rgba(0,0,0,0.22)') { | |
| const vb = 30; // 24 px icon + room for the outline | |
| const u = vb / px; // icon units per screen px | |
| return svgUrl( | |
| `<svg xmlns='http://www.w3.org/2000/svg' viewBox='-3 -3 ${vb} ${vb}'>` + | |
| `<path d='${PERSON}' fill='none' stroke='${ring}' stroke-width='${(6 * u).toFixed(3)}' stroke-linejoin='round'/>` + | |
| `<path d='${PERSON}' fill='none' stroke='#fff' stroke-width='${(4 * u).toFixed(3)}' stroke-linejoin='round'/>` + | |
| `<path d='${PERSON}' fill='${fill}'/>` + | |
| `</svg>`, | |
| ); | |
| } | |
| function dialSvg(deg: number) { | |
| return svgUrl( | |
| `<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'>` + | |
| `<g transform='rotate(${deg.toFixed(1)} 10 10)'><line x1='10' y1='10' x2='10' y2='4' stroke='#1d1d1f' stroke-width='1.8' stroke-linecap='round'/></g>` + | |
| `<circle cx='10' cy='10' r='1.6' fill='#1d1d1f'/></svg>`, | |
| ); | |
| } | |
| const sizeInput = $<HTMLInputElement>('size'); | |
| const rotInput = $<HTMLInputElement>('rotation'); | |
| const sizeVs = toolbar.querySelector<HTMLElement>('.vs[data-for=size]'); | |
| const figure = document.createElement('span'); | |
| figure.className = 'vs-figure'; | |
| sizeVs?.querySelector('.vs-track')?.appendChild(figure); | |
| let lastSize = ''; | |
| let lastRot = ''; | |
| function syncHandles() { | |
| const key = `${sizeInput.value}|${coarse.matches}`; | |
| if (key !== lastSize) { | |
| lastSize = key; | |
| const t = (Number(sizeInput.value) - Number(sizeInput.min)) / (Number(sizeInput.max) - Number(sizeInput.min)); | |
| const [lo, hi] = personRange(); | |
| const px = Math.round(lo + t * (hi - lo)); | |
| sizeInput.style.setProperty('--ts', `${px}px`); | |
| sizeInput.style.setProperty('--thumb', personSvg(px)); | |
| // The vertical slider's figure rides at the top of the dark fill (its white outline pops there). | |
| const track = sizeVs?.querySelector<HTMLElement>('.vs-track'); | |
| if (track) { | |
| const h = track.clientHeight || 148; | |
| const vpx = Math.round(18 + t * 18); | |
| const pos = Math.max(vpx / 2 + 6, Math.min(h - vpx / 2 - 6, t * h)); | |
| figure.style.setProperty('--ts', `${vpx}px`); | |
| figure.style.setProperty('--fill', `${pos.toFixed(1)}px`); | |
| figure.style.setProperty('--thumb', personSvg(vpx)); | |
| } | |
| } | |
| if (rotInput.value !== lastRot) { | |
| lastRot = rotInput.value; | |
| rotInput.style.setProperty('--thumb', dialSvg(Number(rotInput.value))); | |
| } | |
| } | |
| // Immediate on slider input; the frame loop below catches scroll / pinch / reset too. | |
| sizeInput.addEventListener('input', syncHandles); | |
| rotInput.addEventListener('input', syncHandles); | |
| coarse.addEventListener('change', syncHandles); | |
| syncHandles(); | |
| // Keep everything in sync with drag / scroll / pinch / reset. | |
| (function follow() { | |
| if (toolbar.querySelector('.tgroup.open .vsliders')) syncSliders(); | |
| syncHandles(); | |
| requestAnimationFrame(follow); | |
| })(); | |
| document.addEventListener('keydown', (e) => { | |
| if (e.key !== 'Escape') return; | |
| if (groups.some((g) => g.classList.contains('open'))) { | |
| setGroup(null); | |
| return; | |
| } | |
| if (!exportMenu.hidden) { | |
| setMenu(false); | |
| exportBtn.focus(); | |
| } else if (isOpen()) { | |
| setSheet(false); | |
| advancedBtn.focus(); | |
| } | |
| }); | |
| // ----- Hint above the toolbar: shown whenever nothing is being touched ----- | |
| // It steps aside while the stage or the toolbar is in use (dragging the logo or a hand, | |
| // scrolling / pinching to resize or rotate, moving a slider) and comes back shortly after. | |
| // (An open menu or the Advanced sheet hides it too; that part is CSS.) | |
| const hint = $<HTMLParagraphElement>('hint'); | |
| const HINT_BACK_MS = 1400; | |
| let hintTimer = 0; | |
| let pointersDown = 0; | |
| const hintAway = () => { | |
| window.clearTimeout(hintTimer); | |
| hint.classList.add('gone'); | |
| }; | |
| const hintBackSoon = () => { | |
| window.clearTimeout(hintTimer); | |
| hintTimer = window.setTimeout(() => { | |
| if (pointersDown === 0) hint.classList.remove('gone'); | |
| }, HINT_BACK_MS); | |
| }; | |
| for (const area of [$<HTMLElement>('stage')]) { | |
| area.addEventListener('pointerdown', (e) => { | |
| if ((e.target as Element).closest('#drop')) return; // the upload / drop overlay isn't tweaking | |
| pointersDown++; | |
| hintAway(); | |
| }); | |
| // Scroll to resize, shift-scroll to rotate, trackpad pinch: one event per step, no "end". | |
| area.addEventListener( | |
| 'wheel', | |
| () => { | |
| hintAway(); | |
| hintBackSoon(); | |
| }, | |
| { passive: true }, | |
| ); | |
| // Sliders moved by keyboard (or anything else that changes them). | |
| area.addEventListener('input', () => { | |
| hintAway(); | |
| hintBackSoon(); | |
| }); | |
| } | |
| for (const type of ['pointerup', 'pointercancel'] as const) { | |
| window.addEventListener(type, () => { | |
| if (pointersDown === 0) return; | |
| pointersDown = Math.max(0, pointersDown - 1); | |
| if (pointersDown === 0) hintBackSoon(); | |
| }); | |
| } | |
| // ----- Toast: status messages show briefly, then clear ----- | |
| const toast = $<HTMLParagraphElement>('status'); | |
| let toastTimer = 0; | |
| new MutationObserver(() => { | |
| window.clearTimeout(toastTimer); | |
| if (toast.textContent) toastTimer = window.setTimeout(() => (toast.textContent = ''), 3200); | |
| }).observe(toast, { childList: true, characterData: true, subtree: true }); | |