]> git.r.bdr.sh - rbdr/canvas/blame - src/lib/stores/widgets.js
Update project, improve sensor/render logic
[rbdr/canvas] / src / lib / stores / widgets.js
CommitLineData
c30e6881
RBR
1import { derived, writable } from 'svelte/store';
2import { createClient } from '@supabase/supabase-js';
3import { supabase } from '$lib/config';
4import { maxSize } from '$lib/config';
5
d7cea969 6const boxParser = /\(([0-9]+),([0-9]+)\),\(([0-9]+),([0-9]+)\)/
c30e6881
RBR
7const client = createClient(supabase.url, supabase.key);
8
9export const sensor = writable({left: 0, top: 0, right: 0, bottom: 0});
10
11const getBoxes = function getBoxes ({left, top, right, bottom}) {
d7cea969
RBR
12 const results = [
13 `box.ov."((${left},${top}),(${right},${bottom}))"`,
14 `box.ov."((${left+maxSize},${top+maxSize}),(${right+maxSize},${bottom+maxSize}))"`,
15 `box.ov."((${left+maxSize},${top}),(${right+maxSize},${bottom}))"`,
e4e4b520
RBR
16 `box.ov."((${left},${top+maxSize}),(${right},${bottom+maxSize}))"`,
17 `box.ov."((${left-maxSize},${top-maxSize}),(${right-maxSize},${bottom-maxSize}))"`,
18 `box.ov."((${left-maxSize},${top}),(${right-maxSize},${bottom}))"`,
19 `box.ov."((${left},${top-maxSize}),(${right},${bottom-maxSize}))"`
d7cea969
RBR
20 ];
21
d7cea969
RBR
22 return results
23};
24
25const serialize = function serialize(widget) {
26
27 const boxComponents = widget.box
28 .match(boxParser)
29 .slice(1,5)
30 .map(Number);
31 const box = {
32 left: Math.min(boxComponents[0], boxComponents[2]),
33 right: Math.max(boxComponents[0], boxComponents[2]),
34 top: Math.min(boxComponents[1], boxComponents[3]),
35 bottom: Math.max(boxComponents[1], boxComponents[3])
36 };
37
38 return {...widget, box }
c30e6881
RBR
39};
40
41let ac = null;
42export const widgets = derived(sensor, async function ($sensor, set) {
43
44 const boxes = getBoxes($sensor);
45 ac && ac.abort()
46 ac = new AbortController();
47 const { data } = await client
48 .from('widgets')
49 .select()
50 .or(boxes.join(','))
51 .abortSignal(ac.signal)
d7cea969
RBR
52 if (data) {
53 return set(data.map(serialize));
54 }
c30e6881 55});