refactor(frontent): move components and ts to lib folder

This commit is contained in:
2025-12-29 18:38:20 +01:00
parent 54b9e1fc78
commit abf227d15d
30 changed files with 41 additions and 40 deletions
@@ -0,0 +1,188 @@
<script lang="ts">
import { get_shifted_color } from '../ts/stores/ui_behavior';
import type { MenuOption } from '../ts/types';
import { fade } from 'svelte/transition';
let {
className = '',
bg = 'bg-stone-700',
hover_bg = get_shifted_color(bg, 100),
active_bg = get_shifted_color(bg, 200),
disabled = false,
title = '',
click_function = () => {},
menu_options = null,
menu_class = 'right-0',
div_class = '',
children
}: {
className?: string;
bg?: string;
hover_bg?: string;
active_bg?: string;
disabled?: boolean;
title?: string;
click_function?: (e: MouseEvent) => void;
menu_options?: MenuOption[] | null;
menu_class?: string;
div_class?: string;
children?: any;
} = $props();
let menu_shown = $state(false);
let button_element: HTMLButtonElement;
let menu_element: HTMLDivElement | null = $state(null);
let position_bottom = $state(true);
function onclick(e: MouseEvent) {
if (menu_options !== null) {
if (menu_shown) {
close_menu();
} else {
open_menu();
}
}
click_function(e);
}
function getPolygon(): [number, number][] | null {
if (!button_element || !menu_element) return null;
const b = button_element.getBoundingClientRect();
const m = menu_element.getBoundingClientRect();
// get polygon coords
if (position_bottom) {
return [
[b.left, b.top],
[b.right, b.top],
[m.right, m.top],
[m.right, m.bottom],
[m.left, m.bottom],
[m.left, m.top],
[b.left, b.top]
];
} else {
return [
[b.left, b.bottom],
[b.right, b.bottom],
[m.right, m.bottom],
[m.right, m.top],
[m.left, m.top],
[m.left, m.bottom],
[b.left, b.bottom]
];
}
}
function handleMouseMove(e: MouseEvent) {
if (!menu_shown) return;
const polygon = getPolygon();
if (!polygon) return;
const inside = pointInPolygon([e.clientX, e.clientY], polygon);
if (!inside) {
close_menu();
}
}
function pointInPolygon(point: [number, number], polygon: [number, number][]) {
let [x, y] = point;
let inside = false;
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
let [xi, yi] = polygon[i];
let [xj, yj] = polygon[j];
let intersect = yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi;
if (intersect) inside = !inside;
}
return inside;
}
function is_enough_space_below(): boolean {
if (!button_element || !menu_element) return true;
const button_rectangle = button_element.getBoundingClientRect();
const menu_height = menu_element.offsetHeight;
const space_below_available = window.innerHeight - button_rectangle.bottom;
return space_below_available > menu_height;
}
function open_menu() {
menu_shown = true;
window.addEventListener('mousemove', handleMouseMove);
setTimeout(() => {
position_bottom = is_enough_space_below();
}, 0);
}
function close_menu() {
window.removeEventListener('mousemove', handleMouseMove);
menu_shown = false;
}
function no_option_has_icon(): boolean {
for (const option of menu_options) {
if (option.icon) {
return false;
}
}
return true;
}
</script>
<div class="relative min-w-0 flex {div_class}" {title}>
<button
bind:this={button_element}
class="{className} {menu_shown ? hover_bg : bg} {disabled
? 'text-stone-500 cursor-not-allowed'
: 'hover:' +
hover_bg +
' active:' +
active_bg +
' cursor-pointer'} p-2 rounded-xl flex justify-center items-center transition-colors duration-200"
{disabled}
{onclick}
>
{@render children()}
</button>
{#if menu_shown}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<!-- svelte-ignore a11y_click_events_have_key_events -->
<div
bind:this={menu_element}
transition:fade={{ duration: 50 }}
class="absolute {position_bottom
? 'top-full'
: 'bottom-full'} {menu_class} z-100 my-1.5 min-w-64 rounded-xl backdrop-blur bg-stone-800/45 border border-stone-400/10 shadow-xl/20 p-2 flex flex-col gap-2 text-stone-200 cursor-auto"
onclick={(e) => {
e.stopPropagation();
}}
>
{#each menu_options as option}
<button
disabled={option.disabled ?? false}
class="bg-white/15 {option.disabled
? 'text-stone-500 cursor-not-allowed'
: 'hover:bg-white/35 active:bg-white/60 cursor-pointer ' +
option.class} rounded-lg p-2 transition-colors duration-200 select-none flex flex-row gap-2 items-center"
onclick={async (e) => {
if (option.on_select) await option.on_select();
close_menu();
}}
>
{#if !no_option_has_icon()}
<div class="aspect-square h-[1.2rem]">
{#if option.icon}
{@const Icon = option.icon}
<Icon class="size-full" />
{/if}
</div>
{/if}
<div class="truncate min-w-0" title={option.name}>
{option.name}
</div>
</button>
{/each}
</div>
{/if}
</div>
@@ -0,0 +1,148 @@
<script lang="ts">
import {
ArrowBigLeft,
ArrowBigRight,
ChevronDown,
Keyboard,
Power,
PowerOff,
Presentation,
SquareTerminal,
TextAlignStart,
TrafficCone
} from 'lucide-svelte';
import { onMount } from 'svelte';
import Button from './Button.svelte';
import PopUp from './PopUp.svelte';
import type { PopupContent } from '../ts/types';
import KeyInput from './KeyInput.svelte';
import { send_keyboard_input, show_blackscreen } from '../ts/api_handler';
import { run_on_all_selected_displays } from '../ts/stores/displays';
import { selected_display_ids } from '../ts/stores/select';
import TipTapInput from './TipTapInput.svelte';
let popup_content: PopupContent = $state({
open: false,
snippet: null,
title: '',
closable: true
});
function popup_close_function() {
popup_content.open = false;
}
const show_send_keys_popup = () => {
popup_content = {
open: true,
snippet: send_keys_popup,
title: 'Tastatur-Eingaben durchgeben',
title_icon: Keyboard,
closable: true
};
};
const show_text_popup = () => {
popup_content = {
open: true,
snippet: text_popup,
title: 'Text anzeigen',
title_icon: TextAlignStart,
closable: true,
window_class: 'size-full'
};
};
</script>
{#snippet send_keys_popup()}
<div class="overflow-hidden flex flex-col gap-2">
<div>
<KeyInput />
</div>
<div class="flex flex-row justify-end gap-2">
<Button className="px-4 font-bold" click_function={popup_close_function}>Fertig</Button>
</div>
</div>
{/snippet}
{#snippet text_popup()}
<TipTapInput />
{/snippet}
<div class="grid grid-rows-[2.5rem_auto] bg-stone-800 rounded-2xl min-w-0">
<div class="text-xl font-bold pl-3 content-center bg-stone-700 rounded-t-2xl truncate min-w-0">
Bildschirme steuern
</div>
<div class="relative flex flex-col gap-2 p-2 overflow-auto">
<div class="flex flex-row justify-between gap-2">
<div class="flex flex-col gap-2">
<div class="flex flex-row gap-2 w-75 justify-normal">
<Button
title="Vorherige Folie (Pfeil nach Links)"
className="px-9"
disabled={$selected_display_ids.length === 0}
click_function={async () => {
await run_on_all_selected_displays(send_keyboard_input, true, 'VK_LEFT');
}}><ArrowBigLeft /></Button
>
<Button
title="Nächste Folie (Pfeil nach Rechts)"
className="px-9"
disabled={$selected_display_ids.length === 0}
click_function={async () => {
await run_on_all_selected_displays(send_keyboard_input, true, 'VK_RIGHT');
}}><ArrowBigRight /></Button
>
</div>
<Button
className="px-3 flex gap-3 w-75 justify-normal"
disabled={$selected_display_ids.length === 0}
click_function={show_text_popup}><TextAlignStart /> Text anzeigen</Button
>
<Button
className="px-3 flex gap-3 w-75 justify-normal"
disabled={$selected_display_ids.length === 0}
click_function={async () => {
await run_on_all_selected_displays(show_blackscreen, true);
}}><Presentation />Blackout</Button
>
<div class="flex flex-row justify-normal">
<Button
className="rounded-r-none pl-3 flex gap-3 grow w-65 justify-normal"
disabled={$selected_display_ids.length === 0}
><TrafficCone /> Fallback-Bild anzeigen</Button
>
<Button className="rounded-l-none flex grow-0 w-10"><ChevronDown /></Button>
</div>
<Button
className="px-3 flex gap-3 w-75 justify-normal"
disabled={$selected_display_ids.length === 0}
click_function={show_send_keys_popup}><Keyboard /> Tastatur-Eingaben durchgeben</Button
>
</div>
<div class="flex flex-col gap-2 justify-between">
<div class="flex flex-col gap-2">
<Button
className="px-3 flex gap-3 w-full xl:w-75 justify-normal"
disabled={$selected_display_ids.length === 0}><Power /> PC hochfahren</Button
>
<Button
className="px-3 flex gap-3 w-full xl:w-75 justify-normal"
disabled={$selected_display_ids.length === 0}><PowerOff /> PC herunterfahren</Button
>
</div>
<Button
className="px-3 flex gap-3 w-full xl:w-75 justify-normal"
disabled={$selected_display_ids.length === 0}
><SquareTerminal /> Shell-Befehl ausführen</Button
>
</div>
</div>
<PopUp
content={popup_content}
close_function={popup_close_function}
className="rounded-b-2xl"
snippet_container_class="size-full"
/>
</div>
</div>
@@ -0,0 +1,16 @@
<script lang="ts">
import { GripHorizontal } from 'lucide-svelte';
import { dragHandle } from 'svelte-dnd-action';
let { bg, className = "" }: {
bg: string;
className?: string;
} = $props();
</script>
<div
use:dragHandle
class="{className} bg-transparent hover:{bg} active:{bg} p-2 rounded-xl duration-200 transition-colors"
>
<GripHorizontal />
</div>
@@ -0,0 +1,127 @@
<script lang="ts">
import { dragHandleZone, TRIGGERS } from 'svelte-dnd-action';
import {
dnd_flip_duration_ms,
get_selectable_color_classes,
is_display_drag,
is_group_drag
} from '../ts/stores/ui_behavior';
import { cubicOut } from 'svelte/easing';
import { flip } from 'svelte/animate';
import DisplayObject from './DisplayObject.svelte';
import {
all_displays_of_group_selected,
get_display_ids_in_group,
select_all_of_group,
set_new_display_order
} from '../ts/stores/displays';
import DNDGrip from './DNDGrip.svelte';
import { fade } from 'svelte/transition';
import type { MenuOption } from '../ts/types';
import { selected_display_ids } from '../ts/stores/select';
import { liveQuery } from 'dexie';
let {
display_group_id,
get_display_menu_options,
close_pinned_display
}: {
display_group_id: string;
get_display_menu_options: (display_id: string) => MenuOption[];
close_pinned_display: () => void;
} = $props();
let all_selected = liveQuery(() =>
all_displays_of_group_selected(display_group_id, $selected_display_ids)
);
let display_ids_in_group = liveQuery(() => get_display_ids_in_group(display_group_id));
let hovering_selectable = $state(false);
async function select_all_of_this_group() {
const new_value = !(await all_displays_of_group_selected(
display_group_id,
$selected_display_ids
));
await select_all_of_group(display_group_id, new_value);
}
async function handle_consider(e: CustomEvent) {
const { items, info } = e.detail;
if (items.length !== 1 && info.trigger === TRIGGERS.DRAG_STARTED) {
$is_display_drag = true;
// add_empty_display_group();
}
await set_new_display_order(items);
}
async function handle_finalize(e: CustomEvent) {
$is_display_drag = false;
await set_new_display_order(e.detail.items);
}
</script>
<div
transition:fade={{ duration: 100 }}
class="{get_selectable_color_classes(
$all_selected || false,
{
bg: true,
hover: hovering_selectable,
active: hovering_selectable,
text: true
},
-150,
-50
)} transition-colors duration-200 rounded-2xl flex flex-row cursor-pointer"
>
<div
class="flex flex-col min-w-0 pl-2 py-2 gap-2 w-full"
use:dragHandleZone={{
items: $display_ids_in_group || [],
type: 'item',
flipDurationMs: dnd_flip_duration_ms,
dropTargetStyle: { outline: 'none' }
}}
onconsider={handle_consider}
onfinalize={handle_finalize}
>
{#each $display_ids_in_group || [] as display (display.id)}
<!-- Each Group -->
<section
animate:flip={{ duration: $is_group_drag ? 0 : dnd_flip_duration_ms, easing: cubicOut }}
class="outline-none"
role="figure"
>
<DisplayObject {display} {get_display_menu_options} {close_pinned_display} />
</section>
{/each}
{#if ($display_ids_in_group || []).length === 0}
<div class="min-h-10 h-full w-full pl-2 py-2 flex justify-center items-center">
Hier in leere neue Gruppe ablegen
</div>
{/if}
</div>
<div
class="flex items-center justify-center px-2"
onclick={select_all_of_this_group}
role="button"
tabindex="0"
onkeydown={async (e) => {
if (e.key === 'Enter' || e.key === ' ') await select_all_of_this_group();
}}
onmouseenter={() => (hovering_selectable = true)}
onmouseleave={() => (hovering_selectable = false)}
>
<DNDGrip
bg={get_selectable_color_classes(
$all_selected || false,
{
bg: true
},
-150
)}
/>
</div>
</div>
+143
View File
@@ -0,0 +1,143 @@
<script lang="ts">
import Button from './Button.svelte';
import {
current_height,
get_selectable_color_classes,
pinned_display_id
} from '../ts/stores/ui_behavior';
import DNDGrip from './DNDGrip.svelte';
import { Menu, Pin, PinOff, VideoOff } from 'lucide-svelte';
import OnlineState from './OnlineState.svelte';
import type { Display, MenuOption } from '../ts/types';
import { is_selected, select, selected_display_ids } from '../ts/stores/select';
import { screenshot_loop } from '../ts/stores/displays';
import { change_file_path, current_file_path } from '../ts/stores/files';
let {
display,
get_display_menu_options,
close_pinned_display
}: {
display: Display;
get_display_menu_options: (display_id: string) => MenuOption[];
close_pinned_display: () => void;
} = $props();
let hovering_unselectable = $state(false);
async function onclick(e: Event) {
e.stopPropagation();
select(selected_display_ids, display.id, 'toggle');
// force file view update
await change_file_path($current_file_path);
}
async function on_preview_click(e: MouseEvent) {
if ($pinned_display_id === display.id) {
close_pinned_display();
} else {
$pinned_display_id = display.id;
}
await screenshot_loop(display.id);
e.stopPropagation();
}
</script>
<div
data-testid="display"
role="button"
tabindex="0"
onkeydown={(e) => {
if (e.key === 'Enter' || e.key === ' ') onclick(e);
}}
{onclick}
class="p-1 {get_selectable_color_classes(is_selected(display.id, $selected_display_ids), {
bg: true,
hover: true,
active: !hovering_unselectable,
text: true
})} rounded-xl flex flex-row justify-between h-{$current_height.display} transition-colors duration-100 gap-2 cursor-pointer w-full text-stone-200"
>
<div class="flex flex-row gap-4 min-w-0 flex-1">
<!-- Left Preview Screen -->
<button
class="group relative aspect-video bg-stone-800 h-full rounded-lg overflow-hidden cursor-pointer text-stone-200 transition-colors duration-200"
onmouseenter={() => (hovering_unselectable = true)}
onmouseleave={() => (hovering_unselectable = false)}
onclick={on_preview_click}
>
<div class="flex h-full w-full items-center justify-center">
{#if $pinned_display_id === display.id}
<div class="size-[50%]">
<Pin class="size-full" />
</div>
{:else if display.preview.url}
<img src={display.preview.url} alt="preview" class="w-full object-cover bg-black" />
{:else}
<!-- No Signal -->
<div class="size-full bg-black flex justify-center items-center">
<VideoOff class="size-[30%]" />
</div>
{/if}
</div>
<!-- Hover Effect -->
<span
class="pointer-events-none absolute inset-0 {$pinned_display_id === display.id
? 'bg-stone-700'
: 'bg-stone-700/70'} opacity-0 transition-opacity duration-200 flex items-center justify-center group-hover:opacity-100"
>
{#if $pinned_display_id === display.id}
<PinOff class="size-[50%]" aria-hidden="true" />
{:else}
<Pin class="size-[50%]" aria-hidden="true" />
{/if}
</span>
</button>
<!-- Middle Text Block -->
<div
class="h-full flex flex-col justify-center gap-1 select-none
min-w-0 basis-0 flex-1"
>
<div class="text-xl font-bold truncate w-full" title={display.name}>
{display.name}
</div>
<OnlineState
selected={is_selected(display.id, $selected_display_ids)}
status={display.status}
/>
</div>
</div>
<!-- Right Controls -->
<div class="flex flex-row h-full items-center gap-2 pr-3">
<DNDGrip
bg={get_selectable_color_classes(is_selected(display.id, $selected_display_ids), {
bg: true
})}
/>
<div
role="figure"
onmouseenter={() => (hovering_unselectable = true)}
onmouseleave={() => (hovering_unselectable = false)}
>
<Button
bg="bg-transparent"
hover_bg={get_selectable_color_classes(is_selected(display.id, $selected_display_ids), {
bg: true
})}
active_bg={get_selectable_color_classes(is_selected(display.id, $selected_display_ids), {
bg: true
})}
click_function={(e) => {
e.stopPropagation();
}}
menu_options={get_display_menu_options(display.id)}
>
<Menu />
</Button>
</div>
</div>
</div>
+293
View File
@@ -0,0 +1,293 @@
<script lang="ts">
import { fade, scale } from 'svelte/transition';
import {
all_displays_of_group_selected,
get_display_by_id,
get_display_groups,
select_all_of_group,
set_new_display_group_order
} from '../ts/stores/displays';
import {
change_height,
current_height,
dnd_flip_duration_ms,
get_selectable_color_classes,
is_display_drag,
is_group_drag,
next_height_step_size,
pinned_display_id
} from '../ts/stores/ui_behavior';
import { type Display, type DisplayGroup, type MenuOption } from '../ts/types';
import Button from './Button.svelte';
import OnlineState from './OnlineState.svelte';
import { cubicOut } from 'svelte/easing';
import { Menu, Pencil, PinOff, Settings, Trash2, VideoOff, ZoomIn, ZoomOut } from 'lucide-svelte';
import { selected_display_ids } from '../ts/stores/select';
import { dragHandleZone } from 'svelte-dnd-action';
import { flip } from 'svelte/animate';
import DisplayGroupObject from './DisplayGroupObject.svelte';
import { Pane, Splitpanes } from 'svelte-splitpanes';
import HighlightedText from './HighlightedText.svelte';
import { liveQuery, type Observable } from 'dexie';
let {
handle_display_deletion,
handle_display_editing
}: {
handle_display_deletion: (display_id: string) => void;
handle_display_editing: (display_id: string) => void;
} = $props();
let displays_scroll_box: HTMLElement;
let pinned_display: Observable<Display | null> = liveQuery(() =>
get_display_by_id($pinned_display_id || '')
);
let display_groups = liveQuery(() => get_display_groups());
let all_groups_selected = liveQuery(() =>
all_selected($display_groups || [], $selected_display_ids)
);
let last_pinned_pane_size: number = 45;
let pinned_pane_size: number = $state(last_pinned_pane_size);
function close_pinned_display() {
last_pinned_pane_size = pinned_pane_size;
pinned_pane_size = 0;
}
function get_display_menu_options(display_id: string): MenuOption[] {
return [
{
icon: Pencil,
name: 'Bildschirm bearbeiten',
on_select: () => {
handle_display_editing(display_id);
}
},
{
icon: Trash2,
name: 'Bildschirm löschen',
class: 'text-red-400 hover:text-stone-200 hover:!bg-red-400 active:!bg-red-500',
on_select: () => {
handle_display_deletion(display_id);
}
}
];
}
async function select_all(
current_displays: DisplayGroup[],
current_selected_display_ids: string[]
) {
const new_value = !(await all_selected(current_displays, current_selected_display_ids));
for (const display_group of current_displays) {
await select_all_of_group(display_group.id, new_value);
}
}
async function all_selected(
current_displays: DisplayGroup[],
current_selected_display_ids: string[]
) {
for (const display_group of current_displays) {
if (!(await all_displays_of_group_selected(display_group.id, current_selected_display_ids))) {
return false;
}
}
return true;
}
function handle_splitpane_resize(e: any) {
if (e.detail[0].size === 0) {
$pinned_display_id = null;
pinned_pane_size = last_pinned_pane_size;
}
}
function on_wheel(e: WheelEvent) {
if (!$is_group_drag && !$is_display_drag) return;
if (!displays_scroll_box) return;
// apply custom scroll feature
e.preventDefault();
(displays_scroll_box as HTMLElement).scrollBy?.({
top: e.deltaY,
behavior: 'auto'
});
}
</script>
<svelte:window on:wheel={on_wheel} />
<div class="h-[calc(100dvh-3rem-(6*var(--spacing)))] flex flex-col gap-2">
<Splitpanes
horizontal
theme="mudics-stone-theme"
on:resized={handle_splitpane_resize}
dblClickSplitter={false}
>
{#if $pinned_display_id}
<!-- Pinned Item -->
<Pane maxSize={60} snapSize={20} bind:size={pinned_pane_size}>
<div class="h-full" transition:fade>
<div class="grid grid-rows-[2.5rem_auto] will-change-[height,opacity] h-full">
<div
class="bg-stone-700 rounded-t-2xl flex justify-between w-full p-1 min-w-0 basis-0 flex-1"
>
<span
class="text-xl font-bold pl-2 content-center truncate min-w-0"
title={$pinned_display?.name || '...'}
>
{$pinned_display?.name || '...'}
</span>
<div class="flex flex-row gap-1">
<div class="flex flex-row items-center mr-1">
<span class="text-stone-400"> Aktueller Status: </span>
<OnlineState
selected={false}
status={$pinned_display?.status ?? null}
className="flex items-center px-2"
/>
</div>
<Button
className="aspect-square !p-1"
bg="bg-stone-600"
click_function={(e) => {
e.stopPropagation();
}}
menu_options={get_display_menu_options($pinned_display_id)}
>
<Menu />
</Button>
<Button
title="Bildschirm nicht mehr anpinnen"
className="aspect-square !p-1"
bg="bg-stone-600"
click_function={close_pinned_display}
>
<PinOff />
</Button>
</div>
</div>
<div
class="h-full bg-stone-800 rounded-b-2xl overflow-hidden flex justify-center items-center"
>
{#if $pinned_display?.preview.url}
<img
src={$pinned_display.preview.url}
alt="preview"
class="max-h-full max-w-full object-cover bg-black"
/>
{:else}
<div class="size-full bg-black flex justify-center items-center">
<VideoOff class="size-[20%]" />
</div>
{/if}
</div>
</div>
</div>
</Pane>
{/if}
<Pane>
<div
class="min-h-0 h-full grid grid-rows-[2.5rem_auto] bg-stone-800 rounded-2xl overflow-hidden"
>
<!-- Normal Heading Left -->
<div class="bg-stone-700 flex justify-between w-full p-1 gap-2 min-w-0">
<span class="text-xl font-bold pl-2 content-center truncate min-w-0">
Verbundene Bildschirme
</span>
<div class="flex flex-row gap-1">
<button
class="min-w-40 px-4 rounded-xl cursor-pointer duration-200 transition-colors {get_selectable_color_classes(
$all_groups_selected || false,
{
bg: true,
hover: true,
active: true,
text: true
}
)}"
onclick={async () => await select_all($display_groups || [], $selected_display_ids)}
>
<span>{$all_groups_selected || false ? 'Alle abwählen' : 'Alle auswählen'}</span>
</button>
<div class="flex flex-row">
<Button
title="Bildschirme größer darstellen"
className="aspect-square !p-1 rounded-r-none"
bg="bg-stone-600"
disabled={!Boolean(next_height_step_size('display', $current_height, 1))}
click_function={() => {
change_height('display', 1);
}}
>
<ZoomIn />
</Button>
<Button
title="Bildschirme kleiner darstellen"
className="aspect-square !p-1 rounded-l-none"
bg="bg-stone-600"
disabled={!Boolean(next_height_step_size('display', $current_height, -1))}
click_function={() => {
change_height('display', -1);
}}
>
<ZoomOut />
</Button>
</div>
</div>
</div>
<div class="min-h-0 overflow-y-auto" bind:this={displays_scroll_box}>
<div
class="min-h-full p-2 flex flex-col gap-4"
use:dragHandleZone={{
items: $display_groups || [],
type: 'group',
flipDurationMs: dnd_flip_duration_ms,
dropFromOthersDisabled: true,
dropTargetStyle: { outline: 'none' }
}}
onconsider={async (e: CustomEvent) => {
$is_group_drag = true;
await set_new_display_group_order(e.detail.items);
}}
onfinalize={async (e: CustomEvent) => {
await set_new_display_group_order(e.detail.items);
$is_group_drag = false;
}}
>
{#if ($display_groups || []).length === 0}
<div class="text-stone-500 px-10 py-6 leading-relaxed text-center">
Es wurden noch keine Bildschirme hinzugefügt. Klicke oben rechts auf
<HighlightedText fg="text-stone-450" className="!p-1"
><Settings class="inline pb-1" /></HighlightedText
>
und
<HighlightedText fg="text-stone-450">Neuen Bildschirm hinzufügen</HighlightedText>.
</div>
{:else}
{#each $display_groups || [] as display_group (display_group.id)}
<!-- Each Group -->
<section
out:scale={{ duration: dnd_flip_duration_ms, easing: cubicOut }}
animate:flip={{ duration: dnd_flip_duration_ms, easing: cubicOut }}
class="outline-none"
>
<DisplayGroupObject
display_group_id={display_group.id}
{get_display_menu_options}
{close_pinned_display}
/>
</section>
{/each}
{/if}
</div>
</div>
</div>
</Pane>
</Splitpanes>
</div>
+366
View File
@@ -0,0 +1,366 @@
<script lang="ts">
import {
ClipboardPaste,
Download,
FolderPlus,
Pen,
RefreshCcw,
Scissors,
Trash2,
Upload,
ZoomIn,
ZoomOut
} from 'lucide-svelte';
import { change_height, current_height, next_height_step_size } from '../ts/stores/ui_behavior';
import Button from './Button.svelte';
import PathBar from './PathBar.svelte';
import { selected_display_ids, selected_file_ids } from '../ts/stores/select';
import {
current_file_path,
get_current_folder_elements,
get_file_by_id,
run_for_selected_files_on_selected_displays,
update_current_folder_on_selected_displays,
get_displays_where_path_exists,
create_folder_on_all_selected_displays
} from '../ts/stores/files';
import { slide } from 'svelte/transition';
import InodeElement from './InodeElement.svelte';
import PopUp from './PopUp.svelte';
import { get_file_primary_key, type Inode, type PopupContent } from '../ts/types';
import TextInput from './TextInput.svelte';
import { is_valid_name } from '../ts/utils';
import { delete_files, rename_file } from '../ts/api_handler';
import HighlightedText from './HighlightedText.svelte';
import { liveQuery } from 'dexie';
let current_name: string = $state('');
let current_valid: boolean = $state(false);
let display_names_where_path_does_not_exist: string[] = $state([]);
let selected_files = liveQuery(() => get_selected_files($selected_display_ids));
let current_folder_elements = liveQuery(() =>
get_current_folder_elements($current_file_path, $selected_display_ids)
);
let popup_content: PopupContent = $state({
open: false,
snippet: null,
title: '',
closable: true
});
async function get_selected_files(selected_file_ids: string[]): Promise<Inode[]> {
try {
const results = await Promise.all(selected_file_ids.map((id) => get_file_by_id(id)));
return results.filter((element) => element !== null);
} catch (e: unknown) {
console.error('Error on generating selected_files');
return [];
}
}
function popup_close_function() {
popup_content.open = false;
}
async function create_new_folder() {
await create_folder_on_all_selected_displays(
current_name.trim(),
$current_file_path,
$selected_display_ids
);
await update_current_folder_on_selected_displays();
popup_close_function();
}
async function edit_file_name(new_file_name: string) {
await run_for_selected_files_on_selected_displays(async (ip: string, file_names: string[]) => {
if (file_names.length !== 1) {
console.log('EEEERRRRROOOOOOR', file_names);
return; // Error
}
await rename_file(ip, $current_file_path, file_names[0], new_file_name);
});
await update_current_folder_on_selected_displays();
popup_close_function();
}
const show_edit_file_popup = async () => {
const file = await get_file_by_id($selected_file_ids[0]);
if (!file) return;
const is_folder = file.type === 'inode/directory';
const extension = is_folder ? '' : '.' + file.name.split('.').at(-1) || '';
current_name = file.name.slice(0, file.name.length - extension.length);
current_valid = true;
popup_content = {
open: true,
snippet: edit_file_name_popup,
title: `${is_folder ? 'Ordner' : 'Datei'} umbenennen`,
title_icon: FolderPlus,
snippet_arg: extension,
closable: true
};
};
const show_new_folder_popup = async () => {
current_name = '';
current_valid = false;
display_names_where_path_does_not_exist = (
await get_displays_where_path_exists($current_file_path, $selected_display_ids, true)
).map((display) => display.name);
popup_content = {
open: true,
snippet: new_folder_popup,
title: 'Neuen Ordner erstellen',
title_icon: FolderPlus,
closable: true
};
};
const delete_folder_element_popup = () => {
popup_content = {
open: true,
snippet: delete_request_popup,
title: `${$selected_file_ids.length} ${$selected_file_ids.length === 1 ? 'Objekt' : 'Objekte'} wirklich löschen?`,
title_icon: Trash2,
closable: true
};
};
</script>
{#snippet new_folder_popup()}
{#if display_names_where_path_does_not_exist.length > 0}
<span class="leading-relaxed"
>Der aktuelle Pfad <HighlightedText
>{$current_file_path.slice(0, $current_file_path.length - 1)}</HighlightedText
> existiert nicht auf {display_names_where_path_does_not_exist.length === 1
? 'dem Bildschirm'
: 'den Bildschirmen'}
{#each display_names_where_path_does_not_exist as display_name, i}
{#if i !== 0}
,
{/if}
<HighlightedText>{display_name}</HighlightedText>
{/each}. Mit der Erstellung dieses Ordners wird der Pfad automatisch mit leeren Ordnern bis
zum aktuellen Pfad aufgefüllt.
</span>
{/if}
<TextInput
focused_on_start={true}
bind:current_value={current_name}
bind:current_valid
title="Ordnername"
is_valid_function={async (input: string) => {
if (input.startsWith('.')) return [false, 'Name darf nicht mit . beginnen'];
const trimmed_input = input.trim();
if (trimmed_input.length === 0 || trimmed_input.length > 50)
return [false, 'Ungültige Länge'];
if (!is_valid_name(trimmed_input)) return [false, 'Name enthält ungültige Zeichen'];
if (
(await get_current_folder_elements($current_file_path, $selected_display_ids)).some(
(e) => e.name === trimmed_input
)
)
return [false, 'Name bereits verwendet'];
return [true, 'Gültiger Name'];
}}
enter_mode="submit"
enter_function={create_new_folder}
/>
<div class="flex flex-row justify-end gap-2">
<Button className="px-4 font-bold" click_function={create_new_folder} disabled={!current_valid}
>Neuen Ordner erstellen</Button
>
</div>
{/snippet}
{#snippet edit_file_name_popup(extension: string)}
<TextInput
focused_on_start={true}
bind:current_value={current_name}
bind:current_valid
title="Neuer {extension === '' ? 'Ordner' : 'Datei'}name"
is_valid_function={async (input: string) => {
if (input.startsWith('.')) return [false, 'Name darf nicht mit . beginnen'];
const trimmed_input = input.trim() + extension;
if (trimmed_input.length === 0 || trimmed_input.length > 50)
return [false, 'Ungültige Länge'];
if (!is_valid_name(trimmed_input)) return [false, 'Name enthält ungültige Zeichen'];
if (
(await get_current_folder_elements($current_file_path, $selected_display_ids)).some(
async (e) => e.name === trimmed_input && get_file_primary_key(e) !== $selected_file_ids[0]
)
)
return [false, 'Name bereits verwendet'];
return [true, 'Gültiger Name'];
}}
enter_mode="submit"
enter_function={async () => await edit_file_name(current_name.trim() + extension)}
{extension}
/>
<div class="flex flex-row justify-end gap-2">
<Button
className="px-4 font-bold"
click_function={async () => await edit_file_name(current_name.trim() + extension)}
disabled={!current_valid}>{extension === '' ? 'Ordner' : 'Datei'} umbenennen</Button
>
</div>
{/snippet}
{#snippet delete_request_popup()}
<div class="flex flex-col gap-1 h-full min-h-0 grow-0">
<span class="text-stone-400 px-1"
>{`${$selected_file_ids.length === 1 ? 'Folgendes Objekt' : `Folgende ${$selected_file_ids.length} Objekte`} löschen? (Wiederherstellung nicht möglich)`}</span
>
<div class="flex flex-col gap-2 overflow-auto h-full min-h-0 grow-0">
{#each $selected_files || [] as file}
<InodeElement {file} not_interactable />
{/each}
</div>
</div>
<div class="flex flex-row justify-end gap-2">
<Button className="px-4 font-bold" click_function={popup_close_function}>Abbrechen</Button>
<Button
hover_bg="bg-red-400"
active_bg="bg-red-500"
className="px-4 flex text-red-400 hover:text-stone-100"
click_function={async () => {
await run_for_selected_files_on_selected_displays(
async (ip: string, file_names: string[]) => {
await delete_files(ip, $current_file_path, file_names);
}
);
await update_current_folder_on_selected_displays();
popup_close_function();
}}>Löschen</Button
>
</div>
{/snippet}
<div class="bg-stone-800 h-full rounded-2xl grid grid-rows-[2.5rem_1fr] min-h-0">
<div class="bg-stone-700 flex justify-between w-full p-1 rounded-t-2xl min-w-0 gap-2">
<span class="text-xl font-bold pl-2 content-center truncate min-w-0">
Dateien anzeigen und verwalten
</span>
<div class="flex flex-ro">
<Button
title="Dateien größer darstellen"
className="aspect-square !p-1 rounded-r-none"
bg="bg-stone-600"
disabled={!Boolean(next_height_step_size('file', $current_height, 1))}
click_function={() => {
change_height('file', 1);
}}
>
<ZoomIn />
</Button>
<Button
title="Dateien kleiner darstellen"
className="aspect-square !p-1 rounded-l-none"
bg="bg-stone-600"
disabled={!Boolean(next_height_step_size('file', $current_height, -1))}
click_function={() => {
change_height('file', -1);
}}
>
<ZoomOut />
</Button>
</div>
</div>
<div class="flex flex-col gap-2 p-2 overflow-hidden relative rounded-b-2xl">
<div class="flex flex-col gap-2 p-2 bg-stone-750 rounded-xl">
<PathBar />
<div class="flex flex-row justify-between gap-6">
<div class="flex flex-row gap-2 shrink-0">
<Button
title="Neuen Ordner erstellen (Neuen Ordner mit ausgewählten Objekten erstellen)"
className="px-3 flex"
click_function={show_new_folder_popup}
disabled={$selected_display_ids.length === 0}><FolderPlus /></Button
>
<div class="border border-stone-700 my-1"></div>
<Button
title="Datei(en) hochladen"
className="px-3 flex"
disabled={$selected_display_ids.length === 0}><Upload /></Button
>
<Button
title="Ausgewählte Datei(en) herunterladen"
className="px-3 flex"
disabled={$selected_file_ids.length === 0}><Download /></Button
>
<div class="border border-stone-700 my-1"></div>
<Button
title="Aktuellen Ordner / Ausgewählte Datei(en) zwischen Bildschirmen synchronisieren"
className="px-3 flex gap-3"
disabled={$selected_display_ids.length === 0}
><RefreshCcw />
<span class="hidden 2xl:flex">Synchronisieren</span>
</Button>
</div>
<div class="flex flex-row gap-2">
<Button
title="Ausgewählte Datei(en) ausschneiden"
className="px-3 flex"
disabled={$selected_file_ids.length === 0}><Scissors /></Button
>
<Button
title="Ausgewählte Datei(en) einfügen"
className="px-3 flex"
disabled={$selected_display_ids.length === 0}
>
<ClipboardPaste />
</Button>
<div class="border border-stone-700 my-1"></div>
<Button
title="Ausgewählte Datei umbenennen"
className="px-3 flex"
click_function={show_edit_file_popup}
disabled={$selected_file_ids.length !== 1}><Pen /></Button
>
<Button
title="Ausgewählte Datei(en) löschen"
hover_bg="bg-red-400"
active_bg="bg-red-500"
className="px-3 flex"
disabled={$selected_file_ids.length === 0}
click_function={delete_folder_element_popup}><Trash2 /></Button
>
</div>
</div>
</div>
<div class="min-h-0 h-full overflow-y-auto bg-stone-750 rounded-xl">
<div class="flex flex-col gap-2 p-2 min-h-0 max-w-full">
{#if $selected_display_ids.length === 0}
<span class="text-stone-450 px-10 py-6 leading-relaxed text-center">
Es sind keine Bildschirme ausgewählt.
</span>
{:else}
{#each $current_folder_elements || [] as folder_element (get_file_primary_key(folder_element))}
<section in:slide={{ duration: 100 }} class="outline-none">
<InodeElement file={folder_element} />
</section>
{/each}
{#if ($current_folder_elements || []).length === 0}
<span class="text-stone-450 px-10 py-6 leading-relaxed text-center max-w-full">
Es existieren keine Dateien auf {$selected_display_ids.length === 1
? 'dem ausgewähltem Bildchirm'
: 'den ausgewählten Bildschirmen'} im aktuellen Ordner. Klicke auf <HighlightedText
bg="bg-stone-700"
fg="text-stone-400"
className="!p-1"><Upload class="inline pb-1" /></HighlightedText
> um Datei(en) hochzuladen.
</span>
{/if}
{/if}
</div>
</div>
<PopUp
content={popup_content}
close_function={popup_close_function}
className="rounded-b-2xl"
snippet_container_class="overflow-hidden min-w-90"
/>
</div>
</div>
@@ -0,0 +1,19 @@
<script lang="ts">
let {
children,
bg = 'bg-stone-750',
fg = 'text-stone-200',
className = ''
}: {
children: any;
bg?: string;
fg?: string;
className?: string;
} = $props();
</script>
<div
class="{bg} {fg} {className} rounded-lg py-0.5 px-1 inline-block truncate min-w-0 max-w-full align-middle my-[1.5px]"
>
{@render children()}
</div>
+248
View File
@@ -0,0 +1,248 @@
<script lang="ts">
import { ArrowRight, Ban, FileIcon, Folder, Play } from 'lucide-svelte';
import {
current_height,
get_selectable_color_classes,
get_shifted_color
} from '$lib/ts/stores/ui_behavior';
import Button from './Button.svelte';
import { supported_file_type_icon, type Inode, get_file_primary_key } from '$lib/ts/types';
import {
is_selected,
select,
selected_display_ids,
selected_file_ids
} from '$lib/ts/stores/select';
import {
change_file_path,
current_file_path,
get_missing_colliding_display_ids
} from '$lib/ts/stores/files';
import RefreshPlay from './RefreshPlay.svelte';
import { get_file_size_display_string, get_file_type } from '$lib/ts/utils';
import { open_file } from '$lib/ts/api_handler';
import { run_on_all_selected_displays } from '$lib/ts/stores/displays';
import { get_thumbnail_url } from '$lib/ts/stores/thumbnails';
import { liveQuery } from 'dexie';
let { file, not_interactable = false }: { file: Inode; not_interactable?: boolean } = $props();
let missing_colliding_displays_ids = liveQuery(() =>
get_missing_colliding_display_ids(file, $selected_display_ids)
);
let thumbnail_url = liveQuery(() => get_thumbnail_url(file));
const is_folder = file.type === 'inode/directory';
function get_created_string(date_object: Date | null, full_string = false) {
if (!date_object) {
return full_string ? 'Verschiedene Daten auf verschiedenen Bildschirmen' : 'versch.';
}
if (full_string) {
return (
get_formated_date_string(date_object, true) + ' ' + get_formated_time_string(date_object)
);
} else if (date_object.toDateString() === new Date().toDateString()) {
return get_formated_time_string(date_object);
} else {
return get_formated_date_string(date_object);
}
}
function get_formated_time_string(date_object: Date) {
return `${date_object.getHours().toString().padStart(2, '0')}:${date_object.getMinutes().toString().padStart(2, '0')}`;
}
function get_formated_date_string(date_object: Date, full_year = false) {
return `${date_object.getDate().toString().padStart(2, '0')}.${(date_object.getMonth() + 1).toString().padStart(2, '0')}.${date_object
.getFullYear()
.toString()
.slice(full_year ? 0 : 2)}`;
}
function get_grayed_out_text_color_strings(is_selected: boolean): string {
if (not_interactable) return 'text-stone-400';
const color = is_selected ? 'text-stone-600' : 'text-stone-400';
const factor = is_selected ? -1 : 1;
return `${color} group-hover:${get_shifted_color(color, factor * 100)} group-active:${get_shifted_color(color, factor * 150)}`;
}
function get_grayed_out_border_color_strings(is_selected: boolean): string {
if (not_interactable) return 'border-stone-550';
const color = is_selected ? 'border-stone-450' : 'border-stone-550';
const factor = is_selected ? 1 : 1;
return `${color} group-hover:${get_shifted_color(color, factor * 100)} group-active:${get_shifted_color(color, factor * 150)}`;
}
function onclick(e: Event) {
if (not_interactable) return;
select(selected_file_ids, get_file_primary_key(file), 'toggle');
e.stopPropagation();
}
async function open() {
if (is_folder) {
await change_file_path($current_file_path + file.name + '/');
} else {
const path_to_file = $current_file_path + file.name;
await run_on_all_selected_displays(open_file, true, path_to_file);
}
}
</script>
<div data-testid="inode" class="flex flex-row h-{$current_height.file} w-full">
{#if !not_interactable}
<div class="h-{$current_height.file} aspect-square max-w-15 flex">
<Button
disabled={!is_folder && get_file_type(file) === null}
title={!is_folder && get_file_type(file) === null ? 'Dateityp nicht unterstützt' : ''}
className="flex rounded-l-lg rounded-r-none {is_folder
? 'text-stone-450'
: 'text-stone-800'} w-full"
div_class="w-full"
bg={get_selectable_color_classes(
!is_folder && get_file_type(file) !== null,
{
bg: true
},
-50
)}
hover_bg={get_selectable_color_classes(
!is_folder,
{
bg: true
},
50
)}
active_bg={get_selectable_color_classes(
!is_folder,
{
bg: true
},
100
)}
click_function={(e) => {
open();
e.stopPropagation();
}}
>
{#if is_folder}
<ArrowRight class="size-full" strokeWidth="3" />
{:else if $missing_colliding_displays_ids && $missing_colliding_displays_ids.missing.length !== 0}
<RefreshPlay className="size-full" />
{:else if get_file_type(file) !== null}
<Play class="size-full" strokeWidth="3" />
{:else}
<Ban class="size-full" strokeWidth="3" />
{/if}
</Button>
</div>
{/if}
<div
role="button"
tabindex="0"
onkeydown={(e) => {
if (e.key === 'Enter' || e.key === ' ') onclick(e);
}}
{onclick}
class="{get_selectable_color_classes(
!not_interactable && is_selected(get_file_primary_key(file), $selected_file_ids),
{
bg: true,
hover: !not_interactable,
active: !not_interactable,
text: true
}
)} {not_interactable
? 'rounded-lg'
: 'rounded-r-lg cursor-pointer'} transition-colors duration-200 gap-4 flex flex-row justify-between group w-full min-w-0"
>
<div class="flex flex-row gap-2 min-w-0 w-full">
<div class="aspect-square rounded-md flex justify-center items-center">
{#if is_folder}
<Folder class="size-full p-2" />
{:else if $thumbnail_url || null}
<img
src={$thumbnail_url || null}
alt="file_thumbnail"
class="object-contain size-full select-none block p-1 rounded-lg"
draggable="false"
/>
{:else if supported_file_type_icon[get_file_type(file)?.display_name || '']}
{@const Icon = supported_file_type_icon[get_file_type(file)?.display_name || '']}
<Icon class="size-full p-2" />
{:else}
<FileIcon class="size-full p-2" />
{/if}
</div>
<div class="content-center truncate select-none w-full" title={file.name}>
{file.name.includes('.') && !is_folder && get_file_type(file)
? file.name.slice(0, file.name.lastIndexOf('.'))
: file.name}
</div>
</div>
<div
class=" p-1 flex flex-row items-center gap-1 pr-1 {get_grayed_out_text_color_strings(
is_selected(get_file_primary_key(file), $selected_file_ids)
)} duration-200 transition-colors"
>
<!-- {#if get_display_ids_where_file_is_missing($current_file_path, file, $selected_display_ids, $all_files)[1].length !== 0}
<Button
className="h-8 aspect-square transition-colors duration-200 !p-1.5 text-stone-100"
bg="bg-red-500"
click_function={(e) => {
e.stopPropagation();
}}
>
<TriangleAlert class="size-full" />
</Button>
{:else if get_display_ids_where_file_is_missing($current_file_path, file, $selected_display_ids, $all_files)[0].length !== 0}
<Button
className="h-8 aspect-square transition-colors duration-200 !p-1.5"
bg="bg-transparent"
hover_bg={get_selectable_color_classes(false, {
bg: true
})}
active_bg={get_selectable_color_classes(false, {
bg: true
})}
click_function={(e) => {
e.stopPropagation();
}}
>
<RefreshCcwDot class="size-full" />
</Button>
{/if} -->
<div
class="w-14 content-center text-center select-none text-xs whitespace-nowrap"
title={get_created_string(file.date_created, true)}
>
{get_created_string(file.date_created)}
</div>
<div
class="h-[70%] border {get_grayed_out_border_color_strings(
is_selected(get_file_primary_key(file), $selected_file_ids)
)} duration-200 transition-colors my-1"
></div>
<div
class="w-12 content-center text-center select-none text-xs whitespace-nowrap truncate"
title={file.type}
>
{is_folder ? 'Ordner' : (get_file_type(file)?.display_name ?? '?')}
</div>
<div
class="h-[70%] border {get_grayed_out_border_color_strings(
is_selected(get_file_primary_key(file), $selected_file_ids)
)} duration-200 transition-colors"
></div>
<div
class="w-12 content-center text-center select-none text-xs whitespace-nowrap"
title={get_file_size_display_string(file.size, 3)}
>
{get_file_size_display_string(file.size)}
</div>
</div>
</div>
</div>
@@ -0,0 +1,72 @@
<script lang="ts">
import { flip } from 'svelte/animate';
import { get_selectable_color_classes } from '$lib/ts/stores/ui_behavior';
import key_map_json from './../../../../../shared/keys.json';
import { fade } from 'svelte/transition';
import { run_on_all_selected_displays } from '$lib/ts/stores/displays';
import { send_keyboard_input } from '$lib/ts/api_handler';
const key_map: Record<string, string> = key_map_json as Record<string, string>;
let active = $state(false);
let last_keys: { id: number; key: string }[] = $state([]);
let el: HTMLDivElement;
function add_to_last_keys(name: string) {
const id = Date.now();
last_keys.push({ id, key: name });
setTimeout(() => {
last_keys = last_keys.filter((e) => e.id !== id);
}, 1500);
}
async function on_key_down(e: KeyboardEvent) {
if (!active) return;
const id = key_map[e.code];
if (!id) return;
e.preventDefault();
e.stopPropagation();
add_to_last_keys(e.code);
if (e.repeat) return;
await run_on_all_selected_displays(send_keyboard_input, true, id);
}
</script>
<div
role="textbox"
tabindex="0"
bind:this={el}
onclick={() => {
if (active) {
el.blur();
} else {
el.focus();
active = true;
}
}}
onblur={() => (active = false)}
onkeydown={on_key_down}
class="relative flex justify-center items-center h-15 w-full cursor-pointer rounded-xl transition-colors duration-200 select-none {get_selectable_color_classes(
active,
{
bg: true,
hover: true,
active: true,
text: true
}
)}"
>
{active ? 'Erfassung aktiv' : 'Hier für Erfassung klicken'}
<div class="absolute top-full left-0 ml-1 mt-0.5 flex flex-col-reverse text-sm text-stone-400">
{#each last_keys as key (key.id)}
<span
animate:flip={{ duration: 200 }}
in:fade={{ duration: 200 }}
out:fade={{ duration: 500 }}>{key.key}</span
>
{/each}
</div>
</div>
@@ -0,0 +1,54 @@
<script lang="ts">
import { fade } from 'svelte/transition';
import Button from './Button.svelte';
import { X } from 'lucide-svelte';
import { notifications } from '$lib/ts/stores/notification';
</script>
<div
data-testid="notification"
class="fixed flex flex-col gap-2 top-[41%] right-2 left-2 md:top-auto md:left-auto md:bottom-2 md:w-100 z-50"
>
{#each $notifications as n (n.id)}
<div
transition:fade={{ duration: 200 }}
class="p-2 pl-4 pb-3 rounded-lg shadow-xl/30 text-white flex flex-col gap-2 overflow-hidden relative border border-black/20 {n.className}"
class:bg-red-900={n.type === 'error'}
class:bg-green-900={n.type === 'success'}
class:bg-sky-900={n.type === 'info'}
style="--dur: {n.duration}ms"
>
<div class="flex flex-row justify-between">
<span class="text-xl font-bold flex items-center">{n.title}</span>
<Button
click_function={() => notifications.remove(n.id)}
className="p-2"
bg="bg-stone-900/50"
hover_bg="bg-stone-600/70"
active_bg="bg-stone-500/80"><X /></Button
>
</div>
<span class="whitespace-break-spaces">{n.message}</span>
<div class="absolute inset-x-0 bottom-0 h-1 bg-white/25">
<div class="block h-full w-full bg-white/80 origin-left animate-progress-bar"></div>
</div>
</div>
{/each}
</div>
<style>
@keyframes progress {
from {
transform: scaleX(0);
}
to {
transform: scaleX(1);
}
}
.animate-progress-bar {
animation: progress var(--dur) linear forwards;
transform-origin: left;
}
</style>
@@ -0,0 +1,31 @@
<script lang="ts">
import { type DisplayStatus } from '$lib/ts/types';
import { display_status_to_info } from '$lib/ts/utils';
let {
selected,
status,
className = ''
}: {
selected: boolean;
status: DisplayStatus;
className?: string;
} = $props();
function get_text_color(selected: boolean, status: DisplayStatus) {
switch (status) {
case 'app_online':
return selected ? 'text-green-700' : 'text-green-400';
case 'app_offline':
return selected ? 'text-amber-700' : 'text-amber-400';
case 'host_offline':
return selected ? 'text-red-700' : 'text-red-400';
default:
return selected ? 'text-stone-700' : 'text-stone-400';
}
}
</script>
<div class="{get_text_color(selected, status)} {className} transition-colors duration-100">
{display_status_to_info(status)}
</div>
@@ -0,0 +1,164 @@
<script lang="ts">
import { ChevronRight, House } from 'lucide-svelte';
import Button from './Button.svelte';
import { onDestroy, onMount } from 'svelte';
import type { MenuOption } from '$lib/ts/types';
import { change_file_path, current_file_path } from '$lib/ts/stores/files';
import { flip } from 'svelte/animate';
import { cubicOut } from 'svelte/easing';
let {
bg = 'bg-stone-700'
}: {
bg?: string;
} = $props();
let outside_container: HTMLDivElement;
let inside_container: HTMLDivElement;
let resize_observer: ResizeObserver;
let w10_div: HTMLDivElement;
let cut_folders: number = $state(0);
// let folders_length: number = $state(get_folders($current_file_path).length);
// let all_folders_length: number = $state(get_folders($current_file_path).length);
function get_folders(path: string): string[] {
path = path.slice(1); // Cut first '/'
if (path === '') return [];
if (path.endsWith('/')) {
path = path.slice(0, path.length - 1);
}
return path.split('/');
}
function get_sliced_folders(path: string, cut_folders: number): string[] {
const folders = get_folders(path);
let sliced_folders: string[] = [];
if (cut_folders !== get_folders($current_file_path).length)
sliced_folders = folders.slice(cut_folders);
return sliced_folders;
}
function get_hidden_folders(path: string, cut_folders: number): string[] {
const folders = get_folders(path);
let hidden_folders: string[] = [];
if (cut_folders !== get_folders($current_file_path).length)
hidden_folders = folders.slice(0, cut_folders);
return hidden_folders;
}
function recalc() {
if (!outside_container || !inside_container || !w10_div) return;
const first_shrink = cut_folders === 0;
const second_last_grow = cut_folders === 2;
const difference = outside_container.offsetWidth - inside_container.offsetWidth;
const w10_px = parseFloat(getComputedStyle(w10_div).width);
if ((!first_shrink && difference < 2 * w10_px) || (first_shrink && difference < w10_px)) {
if (cut_folders < get_folders($current_file_path).length) {
cut_folders += first_shrink ? 2 : 1;
}
} else if (
(!second_last_grow && difference > 6 * w10_px) ||
(second_last_grow && difference > 7 * w10_px)
) {
if (cut_folders >= 1) {
if (second_last_grow) {
cut_folders -= 2;
} else {
cut_folders -= 1;
}
}
}
}
function get_hidden_menu_options(hidden_folders: string[], path: string): MenuOption[] {
const out: MenuOption[] = [];
for (let i = 0; i < hidden_folders.length; i++) {
out.push({
name: '  '.repeat(i) + hidden_folders[i],
class: 'truncate max-w-80',
on_select: async () => {
await open_path(i + 1, path);
}
});
}
return out;
}
async function open_path(index_of_all_folders: number, path: string) {
let new_path = '/';
const all_folders = get_folders(path);
for (let i = 0; i < index_of_all_folders; i++) {
new_path += all_folders[i] + '/';
}
await change_file_path(new_path);
}
onMount(() => {
resize_observer = new ResizeObserver(() => recalc());
resize_observer.observe(outside_container);
resize_observer.observe(inside_container);
// initial
setTimeout(recalc, 0);
});
onDestroy(() => resize_observer?.disconnect());
</script>
<div class="{bg} rounded-xl flex" bind:this={outside_container}>
<div class="flex flex-row">
<div class="flex flex-row">
<div bind:this={w10_div} class="flex">
<Button
className="py-1 shrink-0 grow-0 w-10"
{bg}
click_function={async () => {
await open_path(0, $current_file_path);
}}
>
<House
class="size-full transition-all duration-100"
strokeWidth={$current_file_path === '/' ? 2.7 : 2}
/>
</Button>
</div>
{#if cut_folders !== 0}
<Button
className="pl-0 py-1 grow"
{bg}
menu_options={get_hidden_menu_options(
get_hidden_folders($current_file_path, cut_folders),
$current_file_path
)}
menu_class="left-0"
>
<ChevronRight class="shrink-0 text-stone-500 h-full" />
<span class="font-bold" title="Weiteren Pfad zeigen"> ... </span>
</Button>
{/if}
</div>
<div class="flex flex-row" bind:this={inside_container}>
{#each get_sliced_folders($current_file_path, cut_folders) as folder, i (i)}
<div animate:flip={{ duration: 100, easing: cubicOut }}>
<Button
className="shrink-0 py-1 pl-0 {i ===
get_sliced_folders($current_file_path, cut_folders).length - 1
? 'max-w-80 font-bold'
: 'max-w-30'}"
{bg}
click_function={async () => {
await open_path(cut_folders + i + 1, $current_file_path);
}}
>
<ChevronRight class="shrink-0 text-stone-500 h-full" />
<span class="truncate" title={folder}>
{folder}
</span>
</Button>
</div>
{/each}
</div>
</div>
</div>
@@ -0,0 +1,80 @@
<script lang="ts">
import { X } from 'lucide-svelte';
import Button from './Button.svelte';
import type { PopupContent } from '$lib/ts/types';
import { fade } from 'svelte/transition';
import { onMount } from 'svelte';
let {
content,
close_function,
className = '',
snippet_container_class = ''
}: {
content: PopupContent;
close_function: () => void;
className?: string;
snippet_container_class?: string;
} = $props();
function try_to_close() {
if (!content.closable || !content.open) return;
close_function();
}
function handleKeydown(e: KeyboardEvent) {
if (e.key === 'Escape') {
try_to_close();
}
}
onMount(() => {
window.addEventListener('keydown', handleKeydown);
return () => window.removeEventListener('keydown', handleKeydown);
});
</script>
{#if content.open}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<!-- svelte-ignore a11y_click_events_have_key_events -->
<div
class="absolute inset-0 backdrop-blur flex justify-center items-center {className}"
onclick={try_to_close}
transition:fade={{ duration: 100 }}
>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<!-- svelte-ignore a11y_click_events_have_key_events -->
<div
class="bg-stone-800 rounded-2xl min-w-[30%] max-w-[90%] max-h-[85%] flex flex-col shadow-2xl/60 overflow-hidden {content.window_class ??
''}"
onclick={(e) => e.stopPropagation()}
>
{#if content.title}
<div class="font-bold bg-stone-700 p-1.5 flex flex-row justify-between gap-8 w-full">
<div
class="flex flex-row flex-1 gap-3 pl-2 py-1 items-center grow whitespace-nowrap min-w-0 flex-shrink-0 text-lg {content.title_class ??
''}"
>
{#if content.title_icon}
{@const Icon = content.title_icon}
<Icon strokeWidth="2" class="flex-shrink-0" />
{/if}
<div class="flex-shrink-0">
{content.title}
</div>
</div>
<div class="flex aspect-square flex-shrink-0">
{#if content.closable}
<Button className="aspect-square !p-1.5" click_function={try_to_close}>
<X />
</Button>
{/if}
</div>
</div>
{/if}
<div class="p-2 min-h-0 overflow-auto flex flex-col gap-2 {snippet_container_class}">
{@render content.snippet(content.snippet_arg)}
</div>
</div>
</div>
{/if}
@@ -0,0 +1,25 @@
<script lang="ts">
let { className = '' }: { className?: string } = $props();
</script>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2.7"
stroke-linecap="round"
stroke-linejoin="round"
class="{className} lucide lucide-refresh-ccw-dot-icon lucide-refresh-ccw-dot"
>
<path d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
<path d="M3 3v5h5" />
<path d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16" />
<path d="M16 16h5v5" />
<path
d="M15.033 9.44a.647.647 0 0 1 0 1.12l-4.065 2.352a.645.645 0 0 1-.968-.56V7.648a.645.645 0 0 1 .967-.56z"
transform="translate(0,2.0)"
/>
</svg>
@@ -0,0 +1,134 @@
<script lang="ts">
import { fade } from 'svelte/transition';
import { get_shifted_color } from '$lib/ts/stores/ui_behavior';
import { onMount } from 'svelte';
import { selected_display_ids } from '$lib/ts/stores/select';
let {
current_value = $bindable(),
current_valid = $bindable(),
className = '',
bg = 'bg-stone-750',
title,
placeholder = '',
is_valid_function = null,
focused_on_start = false,
extension = null,
enter_mode = 'none',
enter_function = null
}: {
current_value: string;
current_valid: boolean;
className?: string;
bg?: string;
title: string;
placeholder?: string;
is_valid_function?: ((input: string) => [boolean, string] | Promise<[boolean, string]>) | null;
focused_on_start?: boolean;
extension?: string | null;
enter_mode?: 'none' | 'focus_next' | 'submit';
enter_function?: (() => void) | null;
} = $props();
let focus_bg = get_shifted_color(bg, 100);
let focused: boolean = $state(false);
let current_info = $state('');
let input_element: HTMLInputElement;
async function validate_input() {
if (!is_valid_function) return;
[current_valid, current_info] = await is_valid_function(current_value.trim());
}
function get_highlighting_string(): string {
if (!is_valid_function) return '';
if (current_valid) {
return 'focus-within:inset-ring-2 focus-within:inset-ring-green-400';
} else {
return 'inset-ring-2 inset-ring-red-400';
}
}
function focus_next_element() {
const focusable = Array.from(document.querySelectorAll<HTMLElement>('input')).filter(
(el) => !el.hasAttribute('disabled')
);
const index = focusable.indexOf(input_element);
if (index !== -1 && index < focusable.length - 1) {
focusable[index + 1].focus();
}
}
function handle_keydown(event: KeyboardEvent) {
if (event.key !== 'Enter') return;
if (enter_mode === 'focus_next') {
event.preventDefault();
focus_next_element();
} else if (enter_mode === 'submit' && enter_function) {
event.preventDefault();
enter_function();
}
}
onMount(async () => {
await validate_input();
if (focused_on_start && input_element) input_element.focus();
selected_display_ids.subscribe(async () => {
await validate_input();
});
});
</script>
<div class="flex flex-col {className} relative">
<div class="flex flex-row justify-between text-sm px-1 gap-4">
<div class="text-stone-400">
{title}:
</div>
{#if is_valid_function && focused}
<div
class={current_valid ? 'text-green-400' : 'text-red-400'}
transition:fade={{ duration: 100 }}
>
{current_info}
</div>
{/if}
</div>
<!-- <input
bind:this={input_element}
bind:value={current_value}
bind:focused
onkeydown={handle_keydown}
type="text"
oninput={validate_input}
class="{bg} focus:{focus_bg} outline-none py-2 px-3 rounded-xl transition-all duration-100 {get_highlighting_string()}"
{placeholder}
/> -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<!-- svelte-ignore a11y_click_events_have_key_events -->
<div
onclick={() => {
input_element.focus();
}}
class="{bg} focus-within:{focus_bg} flex items-center rounded-xl {get_highlighting_string()} cursor-text"
>
<input
bind:this={input_element}
bind:value={current_value}
bind:focused
onkeydown={handle_keydown}
oninput={validate_input}
type="text"
class=" outline-none py-2 px-3 transition-all duration-100 flex-grow group"
{placeholder}
/>
{#if extension}
<span class="pr-3 text-stone-400 select-none pointer-events-none">
{extension}
</span>
{/if}
</div>
</div>
@@ -0,0 +1,255 @@
<script lang="ts">
import { onMount, onDestroy } from 'svelte';
import { Editor } from '@tiptap/core';
import { StarterKit } from '@tiptap/starter-kit';
import Placeholder from '@tiptap/extension-placeholder';
import {
Baseline,
Bold,
Highlighter,
Italic,
PaintBucket,
QrCode,
Strikethrough
} from 'lucide-svelte';
import Button from './Button.svelte';
import { run_on_all_selected_displays } from '$lib/ts/stores/displays';
import { show_html } from '$lib/ts/api_handler';
import { get_selectable_color_classes } from '$lib/ts/stores/ui_behavior';
import { TextStyle } from '@tiptap/extension-text-style';
import { Color } from '@tiptap/extension-text-style';
import Highlight from '@tiptap/extension-highlight';
type TextEditOption = {
onclick: () => void;
is_selected: () => boolean;
icon: typeof Bold;
title: string;
color?: ColorElement;
};
type ColorElement = {
color_string: () => string;
color_picker: () => void;
};
type ColorState = {
el: HTMLInputElement | null;
value: string;
};
let element = $state<HTMLElement>();
let editor_state = $state<{ editor: Editor | null }>({ editor: null });
let color_states: { text: ColorState; highlight: ColorState; bg: ColorState } = $state({
text: { el: null, value: '#b91c1c' },
highlight: { el: null, value: '#0c4a6e' },
bg: { el: null, value: '#1c1917' }
});
const text_edit_options: TextEditOption[][] = [
[
{
onclick: () => editor_state.editor?.chain().focus().toggleBold().run(),
is_selected: () => editor_state.editor?.isActive('bold') ?? false,
title: 'Fett (STRG+B)',
icon: Bold
},
{
onclick: () => editor_state.editor?.chain().focus().toggleItalic().run(),
is_selected: () => editor_state.editor?.isActive('italic') ?? false,
title: 'Kursiv (STRG+I)',
icon: Italic
},
{
onclick: () => editor_state.editor?.chain().focus().toggleStrike().run(),
is_selected: () => editor_state.editor?.isActive('strike') ?? false,
title: 'Durchgestrichen',
icon: Strikethrough
},
{
onclick: () => {},
is_selected: () => false,
title: 'QR-Code anfügen',
icon: QrCode
}
],
[
{
onclick: () => editor_state.editor?.chain().focus().setColor(color_states.text.value).run(),
is_selected: () =>
editor_state.editor?.isActive('textStyle', { color: color_states.text.value }) ?? false,
icon: Baseline,
title: 'Textfarbe',
color: get_color_element(color_states.text)
},
{
onclick: () =>
editor_state.editor
?.chain()
.focus()
.toggleHighlight({ color: color_states.highlight.value })
.run(),
is_selected: () =>
editor_state.editor?.isActive('highlight', { color: color_states.highlight.value }) ??
false,
icon: Highlighter,
title: 'Markierungsfarbe',
color: get_color_element(color_states.highlight)
},
{
onclick: () => color_states.bg.el?.click(),
is_selected: () => false,
title: 'Hintergrundfarbe',
icon: PaintBucket
}
]
];
function get_color_element(color_state: ColorState) {
return {
color_string: () => color_state.value,
color_picker: () => color_state.el?.click()
};
}
async function show_text() {
const html =
editor_state.editor?.getHTML() +
`<style>:root {--background-color: ${color_states.bg.value} !important;}
</style>`;
await run_on_all_selected_displays(show_html, true, html);
}
onMount(() => {
editor_state.editor = new Editor({
element: element,
extensions: [
StarterKit,
Placeholder.configure({
placeholder: 'Text hier eingeben ...'
}),
TextStyle,
Color,
Highlight.configure({
multicolor: true
})
],
content: '',
onTransaction: ({ editor }) => {
// Increment the state signal to force a re-render
editor_state = { editor };
},
autofocus: true
});
});
onDestroy(() => {
editor_state.editor?.destroy();
});
</script>
{#each Object.values(color_states) as color_state}
<input type="color" bind:this={color_state.el} bind:value={color_state.value} class="hidden" />
{/each}
<div data-testid="text-popup" class="flex flex-row gap-2 size-full">
<div
class="rounded-xl size-full shrink min-w-0 flex"
style="background-color: {color_states.bg.value};"
>
<div bind:this={element} class="size-full overflow-auto px-3 py-2"></div>
</div>
<div class="flex flex-col gap-2 justify-between">
<div class="flex flex-col gap-2">
{#each text_edit_options as edit_row}
<div class="flex flex-row gap-1">
{#each edit_row as option}
<div class="flex flex-row">
<button
title={option.title}
onclick={option.onclick}
class="p-1 {option.color
? 'rounded-l-xl'
: 'rounded-xl'} cursor-pointer duration-200 transition-colors {get_selectable_color_classes(
option.is_selected(),
{
bg: true,
hover: true,
active: true,
text: true
},
-100,
50
)}"
>
{#if option.icon}
{@const Icon = option.icon}
<Icon class="h-7 w-7" />
{/if}
</button>
{#if option.color}
<button
aria-label="Color"
onclick={option.color.color_picker}
title={option.title}
class="flex p-1 rounded-r-xl cursor-pointer duration-200 transition-colors justify-center items-center {get_selectable_color_classes(
option.is_selected(),
{
bg: true,
hover: true,
active: true,
text: true
},
-100,
50
)}"
>
<span
class="h-7 w-3 rounded-full"
style="background-color: {option.color.color_string()};"
></span>
</button>
{/if}
</div>
{/each}
</div>
{/each}
</div>
<Button click_function={show_text} className="w-full font-bold">Text anzeigen</Button>
</div>
</div>
<style>
:global(.tiptap) {
width: 100%;
height: 100%;
--tw-outline-style: none;
outline-style: none;
}
:global(.tiptap ul),
:global(.tiptap ol) {
padding-left: 1.5rem;
}
:global(.tiptap ul) {
list-style: disc;
}
:global(.tiptap ol) {
list-style: decimal;
}
:global(.tiptap p) {
margin-bottom: 0.5rem;
}
:global(.tiptap p.is-editor-empty:first-child::before) {
content: attr(data-placeholder);
pointer-events: none;
color: oklch(44.4% 0.011 73.639);
float: left;
height: 0;
opacity: 0.7;
}
+302
View File
@@ -0,0 +1,302 @@
import { notifications } from './stores/notification';
import {
to_display_status,
type DisplayStatus,
type Inode,
type RequestResponse,
type ShellCommandResponse,
type TreeElement
} from './types';
export async function get_screenshot(ip: string): Promise<Blob | null> {
const options = { method: 'PATCH' };
const response = await request_display(ip, '/takeScreenshot', options);
if (!response.ok || !response.blob) return null;
return response.blob;
}
export async function open_file(ip: string, path_to_file: string): Promise<void> {
const options = { method: 'PATCH', headers: { 'content-type': 'application/octet-stream' } };
await request_display(ip, `/file${path_to_file}`, options);
}
export async function send_keyboard_input(ip: string, key: string): Promise<void> {
const options = {
method: 'PATCH',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
key: key
})
};
await request_display(ip, '/keyboardInput', options);
}
export async function show_html(ip: string, html: string) {
const options = {
method: 'PATCH',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
html: html
})
};
await request_display(ip, '/showHTML', options);
}
export async function get_file_data(
ip: string,
path: string
): Promise<{ folder_element: Inode; date_created: Date }[] | null> {
interface FileInfo {
name: string;
type: string;
size: string;
created: string;
}
const command = `cd ".${path}" && find . -maxdepth 1 -mindepth 1 -print0 | while IFS= read -r -d '' f; do
typ=$(file -b --mime-type -- "$f")
size=$(stat -c '%s' -- "$f")
created=$(stat -c '%w' -- "$f")
[ "$created" = "-" ] && created=$(stat -c '%y' -- "$f")
jq -n --arg name "$f" --arg type "$typ" --arg size "$size" --arg created "$created" \
'{name:$name, type:$type, size:($size|tostring), created:$created}' | tr -d '\n'
echo
done
`;
const raw_response = await run_shell_command(ip, command, true);
if (!raw_response.ok || !raw_response.json) return null;
const json_response = raw_response.json as ShellCommandResponse;
if (json_response.exitCode === 0 && json_response.stdout.trim() === '') return [];
if (handle_shell_error(ip, json_response, command, true)) return null;
const response: FileInfo[] = json_response.stdout
.trim()
.split('\n')
.filter(Boolean)
.map((line: string) => JSON.parse(line) as FileInfo);
const folder_element_list: { folder_element: Inode; date_created: Date }[] = [];
for (const response_element of response) {
// filter hidden files (start with '.' -> './.config')
if (response_element.name.charAt(2) === '.') continue;
const folder_element: Inode = {
path: path,
name: response_element.name.slice(2), // remove "./"
type: response_element.type,
size: Number(response_element.size),
thumbnail: null
};
folder_element_list.push({ folder_element, date_created: new Date(response_element.created) });
}
return folder_element_list;
}
export async function get_file_tree_data(ip: string, path: string): Promise<TreeElement[] | null> {
const command = `cd ".${path}" && tree -Js`;
const raw_response = await run_shell_command(ip, command, true);
if (!raw_response.ok || !raw_response.json) return null;
const json_response = raw_response.json as ShellCommandResponse;
if (handle_shell_error(ip, json_response, command, true)) return null;
const tree_element: TreeElement | null = JSON.parse(json_response.stdout.trim())[0] || null;
return tree_element?.contents || null;
}
export async function create_folders(
ip: string,
path: string,
folder_names: string[]
): Promise<void> {
let command = `cd ".${path}"`;
for (const part of folder_names) {
command += ` && mkdir "${part}" && cd "${part}/"`;
}
const raw_response = await run_shell_command(ip, command);
if (!raw_response.ok || !raw_response.json) return;
const json_response = raw_response.json as ShellCommandResponse;
handle_shell_error(ip, json_response, command, true);
}
export async function rename_file(
ip: string,
path: string,
old_file_name: string,
new_file_name: string
): Promise<void> {
const command: string = `cd ".${path}" && mv "${old_file_name}" "${new_file_name}"`;
const raw_response = await run_shell_command(ip, command);
if (!raw_response.ok || !raw_response.json) return;
const json_response = raw_response.json as ShellCommandResponse;
handle_shell_error(ip, json_response, command, true);
}
export async function delete_files(
ip: string,
current_path: string,
file_names: string[]
): Promise<void> {
let command: string = `cd ".${current_path}"`;
for (const file_name of file_names) {
command += ` && rm -r "${file_name}"`;
}
const raw_response = await run_shell_command(ip, command);
if (!raw_response.ok || !raw_response.json) return;
const json_response = raw_response.json as ShellCommandResponse;
handle_shell_error(ip, json_response, command, true);
}
export async function show_blackscreen(ip: string): Promise<void> {
const options = {
method: 'PATCH',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
html: ``
})
};
await request_display(ip, '/showHTML', options);
}
export async function get_thumbnail_blob(ip: string, path_to_file: string): Promise<Blob | null> {
const raw_response = await request_display(
ip,
`/file/preview${path_to_file}`,
{ method: 'GET' },
true,
[415]
);
if (!raw_response.ok || !raw_response.blob) return null;
return raw_response.blob;
}
export async function ping_ip(ip: string): Promise<DisplayStatus> {
const raw_response = await request_control(`/ping?ip=${ip}`, { method: 'GET' });
if (!raw_response.ok || !raw_response.json) return null;
const status = raw_response.json.status;
if (typeof status === 'string') {
return to_display_status(status);
}
return null;
}
async function request_display(
ip: string,
api_route: string,
options: { method: string; headers?: Record<string, string>; body?: string },
log_in_debug: boolean = false,
supress_error_handling_http_codes: number[] = []
): Promise<RequestResponse> {
const url = `http://${ip}:1323/api${api_route}`;
return await request(url, options, log_in_debug, supress_error_handling_http_codes);
}
async function request_control(
api_route: string,
options: { method: string; headers?: Record<string, string>; body?: string }
): Promise<RequestResponse> {
const url = `${window.location.origin}/api${api_route}`;
return await request(url, options);
}
async function request(
url: string,
options: { method: string; headers?: Record<string, string>; body?: string },
log_in_debug: boolean = false,
supress_error_handling_http_codes: number[] = []
): Promise<RequestResponse> {
try {
const cache_buster = `${url.includes('?') ? '&' : '?'}=${Date.now()}`;
if (log_in_debug) {
console.debug(url + cache_buster, options.body);
} else {
console.log(url + cache_buster, options.body);
}
const response = await fetch(url + cache_buster, options);
if (response.ok || supress_error_handling_http_codes.includes(response.status)) {
const contentType = response.headers.get('content-type') || '';
let request_response: RequestResponse;
if (!contentType.includes('application/json')) {
const blob: Blob = await response.blob();
request_response = { ok: response.ok, http_code: response.status, blob: blob };
} else {
const json: Record<string, unknown> = await response.json();
request_response = { ok: response.ok, http_code: response.status, json: json };
}
if (log_in_debug) {
console.debug(request_response);
} else {
console.log(request_response);
}
return request_response;
}
let error_description: string;
try {
const json: { description: string } = await response.json();
error_description = json.description;
} catch (error_on_json_parsing: unknown) {
error_description = `unknown error: ${error_on_json_parsing}`;
}
console.error(url, error_description);
notifications.push(
'error',
`Fehler ${response.status} bei API-Anfrage`,
`${url}\nFehler: ${error_description}`
);
} catch (error: unknown) {
if (error instanceof TypeError && /fetch|NetworkError/i.test(error.message)) {
console.log('Request failed - Is the targeted device online?');
} else {
console.error(url, error);
notifications.push('error', `Fataler Fehler bei API-Anfrage`, `${url}\nFehler: ${error}`);
}
}
return { ok: false };
}
function handle_shell_error(
ip: string,
shell_response: ShellCommandResponse,
shell_command: string,
command_includs_cd: boolean
): boolean {
if (shell_response.exitCode !== 0) {
if (
command_includs_cd &&
shell_response.stderr &&
/bash: line \d+: cd: .+: No such file or directory/.test(shell_response.stderr)
) {
console.log('current file_path does not exist on display:', ip);
return true;
}
console.error(shell_response);
notifications.push(
'error',
`Fehler ${shell_response.exitCode} in API-Shell`,
`${ip}\n${shell_command}\nFehler: ${shell_response.stderr}`
);
return true;
}
if (shell_response.stdout.trim() === '') return true;
return false;
}
async function run_shell_command(
ip: string,
command: string,
log_in_debug: boolean = false
): Promise<RequestResponse> {
const options = {
method: 'PATCH',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
command: command
})
};
return await request_display(ip, '/shellCommand', options, log_in_debug);
}
+56
View File
@@ -0,0 +1,56 @@
import Dexie, { type Table } from 'dexie';
import type { Display, DisplayGroup, Inode } from './types';
export interface FileOnDisplay {
display_id: string;
file_primary_key: string; // JSON.stringify([string, string, number, string])
date_created: Date;
is_loading: boolean;
percentage: number;
}
export class FileDatabase extends Dexie {
files!: Table<Inode, [string, string, number, string]>;
files_on_display!: Table<FileOnDisplay, [string, string]>;
displays!: Table<Display, string>;
display_groups!: Table<DisplayGroup, string>;
constructor() {
super('FileDatabase');
this.version(1).stores({
files: `
[path+name+size+type],
path,
name,
size,
type,
thumbnail
`,
files_on_display: `
[display_id+file_primary_key],
display_id,
file_primary_key,
date_created,
is_loading,
percentage
`,
displays: `
id,
ip,
mac,
position,
preview,
group_id,
name,
status
`,
display_groups: `
id,
position
`
});
}
}
export const db = new FileDatabase();
+34
View File
@@ -0,0 +1,34 @@
import { screenshot_loop } from './stores/displays';
import { ping_ip } from './api_handler';
import type { Display } from './types';
import { update_folder_elements_recursively } from './stores/files';
import { db } from './files_display.db';
const update_display_status_interval_seconds = 20;
export async function on_start() {
await db.files.clear();
await db.files_on_display.clear();
await update_all_display_status();
await setInterval(update_all_display_status, update_display_status_interval_seconds * 1000);
}
async function update_all_display_status() {
const all_displays: Display[] = await db.displays.toArray();
for (const display of all_displays) {
const new_status = await ping_ip(display.ip);
if (new_status === null && display.status !== null) continue;
if (new_status === 'app_online' && display.status !== 'app_online') {
on_display_start(display);
}
if (new_status !== display.status) {
display.status = new_status;
await db.displays.put(display); // save
}
}
}
async function on_display_start(display: Display) {
await update_folder_elements_recursively(display, '/');
await screenshot_loop(display.id);
}
+196
View File
@@ -0,0 +1,196 @@
import { get } from 'svelte/store';
import type { Display, DisplayGroup, DisplayStatus } from '../types';
import { is_selected, select, selected_display_ids } from './select';
import { get_uuid, image_content_hash } from '../utils';
import { get_screenshot } from '../api_handler';
import { delete_and_deselect_unique_files_from_display } from './files';
import { db } from '../files_display.db';
export async function is_display_name_taken(name: string): Promise<boolean> {
const exists = await db.displays.where('name').equals(name).first();
return !!exists;
}
export async function add_display(
ip: string,
mac: string | null,
name: string,
status: DisplayStatus
) {
if (await is_display_name_taken(name)) return;
const new_id = get_uuid();
const group = await db.display_groups.toCollection().first();
let group_id: string;
if (group) {
group_id = group.id;
console.log('DISPLAYGROUP WURDE NICHT ERSTELLT');
} else {
group_id = get_uuid();
await db.display_groups.put({ id: group_id, position: 0 });
console.log('DISPLAYGROUP WURDE ERSTELLT');
}
const element_count_in_group = (await db.displays.where('group_id').equals(group_id).toArray())
.length;
await db.displays.put({
id: new_id,
ip,
mac,
position: element_count_in_group,
preview: { currently_updating: false, url: null },
group_id: group_id,
name,
status
});
}
export async function edit_display_data(
display_id: string,
ip: string,
mac: string | null,
name: string
) {
let display = await db.displays.get(display_id);
if (!display) return;
display = { ...display, ip: ip, mac: mac, name: name };
await db.displays.put(display); // save
}
export async function remove_display(display_id: string) {
select(selected_display_ids, display_id, 'deselect');
await delete_and_deselect_unique_files_from_display(display_id);
const group_id = (await db.displays.get(display_id))?.group_id;
await db.displays.delete(display_id);
if (group_id && (await db.displays.where('group_id').equals(group_id).toArray()).length === 0) {
await db.display_groups.delete(group_id); // delete empty group
}
}
export async function all_displays_of_group_selected(
display_group_id: string,
current_selected_displays: string[]
): Promise<boolean> {
const displays_of_group: Display[] = await db.displays
.where('group_id')
.equals(display_group_id)
.toArray();
if (displays_of_group.length === 0) return false;
for (const display of displays_of_group) {
if (!is_selected(display.id, current_selected_displays)) {
return false;
}
}
return true;
}
export async function select_all_of_group(
display_group_id: string,
new_value: boolean | null = null
) {
const displays_of_group: Display[] = await db.displays
.where('group_id')
.equals(display_group_id)
.toArray();
for (const display of displays_of_group) {
let action: string;
if (new_value === true) {
action = 'select';
} else {
action = 'deselect';
}
select(selected_display_ids, display.id, action as 'toggle' | 'select' | 'deselect');
}
}
export async function get_display_by_id(display_id: string): Promise<Display | null> {
return (await db.displays.get(display_id)) ?? null;
}
export async function screenshot_loop(display_id: string, initial_retry_count: number = 5) {
const display = await db.displays.get(display_id);
if (!display || display.preview.currently_updating) return;
display.preview.currently_updating = true;
await db.displays.update(display.id, { preview: display.preview });
let last_hash: number | null = null;
let retry_count = initial_retry_count;
while (retry_count > 0) {
retry_count -= 1;
const new_blob = await get_screenshot(display.ip);
if (!new_blob) {
display.preview = { currently_updating: false, url: null };
await db.displays.update(display.id, { preview: display.preview });
return;
}
const new_hash = await image_content_hash(new_blob);
if (last_hash !== new_hash) {
if (display.preview.url) {
URL.revokeObjectURL(display.preview.url);
}
last_hash = new_hash;
display.preview.url = URL.createObjectURL(new_blob);
await db.displays.update(display.id, { preview: display.preview });
retry_count = initial_retry_count;
}
await new Promise((resolve) => setTimeout(resolve, 2000)); // sleep 2s
}
display.preview.currently_updating = false;
await db.displays.update(display.id, { preview: display.preview });
}
export async function run_on_all_selected_displays<T extends unknown[]>(
run_function: (ip: string, ...args: T) => void | Promise<void>,
update_screenshot_afterwards: boolean,
...args: T
) {
for (const display_id of get(selected_display_ids)) {
const display_ip = (await get_display_by_id(display_id))?.ip;
if (display_ip) {
await run_function(display_ip, ...args);
if (update_screenshot_afterwards) {
await screenshot_loop(display_id);
}
}
}
}
export async function get_display_groups(): Promise<DisplayGroup[]> {
return await db.display_groups.orderBy('position').toArray();
}
export async function get_display_ids_in_group(display_group_id: string): Promise<Display[]> {
const displays: Display[] = await db.displays
.where('group_id')
.equals(display_group_id)
.sortBy('position');
return displays;
}
export async function set_new_display_order(new_ordered_items: Display[]) {
for (let i = 0; i < new_ordered_items.length; i++) {
new_ordered_items[i].position = i;
await db.displays.put(new_ordered_items[i]);
}
}
export async function set_new_display_group_order(new_ordered_items: DisplayGroup[]) {
for (let i = 0; i < new_ordered_items.length; i++) {
new_ordered_items[i].position = i;
await db.display_groups.put(new_ordered_items[i]);
}
}
setTimeout(add_testing_displays, 0);
async function add_testing_displays() {
await add_display('127.0.0.1', '00:1A:2B:3C:4D:5E', 'PC', 'host_offline');
// await add_display("192.168.178.111", "D4:81:D7:C0:DF:3C", "Laptop", "host_offline");
}
+373
View File
@@ -0,0 +1,373 @@
import { get, writable, type Writable } from 'svelte/store';
import { get_file_primary_key, type Display, type Inode, type TreeElement } from '../types';
import { get_display_by_id } from './displays';
import { select, selected_display_ids, selected_file_ids } from './select';
import { create_folders, get_file_data, get_file_tree_data } from '../api_handler';
import { deactivate_old_thumbnail_urls, generate_thumbnail } from './thumbnails';
import { db, type FileOnDisplay } from '../files_display.db';
export const current_file_path: Writable<string> = writable<string>('/');
export async function change_file_path(new_path: string) {
current_file_path.update(() => {
return new_path;
});
selected_file_ids.update(() => {
return [];
});
deactivate_old_thumbnail_urls();
const displays = await db.displays.toArray();
for (const display of displays) {
const changed_paths = await get_changed_directory_paths(display, new_path);
if (!changed_paths) continue;
console.log('Update file system from', display.name, ':', changed_paths);
for (const path of changed_paths) {
await update_folder_elements_recursively(display, path);
}
}
}
export async function delete_and_deselect_unique_files_from_display(display_id: string) {
const files_on_display = await db.files_on_display
.where('display_id')
.equals(display_id)
.toArray();
for (const file of files_on_display) {
await remove_file_from_display(display_id, file.file_primary_key);
}
await remove_all_files_without_display();
}
async function remove_file_from_display(display_id: string, file_primary_key: string) {
const found = await db.files_on_display.get([display_id, file_primary_key]);
if (!found) return;
select(selected_file_ids, file_primary_key, 'deselect');
await db.files_on_display.delete([display_id, file_primary_key]);
}
async function remove_all_files_without_display() {
const existing_file_id_strings: string[] = (await db.files_on_display
.orderBy('file_primary_key')
.uniqueKeys()) as string[];
const existing_file_id_objects: [string, string, number, string][] = existing_file_id_strings.map(
(e) => JSON.parse(e) as [string, string, number, string]
);
await db.files.where('[path+name+size+type]').noneOf(existing_file_id_objects).delete();
}
export async function update_current_folder_on_selected_displays() {
selected_file_ids.update(() => {
return [];
});
const current_path = get(current_file_path);
for (const display of await db.displays.where('id').anyOf(get(selected_display_ids)).toArray()) {
await update_folder_elements_recursively(display, current_path);
}
}
export async function get_missing_colliding_display_ids(
file: Inode,
selected_display_ids: string[]
): Promise<{ missing: string[]; colliding: string[] }> {
const missing: string[] = await get_display_ids_where_file_is_missing(file, selected_display_ids);
const colliding: string[] = [];
const colliding_files = await db.files
.where('[path+name]')
.equals([file.path, file.name])
.filter((e) => e.size !== file.size || e.type !== file.type)
.toArray();
for (const colliding_file of colliding_files) {
colliding.push(
...(await get_display_ids_where_file_is_missing(colliding_file, selected_display_ids))
);
}
return { missing, colliding };
}
async function get_display_ids_where_file_is_missing(
file: Inode,
selected_display_ids: string[]
): Promise<string[]> {
const file_primary_key = get_file_primary_key(file);
const files_on_selected_displays = await db.files_on_display
.where('file_primary_key')
.equals(file_primary_key)
.filter((e) => selected_display_ids.includes(e.display_id))
.toArray();
return selected_display_ids.filter(
(id) => !files_on_selected_displays.some((item) => item.display_id === id)
);
}
export async function get_displays_where_path_exists(
path: string,
selected_display_ids: string[],
invert: boolean
): Promise<Display[]> {
if (path === '/') return [];
const last_path_part =
path
.slice(0, path.length - 1)
.split('/')
.at(-1) ?? '';
const path_without_last_part = path.slice(0, path.length - (last_path_part.length + 1));
const folders_of_current_path = await db.files
.where('[path+name+type]')
.equals([path_without_last_part, last_path_part, 'inode/directory'])
.first();
if (!folders_of_current_path)
return await db.displays.where('id').anyOf(selected_display_ids).toArray();
const folder_primary_key = get_file_primary_key(folders_of_current_path);
const display_ids = selected_display_ids.filter(async (display_id) => {
const folder_exists = await db.files_on_display.get([display_id, folder_primary_key]);
if (invert) {
return !folder_exists;
} else {
return folder_exists;
}
});
return (await db.displays.bulkGet(display_ids)).filter((e) => e !== undefined);
}
async function get_changed_directory_paths(
display: Display,
file_path: string
): Promise<string[] | null> {
const current_folder = await get_file_tree_data(display.ip, file_path);
const directory_strings = await get_recursive_changed_directory_paths(
display,
file_path,
current_folder
);
if (directory_strings.size === 0) return null;
const directory_strings_array = [...directory_strings];
return directory_strings_array.filter(
(e) => !directory_strings_array.some((f) => f !== e && f.startsWith(e))
);
}
async function get_recursive_changed_directory_paths(
display: Display,
current_file_path: string,
current_folder_elements: TreeElement[] | null
): Promise<Set<string>> {
const files_folder: Inode[] = await db.files.where('path').equals(current_file_path).toArray();
if (
(!files_folder || files_folder.length === 0) &&
(!current_folder_elements || current_folder_elements.length === 0)
) {
return new Set([]); // no data -> no update needed
} else if (
!files_folder ||
!current_folder_elements ||
current_folder_elements.length !== files_folder.length
) {
return new Set([current_file_path]); // existing data does not match new data -> update
}
const has_changed: Set<string> = new Set();
for (const tree_folder_element of current_folder_elements) {
const folder_element = files_folder.find((e) => e.name === tree_folder_element.name);
if (
!folder_element ||
(tree_folder_element.type !== 'directory' && folder_element.size !== tree_folder_element.size)
) {
return new Set([current_file_path]);
}
if (tree_folder_element.type === 'directory' && tree_folder_element.contents) {
const new_file_path = current_file_path + tree_folder_element.name + '/';
for (const string of await get_recursive_changed_directory_paths(
display,
new_file_path,
tree_folder_element.contents
)) {
has_changed.add(string);
}
}
}
return has_changed;
}
export async function update_folder_elements_recursively(
display: Display,
file_path: string = '/'
): Promise<void> {
const new_folder_elements = await get_file_data(display.ip, file_path);
if (!new_folder_elements) return;
const existing_file_keys_on_display_in_path: [string, string, number, string][] = (
await db.files_on_display.where('display_id').equals(display.id).toArray()
).map((e) => JSON.parse(e.file_primary_key) as [string, string, number, string]);
const existing_files_on_display_in_path: Inode[] = await db.files
.where('[path+name+size+type]')
.anyOf(existing_file_keys_on_display_in_path)
.filter((e) => e.path === file_path)
.toArray();
const diff = get_folder_elements_difference(
existing_files_on_display_in_path,
new_folder_elements
);
if (diff.new.length > 0) {
// Add new Folder-Elements
for (const new_element of diff.new) {
await db.files.put(new_element.folder_element);
const file_on_display: FileOnDisplay = {
display_id: display.id,
file_primary_key: get_file_primary_key(new_element.folder_element),
is_loading: false,
percentage: 0,
date_created: new_element.date_created
};
await db.files_on_display.put(file_on_display);
if (new_element.folder_element.type === 'inode/directory') {
await update_folder_elements_recursively(
display,
file_path + new_element.folder_element.name + '/'
);
}
}
// Generate Thumbnails:
setTimeout(async () => {
for (const new_element of diff.new) {
await generate_thumbnail(display.ip, file_path, new_element.folder_element);
}
}, 0);
}
if (diff.deleted.length > 0) {
// Remove old Folder-Elements
for (const old_element of diff.deleted) {
remove_file_from_display(display.id, get_file_primary_key(old_element));
}
await remove_all_files_without_display();
}
}
function get_folder_elements_difference(
old_elements: Inode[],
new_elements: { folder_element: Inode; date_created: Date }[]
): { deleted: Inode[]; new: { folder_element: Inode; date_created: Date }[] } {
const old_keys = new Set(old_elements.map((e) => get_file_primary_key(e)));
const new_keys = new Set(new_elements.map((e) => get_file_primary_key(e.folder_element)));
const only_in_old = old_elements.filter((e) => !new_keys.has(get_file_primary_key(e)));
const only_in_new = new_elements.filter(
(e) => !old_keys.has(get_file_primary_key(e.folder_element))
);
return { deleted: only_in_old, new: only_in_new };
}
export async function get_current_folder_elements(
current_file_path: string,
selected_display_ids: string[]
): Promise<Inode[]> {
const existing_file_keys_on_selected_displays: [string, string, number, string][] = (
await db.files_on_display.where('display_id').anyOf(selected_display_ids).toArray()
).map((e) => JSON.parse(e.file_primary_key) as [string, string, number, string]);
const existing_files_on_selected_displays_in_path: Inode[] = await db.files
.where('[path+name+size+type]')
.anyOf(existing_file_keys_on_selected_displays)
.filter((e) => e.path === current_file_path)
.toArray();
return sort_files(existing_files_on_selected_displays_in_path);
}
function sort_files(files: Inode[]) {
files.sort((a, b) => {
const isDirA = a.type === 'inode/directory';
const isDirB = b.type === 'inode/directory';
// Ordner zuerst
if (isDirA && !isDirB) return -1;
if (!isDirA && isDirB) return 1;
// Danach alphabetisch nach name (case-insensitive)
const nameCompare = a.name.localeCompare(b.name, undefined, { sensitivity: 'base' });
if (nameCompare !== 0) return nameCompare;
return -1;
});
return files;
}
export async function get_file_by_id(
file_primary_key: string,
only_from_selected_displays: boolean = false
): Promise<Inode | null> {
const file = (await db.files.get(JSON.parse(file_primary_key))) ?? null;
if (!file || !only_from_selected_displays) {
return file;
} else {
const exist_on_selected_display = !!(await db.files_on_display
.where('file_primary_key')
.equals(file_primary_key)
.filter((e) => get(selected_display_ids).includes(e.display_id))
.first());
return exist_on_selected_display ? file : null;
}
}
export async function run_for_selected_files_on_selected_displays(
action: (ip: string, file_names: string[]) => Promise<void>
): Promise<void> {
for (const display_id of get(selected_display_ids)) {
const file_keys_on_display: [string, string, number, string][] = (
await db.files_on_display.where('display_id').equals(display_id).toArray()
).map((e) => JSON.parse(e.file_primary_key) as [string, string, number, string]);
const file_names_on_display: string[] = (
await db.files.where('[path+name+size+type]').anyOf(file_keys_on_display).toArray()
).map((e) => e.name);
const display = await get_display_by_id(display_id);
if (!display) continue;
await action(display.ip, file_names_on_display);
}
}
export async function create_folder_on_all_selected_displays(
folder_name: string,
path: string,
selected_display_ids: string[]
): Promise<void> {
const path_parts = path
.slice(1, path.length - 1)
.split('/')
.filter((e) => e.length !== 0);
let remaining_display_ids = [...selected_display_ids];
const getDisplaysForPath = async (currentPath: string): Promise<Display[]> => {
if (currentPath === '/') {
const displays = await db.displays.bulkGet(remaining_display_ids);
return displays.filter((d): d is Display => !!d);
}
return get_displays_where_path_exists(currentPath, remaining_display_ids, false);
};
for (let depth = path_parts.length; depth >= 0 && remaining_display_ids.length; depth--) {
const currentPath = depth === 0 ? '/' : `/${path_parts.slice(0, depth).join('/')}/`;
const displays = await getDisplaysForPath(currentPath);
if (!displays.length) continue;
const folders_to_create = [...path_parts.slice(depth), folder_name];
for (const display of displays) {
await create_folders(display.ip, currentPath, folders_to_create);
remaining_display_ids = remaining_display_ids.filter((id) => id !== display.id);
}
}
}
@@ -0,0 +1,28 @@
import { writable } from "svelte/store";
export type Notification = {
id: number;
title: string;
message: string;
duration: number;
className: string;
type?: "error" | "success" | "info";
};
function createNotifications() {
const { subscribe, update } = writable<Notification[]>([]);
function push(type: "error" | "success" | "info", title: string, message: string = "", className: string = "") {
const id = Date.now();
const duration = type === "error" ? 16000 : 4000;
update((n) => [...n, { id, title, message, duration, className, type }]);
setTimeout(() => {
update((n) => n.filter((x) => x.id !== id));
}, duration);
}
const remove = (id: number) => update(n => n.filter(x => x.id !== id));
return { subscribe, push, remove };
}
export const notifications = createNotifications();
+26
View File
@@ -0,0 +1,26 @@
import { writable, type Writable } from 'svelte/store';
export const selected_file_ids: Writable<string[]> = writable<string[]>([]); // JSON.stringify([string, string, number, string])
export const selected_display_ids: Writable<string[]> = writable<string[]>([]);
export function select(
selected_ids: Writable<string[]>,
id: string,
action: 'toggle' | 'select' | 'deselect'
) {
selected_ids.update((all_ids: string[]) => {
if (all_ids.includes(id)) {
const index = all_ids.indexOf(id);
if (index > -1 && action !== 'select') {
all_ids.splice(index, 1);
}
} else if (action !== 'deselect') {
all_ids.push(id);
}
return all_ids;
});
}
export function is_selected(id: string, selected_ids: string[]): boolean {
return selected_ids.includes(id);
}
+43
View File
@@ -0,0 +1,43 @@
import { get, writable, type Writable } from 'svelte/store';
import { get_thumbnail_blob } from '../api_handler';
import { type Inode } from '../types';
import { db } from '../files_display.db';
import { get_file_type } from '../utils';
export const active_thumbnail_urls: Writable<string[]> = writable<string[]>([]);
export async function generate_thumbnail(
display_ip: string,
path: string,
folder_element: Inode
): Promise<void> {
const supported_file_type = get_file_type(folder_element);
if (!supported_file_type) return;
const thumbnail_blob = await get_thumbnail_blob(display_ip, path + folder_element.name);
if (!thumbnail_blob) return;
folder_element.thumbnail = thumbnail_blob;
await db.files.put(folder_element); // save
}
export async function get_thumbnail_url(file: Inode): Promise<string | null> {
if (!file.thumbnail) return null;
const new_url = URL.createObjectURL(file.thumbnail);
active_thumbnail_urls.update((current: string[]) => {
current.push(new_url);
return current;
});
return new_url;
}
export function deactivate_old_thumbnail_urls() {
const current_urls = get(active_thumbnail_urls);
for (const url of current_urls) {
URL.revokeObjectURL(url);
}
active_thumbnail_urls.update(() => {
return [];
});
}
@@ -0,0 +1,72 @@
import { writable, type Writable } from "svelte/store";
export const dnd_flip_duration_ms = 300;
const heights_options: Record<string, { min: number; max: number; step: number }> = {
display: {
min: 15,
max: 40,
step: 5,
},
file: {
min: 10,
max: 20,
step: 5,
}
}
export const current_height: Writable<Record<string, number>> = writable<Record<string, number>>({
display: 25,
file: 10,
});
export const is_group_drag: Writable<boolean> = writable<boolean>(false);
export const is_display_drag: Writable<boolean> = writable<boolean>(false);
export const pinned_display_id: Writable<string | null> = writable<string | null>(null);
export function change_height(key: 'display' | 'file', factor: number) {
current_height.update((height) => {
height[key] = next_height_step_size(key, height, factor) || height[key];
return height;
});
}
export function next_height_step_size(key: 'display' | 'file', current_height_array: Record<string, number>, factor: number): number {
const new_size = current_height_array[key] + (factor * heights_options[key].step);
if (new_size > heights_options[key].max || new_size < heights_options[key].min) {
return 0;
} else {
return new_size;
}
}
export function get_selectable_color_classes(
selected: boolean,
returning_classes: { bg?: boolean; hover?: boolean; active?: boolean; text?: boolean } = {},
base_bg_distance: number = 0,
shifted_distance: number = 0
) {
let base_bg = selected ? 'bg-stone-400' : 'bg-stone-600';
const base_text = selected ? 'text-stone-950' : 'text-stone-200';
base_bg = get_shifted_color(base_bg, base_bg_distance);
const { bg = false, hover = false, active = false, text = false } = returning_classes;
const out: string[] = [];
if (bg) out.push(base_bg);
if (hover) out.push('hover:' + get_shifted_color(base_bg, 100 + shifted_distance));
if (active) out.push('active:' + get_shifted_color(base_bg, 150 + shifted_distance));
if (text) out.push(base_text);
return out.join(' ');
}
export function get_shifted_color(base_color: string, distance: number): string {
return base_color.replace(/(\d+)(?=(?:\/\d+)?$)/, (m: string) => String(+Number(m) - distance));
}
+97
View File
@@ -0,0 +1,97 @@
import { FileBox, FileImage, FileText, FileVideoCamera, ImagePlay, type X } from 'lucide-svelte';
import type { Snippet } from 'svelte';
export type RequestResponse = {
ok: boolean;
http_code?: number;
blob?: Blob;
json?: Record<string, unknown>;
};
export type ShellCommandResponse = {
stdout: string;
stderr: string;
exitCode: number;
};
export type SupportedFileType = {
display_name: string;
mime_type: string;
};
export const supported_file_type_icon: Record<string, typeof X> = {
MP4: FileVideoCamera,
JPG: FileImage,
PNG: FileImage,
GIF: ImagePlay,
PPTX: FileBox,
ODP: FileBox,
PDF: FileText
};
export type Inode = {
path: string;
name: string;
size: number;
type: string;
date_created: Date;
thumbnail: Blob | null;
};
export function get_file_primary_key(file: Inode): string {
return JSON.stringify([file.path, file.name, file.size, file.type]);
}
export type TreeElement = {
contents?: TreeElement[];
type: 'file' | 'directory';
name: string;
size: number;
};
export type Display = {
id: string;
ip: string;
mac: string | null;
position: number;
preview: PreviewObject;
group_id: string;
name: string;
status: DisplayStatus;
};
export type DisplayGroup = {
id: string;
position: number;
};
export type PreviewObject = {
currently_updating: boolean;
url: string | null;
};
export type MenuOption = {
icon?: typeof X;
name: string;
class?: string;
on_select?: () => void | Promise<void>;
disabled?: boolean;
};
export type PopupContent = {
open: boolean;
snippet: Snippet<[string]> | null;
snippet_arg?: string;
title?: string;
title_class?: string;
title_icon?: typeof X | null;
window_class?: string;
closable?: boolean;
};
export type DisplayStatus = 'host_offline' | 'app_offline' | 'app_online' | null;
export function to_display_status(value: string): DisplayStatus {
return ['host_offline', 'app_offline', 'app_online'].includes(value)
? (value as DisplayStatus)
: null;
}
+83
View File
@@ -0,0 +1,83 @@
import type { DisplayStatus, Inode, SupportedFileType } from './types';
import supported_file_types_json from './../../../../../shared/supported_file_types.json';
const supported_file_types: Record<string, SupportedFileType> = supported_file_types_json as Record<
string,
SupportedFileType
>;
export function get_file_type(file: Inode): SupportedFileType | null {
for (const key of Object.keys(supported_file_types)) {
if (file.type === supported_file_types[key].mime_type) {
return supported_file_types[key];
}
}
// Fallback:
const extension = file.name.split('.').pop();
if (extension) {
if (Object.keys(supported_file_types).includes('.' + extension)) {
return supported_file_types['.' + extension];
}
}
return null;
}
export function get_uuid(): string {
return crypto.randomUUID();
}
export function get_file_size_display_string(size: number, toFixed: number | null = null): string {
if (size < 0)
return toFixed === null ? 'versch.' : 'Verschiedene Größen auf verschiedenen Bildschirmen';
if (size === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(size) / Math.log(k));
const value = size / Math.pow(k, i);
const size_string = `${value.toFixed(toFixed !== null ? toFixed : Math.max(0, 2 - Math.floor(Math.log10(value))))} ${sizes[i]}`;
return size_string.replace('.', ',');
}
export async function image_content_hash(blob: Blob, size = 32): Promise<number> {
// Blob → ImageBitmap (GPU-dekodiert, superschnell)
const bitmap = await createImageBitmap(blob);
// OffscreenCanvas ist sehr schnell (kein Layout nötig)
const canvas = new OffscreenCanvas(size, size);
const ctx = canvas.getContext('2d')!;
ctx.drawImage(bitmap, 0, 0, size, size);
// Pixel-Daten holen
const { data } = ctx.getImageData(0, 0, size, size);
// Einfacher, schneller Integer-Hash (FNV-1a)
let hash = 2166136261;
for (let i = 0; i < data.length; i++) {
hash ^= data[i];
hash = Math.imul(hash, 16777619);
}
bitmap.close(); // GPU-Ressourcen freigeben
return hash >>> 0; // unsigned int
}
export function is_valid_name(input: string): boolean {
return /^[\p{L}\p{N}\p{M}\-_.+,()[\]{}@!§$%&=~^ ]+$/u.test(input);
}
export function display_status_to_info(status: DisplayStatus): string {
switch (status) {
case 'app_online':
return 'Online';
case 'app_offline':
return 'Lädt';
case 'host_offline':
return 'Offline';
case null:
return '???';
}
}