Merge branch 'new-ui' into 'main'

New ui

See merge request all-dressed-programming/dodgeball-tracker!1
This commit was merged in pull request #1.
This commit is contained in:
didier committed 2024-11-04 23:51:09 +00:00
commit 1246c2870a
58 files changed
+7935 -24007

No files matched your search

+1
View File
@@ -0,0 +1 @@
use flake
+2
View File
@@ -159,3 +159,5 @@ env
*.pt *.pt
*.png *.png
*.ipynb *.ipynb
.direnv
result
-24
View File
@@ -1,24 +0,0 @@
from pathlib import Path
from dodgeballtracker.logic import (DetectedObjectBox,
DodgeballTracker,
get_court_perspective_transform)
import numpy as np
here = Path(__file__).parent
input_dir = here / '..' / 'data'
output_dir = here / '..' / 'outputs'
if __name__ == "__main__":
detected_box_objects = [
DetectedObjectBox.from_viridis(threshold) for threshold in np.arange(0.5, 1, 0.05)
]
input_video = input_dir / "micro.mp4"
output_video = output_dir / "output-lmbn_n_cuhk03_d.mp4"
transformation_matrix = get_court_perspective_transform()
dodgeball_tracker = DodgeballTracker(input_video, output_video, detected_box_objects, transformation_matrix)
dodgeball_tracker.main()
+70
View File
@@ -0,0 +1,70 @@
from contextlib import closing
from pathlib import Path
from dodgeballtracker.helper import time_tracker
from dodgeballtracker.logic import (DodgeballTracker,
get_court_perspective_transform)
import numpy as np
import logging
import click
from typing import ContextManager
from dodgeballtracker.video_writer import (MP4VVideoWriter,
VideoWriter,
DetectedObjectBox,
MP4VVideoWriterWithFrame)
here = Path(__file__).parent
input_dir = here / '..' / 'data'
output_dir = here / '..' / 'outputs'
@click.group()
@click.option('--debug/--no-debug', default=False)
def cli(debug):
logging.basicConfig(filename='tracker.log', level=logging.DEBUG)
def get_output(input_: Path, proposed_output: Path | None) -> Path:
if proposed_output is not None:
return proposed_output
return output_dir / input_.name
def get_video_writer(display_frame: bool,
video_input: Path,
video_output: Path) -> ContextManager[VideoWriter]:
thresholds = list(np.arange(0.5, 1, 0.05))
if display_frame:
return closing(
MP4VVideoWriterWithFrame.from_frame(video_input, video_output, thresholds))
return closing(MP4VVideoWriter.from_frame(video_input, video_output, thresholds))
@cli.command()
@click.option('--input', '-i', 'input_',
type=click.Path(readable=True, path_type=Path))
@click.option('--output', '-o', type=click.Path(path_type=Path))
@click.option('--display-video', '-d', type=bool, is_flag=True, show_default=True, default=False)
def process(input_: Path, output: Path | None, display_video: bool):
output = get_output(input_, output)
detected_box_objects = [
DetectedObjectBox.from_viridis(threshold) for threshold in
np.arange(0.5, 1, 0.05)
]
transformation_matrix = get_court_perspective_transform()
with get_video_writer(display_video, input_, output) as video_writer:
tracker = DodgeballTracker(input_,
output,
video_writer,
detected_box_objects,
transformation_matrix)
with time_tracker():
tracker.main()
if __name__ == "__main__":
cli()
+7 -16
View File
@@ -1,24 +1,15 @@
import contextlib import contextlib
import time import time
from typing import Iterator
from dodgeballtracker.typing import VideoFrame, VideoTimestamp
import cv2 import cv2
import logging
logger = logging.getLogger(__name__)
def create_video_writer(video_cap, output_filename):
# grab the width, height, and fps of the frames in the video stream. def iter_frames(video_cap) -> Iterator[tuple[VideoFrame, VideoTimestamp]]:
frame_width = int(video_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(video_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = int(video_cap.get(cv2.CAP_PROP_FPS))
# initialize the FourCC and a video writer object
fourcc = cv2.VideoWriter_fourcc(*'MP4V')
writer = cv2.VideoWriter(output_filename, fourcc, fps,
(frame_width, frame_height))
return writer
def iter_frames(video_cap):
while 1: while 1:
ret, frame = video_cap.read() ret, frame = video_cap.read()
if not ret: if not ret:
@@ -31,4 +22,4 @@ def time_tracker():
start = time.monotonic() start = time.monotonic()
yield yield
end = time.monotonic() end = time.monotonic()
print(f"Time to process 1 frame: {(end-start) * 1000:.0f} milliseconds") logger.debug(f"Time to process 1 frame: {(end-start) * 1000:.0f} milliseconds")
+48 -60
View File
@@ -1,32 +1,31 @@
import json import json
from pathlib import Path from pathlib import Path
import logging
import torch import torch
from ultralytics import YOLO from ultralytics import YOLO
import cv2 import cv2
from dodgeballtracker.helper import create_video_writer, iter_frames from dodgeballtracker.helper import iter_frames
import matplotlib from dodgeballtracker.video_writer import VideoWriter, DetectedObjectBox
import numpy as np import numpy as np
from boxmot import DeepOCSORT import pandas as pd
import pandera as pa
from boxmot import DeepOcSort as DeepOCSORT
from .typing import VideoFrame, DetectedObject_
logger = logging.getLogger(__name__)
Color = tuple[int, int, int] Color = tuple[int, int, int]
class DetectedObjectBox: def get_best_available_torch_device() -> torch.device:
def __init__(self, min_threshold: float, color: Color): if torch.cuda.is_available():
self.min_threshold = min_threshold logger.debug("Using the cuda (gpu) torch device.")
self.color = color return torch.device('cuda:0')
if torch.backends.mps.is_available():
def __lt__(self, other): logger.debug("Using the mps (apple silicon) torch device.")
return self.min_threshold < other.min_threshold return torch.device('mps')
logger.debug("Default to cpu (no apple silicon or cuda) torch device.")
@classmethod return torch.device('cpu')
def from_viridis(cls, min_threshold):
cm = matplotlib.colormaps['viridis']
color: Color = tuple((int(255 * cm(min_threshold)[i]) for i in range(3)))
return cls(min_threshold, color)
def get_court_perspective_transform(): def get_court_perspective_transform():
@@ -54,16 +53,21 @@ def get_court_perspective_transform():
return cv2.getPerspectiveTransform(empirical_source, empirical_target) return cv2.getPerspectiveTransform(empirical_source, empirical_target)
class DodgeballTracker: class DodgeballTracker:
def __init__(self, def __init__(self,
input_file: Path, input_file: Path,
output_file: Path, output_file: Path,
video_writer: VideoWriter,
detected_box_objects: list[DetectedObjectBox], detected_box_objects: list[DetectedObjectBox],
transformation_matrix): transformation_matrix):
self.input_path = input_file self.input_path = input_file
self.output_path = output_file self.output_path = output_file
self.output_json_path = output_file.with_suffix(".json") self.output_json_path = output_file.with_suffix(".json")
self.video_writer = video_writer
self.detected_box_objects = sorted(detected_box_objects, reverse=True) self.detected_box_objects = sorted(detected_box_objects, reverse=True)
self.transformation_matrix = transformation_matrix self.transformation_matrix = transformation_matrix
self.points = [] self.points = []
@@ -93,78 +97,62 @@ class DodgeballTracker:
for d in tracker_data: for d in tracker_data:
self.print_box(d, frame_idx, frame_ts) self.print_box(d, frame_idx, frame_ts)
def plot_boxe_to_frame(self, data, frame): def plot_box_to_frame(self, data, frame: VideoFrame):
confidence = float(data[4]) confidence = float(data[4])
for detected_box_object in self.detected_box_objects: for detected_box_object in self.detected_box_objects:
if detected_box_object.min_threshold < confidence: if detected_box_object.min_threshold < confidence:
xmin, ymin, xmax, ymax = self.extract_box(data) # xmin, ymin, xmax, ymax = self.extract_box(data)
cv2.rectangle(frame, (xmin, ymin), (xmax, ymax), detected_box_object.color, 2) # cv2.rectangle(frame, (xmin, ymin), (xmax, ymax), detected_box_object.color, 2)
return True return True
return False return False
def run_model_on_frame(self, model, frame): @pa.check_output(DetectedObject_)
return model(frame)[0] def run_model_on_frame(self, model, frame: VideoFrame):
model_outputs = model(frame)[0]
def crazy_experiment(self, frame): boxes = model_outputs.boxes.data.cpu().numpy()
cv2.putText(frame, columns=['xmin', 'ymin', 'xmax', 'ymin', 'score', 'category']
"Hello world", return pd.DataFrame(boxes, columns=columns)
(50, 50),
cv2.FONT_HERSHEY_SIMPLEX,
2,
(0, 255, 0), 8)
cv2.line(frame, (0, 0), (511, 511), (255, 0, 0), 5)
pts = np.array([[50, 50], [500, 50], [500, 500], [50, 500], [50, 50]], np.int32)
pts = pts.reshape((-1, 1, 2))
cv2.polylines(frame, pts, True, (0, 255, 255), 8)
def persist_points(self): def persist_points(self):
with open(self.output_json_path, "wt") as file_: with open(self.output_json_path, "wt") as file_:
json.dump({"points": self.points}, file_, indent=4) json.dump({"points": self.points}, file_, indent=4)
def _get_tracker(self): def _get_tracker(self) -> DeepOCSORT:
return DeepOCSORT( return DeepOCSORT(
model_weights=Path('lmbn_n_cuhk03_d.pt'), # which ReID model to use Path('lmbn_n_cuhk03_d.pt'), # which ReID model to use
device=torch.device("mps"), get_best_available_torch_device(),
fp16=True, True,
) )
def _get_detection_model(self): def _get_detection_model(self):
""" """
load the pre-trained YOLOv8n model load the pre-trained YOLOv8n model
""" """
return YOLO("yolov8n.pt") return YOLO("yolo11n.pt", verbose=True)
def update_tracker(self, tracker: DeepOCSORT, detected_objs, frame: VideoFrame):
data_ = tracker.update(detected_objs.to_numpy(), frame)
columns = ['xmin', 'ymin', 'xmax', 'ymin', 'object_id', 'score', 'category', 'index']
return pd.DataFrame(data_, columns=columns)
def main(self): def main(self):
# define some constants # define some constants
video_cap = cv2.VideoCapture(str(self.input_path)) video_cap = cv2.VideoCapture(str(self.input_path))
writer = create_video_writer(video_cap, str(self.output_path))
tracker = self._get_tracker() tracker = self._get_tracker()
# load the pre-trained YOLOv8n model
model = self._get_detection_model() model = self._get_detection_model()
for i, (frame, ts) in enumerate(iter_frames(video_cap)): for i, (frame, ts) in enumerate(iter_frames(video_cap)):
# run the YOLO model on the frame # run the YOLO model on the frame
res = [] detected_objs = self.run_model_on_frame(model, frame)
detections = self.run_model_on_frame(model, frame) tracked_obj = self.update_tracker(tracker, detected_objs, frame)
for data in detections.boxes.data.tolist(): # self.video_writer.plot_boxes_to_frame(detected_objs, frame)
is_good_box = self.plot_boxe_to_frame(data, frame) #
if is_good_box: # self.video_writer.write_frame(frame)
res.append(data)
# show the frame to our screen if self.video_writer.wait():
data_ = tracker.update(np.array(res), frame)
self.print_tracker_data(data_, i, ts)
self.write_frame(writer, frame)
if cv2.waitKey(1) == ord("q"):
break break
video_cap.release() video_cap.release()
writer.release()
cv2.destroyAllWindows()
self.persist_points() self.persist_points()
+59
View File
@@ -0,0 +1,59 @@
from typing import NewType
from dataclasses import dataclass
import numpy as np
import pandera as pa
from pandera.dtypes import Float32
XCoord = NewType('XCoord', float)
YCoord = NewType('YCoord', float)
Score = NewType('Confidence', float)
Category = NewType('Category', float)
@dataclass
class Point:
x: XCoord
y: YCoord
VideoFrame = NewType('Frame', float)
VideoTimestamp = float
@dataclass
class DetectedObject:
xmin: XCoord
ymin: YCoord
xmax: XCoord
ymax: YCoord
score: Score
category: Category
def as_int_box(self) -> tuple[tuple[int, int], tuple[int, int]]:
return (int(self.xmin), int(self.ymin)), (int(self.xmax), int(self.ymax))
def as_nparray(self):
return np.array([self.xmin, self.ymax, self.xmax, self.ymax, self.score, self.category])
DetectedObject_ = pa.DataFrameSchema({
"xmin": pa.Column(Float32),
"ymin": pa.Column(Float32),
"xmax": pa.Column(Float32),
"ymin": pa.Column(Float32),
"score": pa.Column(Float32),
"category": pa.Column(Float32),
})
TrackedDetectedObject_ = pa.DataFrameSchema({
"xmin": pa.Column(Float32),
"ymin": pa.Column(Float32),
"xmax": pa.Column(Float32),
"ymin": pa.Column(Float32),
"object_id": pa.Column(Float32),
"score": pa.Column(Float32),
"category": pa.Column(Float32),
"index": pa.Column(Float32),
})
Color = tuple[int, int, int]
+119
View File
@@ -0,0 +1,119 @@
import abc
from pathlib import Path
from dodgeballtracker.typing import VideoFrame, DetectedObject, Color
import matplotlib
import cv2
class DetectedObjectBox:
def __init__(self, min_threshold: float, color: Color):
self.min_threshold = min_threshold
self.color = color
def __lt__(self, other):
return self.min_threshold < other.min_threshold
@classmethod
def from_viridis(cls, min_threshold):
cm = matplotlib.colormaps['viridis']
color: Color = tuple((int(255 * cm(min_threshold)[i]) for i in range(3)))
return cls(min_threshold, color)
def create_video_writer(video_cap: cv2.VideoCapture, output_filename: Path) -> cv2.VideoWriter:
# grab the width, height, and fps of the frames in the video stream.
frame_width = int(video_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(video_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = int(video_cap.get(cv2.CAP_PROP_FPS))
# initialize the FourCC and a video writer object
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
writer = cv2.VideoWriter(str(output_filename.absolute()),
fourcc,
fps,
(frame_width, frame_height))
return writer
class VideoWriter(abc.ABC):
@abc.abstractmethod
def write_frame(self, frame: VideoFrame) -> None:
pass
@abc.abstractmethod
def plot_boxes_to_frame(self, data: list[DetectedObject], frame: VideoFrame) -> None:
pass
@abc.abstractmethod
def close(self) -> None:
pass
@abc.abstractmethod
def wait(self) -> bool:
pass
class NoopVideoWriter(VideoWriter):
def plot_boxes_to_frame(self, boxes: list[DetectedObject], frame: VideoFrame) -> None:
pass
def write_frame(self, frame: VideoFrame) -> None:
pass
def close(self) -> None:
pass
def wait(self) -> bool:
return False
class MP4VVideoWriter(VideoWriter):
def __init__(self, video_writer: cv2.VideoWriter, thresholds: list[DetectedObjectBox]) -> None:
self._video_writer = video_writer
self._thresholds = thresholds
def write_frame(self, frame: VideoFrame) -> None:
self._video_writer.write(frame)
def plot_box_to_frame(self, data: DetectedObject, frame: VideoFrame) -> None:
confidence = float(data.score)
for threshold in self._thresholds:
if threshold.min_threshold < confidence:
# xmin, ymin, xmax, ymax = self._extract_box(data)
cv2.rectangle(frame, *data.as_int_box(), threshold.color, 2)
return
def plot_boxes_to_frame(self, boxes: list[DetectedObject], frame: VideoFrame) -> None:
for box in boxes:
self.plot_box_to_frame(box, frame)
def close(self) -> None:
self._video_writer.release()
cv2.destroyAllWindows()
def wait(self) -> bool:
return False
@classmethod
def from_frame(cls, input_: Path, output: Path, thresholds: list[float]) -> VideoWriter:
object_drawers = [DetectedObjectBox.from_viridis(t) for t in thresholds]
video_cap = cv2.VideoCapture(str(input_))
try:
return cls(create_video_writer(video_cap, output), object_drawers)
finally:
video_cap.release()
class MP4VVideoWriterWithFrame(MP4VVideoWriter):
def write_frame(self, frame: VideoFrame) -> None:
super().write_frame(frame)
cv2.imshow("Frame", frame)
def wait(self) -> bool:
return cv2.waitKey(1) == ord("q")
Executable
+7
View File
@@ -0,0 +1,7 @@
#!/usr/bin/env bash
yt-dlp --write-info-json \
--output data/full.mp4 \
'https://www.youtube.com/watch?v=Spu6OlAZHUo'
ffmpeg -ss 00:19:15.00 -i data/full.mp4.webm -t 00:00:30.00 -c copy data/small.mp4
Generated
+116
View File
@@ -0,0 +1,116 @@
{
"nodes": {
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1726560853,
"narHash": "sha256-X6rJYSESBVr3hBoH0WbKE5KvhPU5bloyZ2L4K60/fPQ=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "c1dfcf08411b08f6b8615f7d8971a2bfa81d5e8a",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"flake-utils_2": {
"inputs": {
"systems": "systems_2"
},
"locked": {
"lastModified": 1726560853,
"narHash": "sha256-X6rJYSESBVr3hBoH0WbKE5KvhPU5bloyZ2L4K60/fPQ=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "c1dfcf08411b08f6b8615f7d8971a2bfa81d5e8a",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1730272153,
"narHash": "sha256-B5WRZYsRlJgwVHIV6DvidFN7VX7Fg9uuwkRW9Ha8z+w=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "2d2a9ddbe3f2c00747398f3dc9b05f7f2ebb0f53",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"opencv-python-related": {
"inputs": {
"flake-utils": "flake-utils_2",
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1730543263,
"narHash": "sha256-bosBOrQgq6OKhGDRg9mHakjx1pof79ZdQhBQUADNlf8=",
"owner": "all-dressed-programming",
"repo": "opencv-python-related",
"rev": "eb2f223c301019bcadade89a388790c2e32ce9d6",
"type": "gitlab"
},
"original": {
"owner": "all-dressed-programming",
"repo": "opencv-python-related",
"type": "gitlab"
}
},
"root": {
"inputs": {
"flake-utils": "flake-utils",
"nixpkgs": "nixpkgs",
"opencv-python-related": "opencv-python-related"
}
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
},
"systems_2": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
}
},
"root": "root",
"version": 7
}
+78
View File
@@ -0,0 +1,78 @@
{
description = "Pre-built CPU-only OpenCV packages for Python. ";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
opencv-python-related.url =
"gitlab:all-dressed-programming/opencv-python-related";
opencv-python-related.inputs.nixpkgs.follows = "nixpkgs";
flake-utils.url = "github:numtide/flake-utils";
};
nixConfig = {
extra-substituters = [ "https://cuda-maintainers.cachix.org" ];
extra-trusted-public-keys = [
"cuda-maintainers.cachix.org-1:0dq3bujKpuEPMCX6U4WylrUDZ9JyUG0VpVZa7CNfq5E="
];
};
outputs = { self, nixpkgs, flake-utils, opencv-python-related }:
flake-utils.lib.eachDefaultSystem (system:
let
pkgs = import nixpkgs {
system = system;
config.allowUnfree = true;
};
pythonPackages = pkgs.python312Packages
// opencv-python-related.packages.${system}.python312Packages;
pandera = pkgs.python3Packages.buildPythonPackage {
version = "0.5.11";
pname = "lapx";
pyproject = true;
src = pkgs.python3Packages.fetchPypi {
pname = "pandera";
version = "0.20.4";
hash = "sha256-zPYXgpPvnUOT3Ed25HR349LdUcgA7N/t7Gf/9Q9K08I=";
};
propagatedBuildInputs = with pythonPackages; [ multimethod
numpy
pandas
pydantic
typeguard
typing-inspect
wrapt
];
nativeBuildInputs = with pythonPackages; [
setuptools
];
meta = with pkgs.lib; {
description = "The Open-source Framework for Precision Data Testing";
homepage = "https://github.com/unionai-oss/pandera";
license = pkgs.lib.licenses.mit;
maintainers = with maintainers; [ ];
};
};
virtual-env = pkgs.python312.withPackages (ps: [
ps.matplotlib
ps.torchWithCuda
ps.jupyter
pythonPackages.opencv4
pythonPackages.boxmot
pythonPackages.ultralytics
pythonPackages.click
pandera
]);
in {
packages = { env = virtual-env; pandera = pandera; };
devShells.default = pkgs.mkShell {
buildInputs = [ virtual-env pkgs.yt-dlp pkgs.ffmpeg_7 ];
};
});
}
+90
View File
@@ -0,0 +1,90 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Dodgeball Tracker</title>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<meta name="description" content="" />
<link rel="icon" href="favicon.png">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css">
<link rel="stylesheet" href="style.css">
<script src="main-old.js" type="module"></script>
</head>
<body>
<h1 class="title is-1">Dodgeball Tracker</h1>
<div id="new"></div>
<h3 id="first-ts"></h3>
<div>
<select>
<option value="lmbn_n_cuhk03_d">lmbn_n_cuhk03_d</option>
</select>
</div>
<svg width="900" height="450" id="first" style="background-color: lightgray">
</svg>
<br>
<svg width="900" height="450" >
<rect x="0" y="0" width="900" height="450" class="court-border"></rect>
<line x1="450" y1="0" x2="450" y2="450" class="court-border"></line>
<line x1="300" y1="0" x2="300" y2="450" class="return-line"></line>
<line x1="600" y1="0" x2="600" y2="450" class="return-line"></line>
<rect x="0" y="157.5" width="15" height="15"
style="fill: red;" id="rect-1"></rect>
<rect x="0" y="157.5" width="15" height="15"
style="fill: blue;" id="rect-2"></rect>
<rect x="0" y="157.5" width="15" height="15"
style="fill: yellow;" id="rect-3"></rect>
<rect x="0" y="157.5" width="15" height="15"
style="fill: pink;" id="rect-4"></rect>
<rect x="0" y="157.5" width="15" height="15"
style="fill: purple;" id="rect-5"></rect>
<rect x="0" y="157.5" width="15" height="15"
style="fill: black;" id="rect-6"></rect>
<rect x="0" y="157.5" width="15" height="15"
style="stroke: red; fill-opacity: 0;" id="rect-7"></rect>
<rect x="0" y="157.5" width="15" height="15"
style="stroke: blue; fill-opacity: 0;" id="rect-8"></rect>
<rect x="0" y="157.5" width="15" height="15"
style="stroke: yellow; fill-opacity: 0;" id="rect-9"></rect>
<rect x="0" y="157.5" width="15" height="15"
style="stroke: pink; fill-opacity: 0;" id="rect-10"></rect>
<rect x="0" y="157.5" width="15" height="15"
style="stroke: purple; fill-opacity: 0;" id="rect-11"></rect>
<rect x="0" y="157.5" width="15" height="15"
style="stroke: black; fill-opacity: 0;" id="rect-12"></rect>
</svg>
<div>
<button id="play">play</button> <br>
<button id="pause">pause</button>
<br>
<input type="number" id="seek-value">
<button id="seek">seek</button>
</div>
</body>
</html>
+2 -14
View File
@@ -2,29 +2,17 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<title>Animation</title> <title>Dodgeball Tracker</title>
<meta name="viewport" content="width=device-width,initial-scale=1" /> <meta name="viewport" content="width=device-width,initial-scale=1" />
<meta name="description" content="" /> <meta name="description" content="" />
<link rel="icon" href="favicon.png"> <link rel="icon" href="favicon.png">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css">
<link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="style.css">
<script src="main.js" type="module"></script> <script src="main.js" type="module"></script>
</head> </head>
<body> <body>
<h1>Hello, world!</h1>
<h3 id="first-ts"></h3>
<div>
<select>
<option value="lmbn_n_cuhk03_d">lmbn_n_cuhk03_d</option>
</select>
</div>
<svg width="900" height="450" id="first" style="background-color: lightgray">
</svg>
</body> </body>
</html> </html>
+118
View File
@@ -0,0 +1,118 @@
import anime from "https://esm.sh/animejs@3.2.2";
import m from "https://esm.sh/mithril@2.2.2"
import colormap from "https://esm.sh/colormap@2.3.2"
const second = 1000;
const canvasWidth = Number.parseFloat(document.querySelector("svg").getAttribute("width"));
const canvasHeight = Number.parseFloat(document.querySelector("svg").getAttribute("height"));
function gaussianRandom(mean=0, stdev=1) {
const u = 1 - Math.random(); // Converting [0,1) to (0,1]
const v = Math.random();
const z = Math.sqrt( -2.0 * Math.log( u ) ) * Math.cos( 2.0 * Math.PI * v );
// Transform to the desired mean and standard deviation:
return z * stdev + mean;
}
function* brownian(n){
let x = 0;
for(let i = 0; i < n; i ++){
x += gaussianRandom(0, 10);
console.log(x);
yield x;
}
}
function* pseudoBrownian(n, limit){
let x = 0;
for(let i = 0; i < n; i ++){
let delta = gaussianRandom(0, 10);
if(Math.abs(x + delta) > limit){
delta = -1 * delta
}
x += delta;
yield x;
}
}
function* keyFrames(duration, framePerSeconds){
const deltaX = canvasWidth / (duration * framePerSeconds);
const limit = 0.75 * (canvasHeight / 2);
for(const deltaY of pseudoBrownian(duration * framePerSeconds, limit)){
yield {translateX: `+=${deltaX}`, translateY: deltaY};
}
}
const duration = 60;
const timeline = anime.timeline({
duration: duration * second,
autoplay: false,
easing: 'linear'});
for(let i = 1; i <= 12; i++){
timeline.add({
targets: `#rect-${i}`,
keyframes: Array.from(keyFrames(duration, 30)),
}, 0)
}
document.querySelector('#play').onclick = timeline.play;
document.querySelector('#pause').onclick = timeline.pause;
document.querySelector('#seek').onclick = function(){
const seekVal = Number.parseFloat(second * document.querySelector('#seek-value').value);
timeline.pause();
timeline.seek(seekVal);
}
function generatePoints(points, frames){
const lst = [];
const colors = colormap({
colormap: 'viridis',
nshades: new Set(points.map(p => p.objectId)).size,
format: 'hex',
alpha: 1
});
for(const point of points){
if(frames.indexOf(point.frameIndex) !== -1){
lst.push(m("text", {x: point.y, y: point.x, fill: colors[point.objectId]}, point.objectId));
}
}
return m("g", lst);
}
function getTimeStamp(points, frameId){
for(const point of points){
if(point.frameIndex === frameId){
return `${point.frameTimestamp / 1000} seconds`;
}
}
}
const url = "/dodgeball-tracker/outputs/output-lmbn_n_cuhk03_d.json";
const resp = await fetch(url);
const points = await resp.json();
function range(min, max){
const ret = [];
while(min < max){
ret.push(min);
min ++;
}
return ret
}
function getCourtLines(){
return [
m("line", {x1: 450, x2: 450, y1: 0, y2: 450, class: "court-border"}),
m("line", {x1: 300, x2: 300, y1: 0, y2: 450, class: "return-line"}),
m("line", {x1: 600, x2: 600, y1: 0, y2: 450, class: "return-line"})
]
}
m.render(document.getElementById("first"), generatePoints(points.points, range(-10, 400)));
m.render(document.getElementById("first-ts"), m("span", getTimeStamp(points.points, 80)));
+112 -5
View File
@@ -2,6 +2,44 @@ import m from "https://esm.sh/mithril@2.2.2"
import colormap from "https://esm.sh/colormap@2.3.2" import colormap from "https://esm.sh/colormap@2.3.2"
import {range} from "./util.js"; import {range} from "./util.js";
function gaussianRandom(mean=0, stdev=1) {
const u = 1 - Math.random(); // Converting [0,1) to (0,1]
const v = Math.random();
const z = Math.sqrt( -2.0 * Math.log( u ) ) * Math.cos( 2.0 * Math.PI * v );
// Transform to the desired mean and standard deviation:
return z * stdev + mean;
}
function* brownian(n){
let x = 0;
for(let i = 0; i < n; i ++){
x += gaussianRandom(0, 10);
console.log(x);
yield x;
}
}
function* pseudoBrownian(n, limit){
let x = 0;
for(let i = 0; i < n; i ++){
let delta = gaussianRandom(0, 10);
if(Math.abs(x + delta) > limit){
delta = -1 * delta
}
x += delta;
yield x;
}
}
function* keyFrames(duration, framePerSeconds){
const deltaX = canvasWidth / (duration * framePerSeconds);
const limit = 0.75 * (canvasHeight / 2);
for(const deltaY of pseudoBrownian(duration * framePerSeconds, limit)){
yield {translateX: `+=${deltaX}`, translateY: deltaY};
}
}
function generatePoints(points, frames){ function generatePoints(points, frames){
const lst = []; const lst = [];
const colors = colormap({ const colors = colormap({
@@ -26,11 +64,80 @@ function getTimeStamp(points, frameId){
} }
} }
const url = "/dodgeball-tracker/outputs/output-lmbn_n_cuhk03_d.json"; // const url = "/dodgeball-tracker/outputs/output-lmbn_n_cuhk03_d.json";
const resp = await fetch(url); // const resp = await fetch(url);
const points = await resp.json(); // const points = await resp.json();
m.render(document.getElementById("first"), generatePoints(points.points, range(-10, 400))); function getCourtLines(){
m.render(document.getElementById("first-ts"), m("span", getTimeStamp(points.points, 80))); return [
m("line", {x1: 450, x2: 450, y1: 0, y2: 450, class: "court-border"}),
m("line", {x1: 300, x2: 300, y1: 0, y2: 450, class: "return-line"}),
m("line", {x1: 600, x2: 600, y1: 0, y2: 450, class: "return-line"})
]
}
class WorkingTabs{
#datasets = []
async oninit(){
const url = "/dodgeball-tracker/outputs/index.json"
this.#datasets = (await m.request({method: "GET", url: url}))?.index ?? [];
}
tabs(){
return m("div.tabs",
m("ul",
m("li.is-active", m("a", "Info")),
m("li", m("a", "Video Player"))));
}
info(){
const options = this.#datasets.map(ds => m('option', {value: ds.id}, ds.label));
return m("div.field",
m("label.label", "Dataset"),
m("div.control",
m("div.select",
m("select", options))));
}
view(){
return m("div",
this.tabs(),
this.info())
}
}
const Court = {
view: function(){
const margin = 50
return m("svg.court-side", { width: 900 + 2 * margin, height: 450 + 2 * margin}, [
m("g.court-border#court", {transform: `translate(${margin} ${margin})`}, [
m("rect", {width: 900, height: 450, style: 'background-color: pink;'}),
getCourtLines()
])
])
}
}
// m.render(document.getElementById("new"), drawCourt());
// m.render(document.getElementById("first"), generatePoints(points.points, range(-10, 400)));
// m.render(document.getElementById("first-ts"), m("span", getTimeStamp(points.points, 80)));
const Main = {
view: function(){
return m("div", [
m("h1.title.is-1", "DodgeBall Tracker"),
m("div.columns.is-centered",
m("m.column.is-three-quarters",
m(Court),
m(WorkingTabs)))
])
}
}
m.mount(document.body, Main);
View File
Whitespace-only changes.
+4
View File
@@ -5,6 +5,10 @@
fill: gray; fill: gray;
} }
.court-side {
background-color: pink;
}
.return-line { .return-line {
stroke: blue; stroke: blue;
stroke-width: 2px; stroke-width: 2px;
-23888
View File
File diff suppressed because it is too large. Load diff
+14
View File
@@ -0,0 +1,14 @@
{
"imports": {
"preact": "https://esm.sh/preact@10.19.2",
"preact/": "https://esm.sh/preact@10.19.2/",
"@preact/signals": "https://esm.sh/*@preact/signals@1.2.1",
"@preact/signals-core": "https://esm.sh/*@preact/signals-core@1.5.0",
"$std/": "https://deno.land/std@0.208.0/"
},
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "preact"
}
}
+211
View File
@@ -0,0 +1,211 @@
{
"version": "3",
"redirects": {
"https://deno.land/x/oak/mod.ts": "https://deno.land/x/oak@v12.6.1/mod.ts",
"https://deno.land/x/oak/mod.tsx": "https://deno.land/x/oak@v12.6.1/mod.tsx"
},
"remote": {
"https://deno.land/std@0.189.0/fmt/colors.ts": "d67e3cd9f472535241a8e410d33423980bec45047e343577554d3356e1f0ef4e",
"https://deno.land/std@0.189.0/streams/write_all.ts": "aec90152978581ea62d56bb53a5cbf487e6a89c902f87c5969681ffbdf32b998",
"https://deno.land/std@0.200.0/_util/os.ts": "d932f56d41e4f6a6093d56044e29ce637f8dcc43c5a90af43504a889cf1775e3",
"https://deno.land/std@0.200.0/assert/assert.ts": "9a97dad6d98c238938e7540736b826440ad8c1c1e54430ca4c4e623e585607ee",
"https://deno.land/std@0.200.0/assert/assertion_error.ts": "4d0bde9b374dfbcbe8ac23f54f567b77024fb67dbb1906a852d67fe050d42f56",
"https://deno.land/std@0.200.0/async/deferred.ts": "42790112f36a75a57db4a96d33974a936deb7b04d25c6084a9fa8a49f135def8",
"https://deno.land/std@0.200.0/bytes/bytes_list.ts": "31d664f4d42fa922066405d0e421c56da89d751886ee77bbe25a88bf0310c9d0",
"https://deno.land/std@0.200.0/bytes/concat.ts": "d26d6f3d7922e6d663dacfcd357563b7bf4a380ce5b9c2bbe0c8586662f25ce2",
"https://deno.land/std@0.200.0/bytes/copy.ts": "939d89e302a9761dcf1d9c937c7711174ed74c59eef40a1e4569a05c9de88219",
"https://deno.land/std@0.200.0/bytes/ends_with.ts": "4228811ebc71615d27f065c54b5e815ec1972538772b0f413c0efe05245b472e",
"https://deno.land/std@0.200.0/bytes/equals.ts": "fc190cce412b2136979181b163ec7e05f7e7a947e39102eee4b8c0d62519ddf9",
"https://deno.land/std@0.200.0/bytes/includes_needle.ts": "76a8163126fb2f8bf86fd7f22192c3bb04bf6a20b987a095127c2ca08adf3ba6",
"https://deno.land/std@0.200.0/bytes/index_of_needle.ts": "9c06610e9611b5647ac25952e71a22e09227c9f1b8cbeeb33399bf8bf8a7f649",
"https://deno.land/std@0.200.0/bytes/last_index_of_needle.ts": "f1602f221c3b678bc4f1e1c88a70a15ab7da32c21751dbbc6c957c956951d784",
"https://deno.land/std@0.200.0/bytes/mod.ts": "e869bba1e7a2e3a9cc6c2d55471888429a544e70a840c087672e656e7ba21815",
"https://deno.land/std@0.200.0/bytes/mod.tsx": "e869bba1e7a2e3a9cc6c2d55471888429a544e70a840c087672e656e7ba21815",
"https://deno.land/std@0.200.0/bytes/repeat.ts": "6f5e490d8d72bcbf8d84a6bb04690b9b3eb5822c5a11687bca73a2318a842294",
"https://deno.land/std@0.200.0/bytes/starts_with.ts": "3e607a70c9c09f5140b7a7f17a695221abcc7244d20af3eb47ccbb63f5885135",
"https://deno.land/std@0.200.0/crypto/keystack.ts": "877ab0f19eb7d37ad6495190d3c3e39f58e9c52e0b6a966f82fd6df67ca55f90",
"https://deno.land/std@0.200.0/crypto/timing_safe_equal.ts": "7b0a4d2ef1c17590e0ad6c0cb1776369d2ba80cd99e945005e117851690507fe",
"https://deno.land/std@0.200.0/encoding/base64.ts": "144ae6234c1fbe5b68666c711dc15b1e9ee2aef6d42b3b4345bf9a6c91d70d0d",
"https://deno.land/std@0.200.0/encoding/base64url.ts": "2ed4ba122b20fedf226c5d337cf22ee2024fa73a8f85d915d442af7e9ce1fae1",
"https://deno.land/std@0.200.0/http/_negotiation/common.ts": "14d1a52427ab258a4b7161cd80e1d8a207b7cc64b46e911780f57ead5f4323c6",
"https://deno.land/std@0.200.0/http/_negotiation/encoding.ts": "ff747d107277c88cb7a6a62a08eeb8d56dad91564cbcccb30694d5dc126dcc53",
"https://deno.land/std@0.200.0/http/_negotiation/language.ts": "7bcddd8db3330bdb7ce4fc00a213c5547c1968139864201efd67ef2d0d51887d",
"https://deno.land/std@0.200.0/http/_negotiation/media_type.ts": "58847517cd549384ad677c0fe89e0a4815be36fe7a303ea63cee5f6a1d7e1692",
"https://deno.land/std@0.200.0/http/cookie_map.ts": "64601025a7d24c3ebd80a169ccc99145bdbfc60606935348e1d4366d0bf9010d",
"https://deno.land/std@0.200.0/http/etag.ts": "807382795850cde5c437c74bcc09392bc0fc56de348fc1271f383f4b28935b9f",
"https://deno.land/std@0.200.0/http/http_errors.ts": "bbda34819060af86537cecc9dc8e045f877130808b7e7acde4197c5328e852d0",
"https://deno.land/std@0.200.0/http/http_status.ts": "8a7bcfe3ac025199ad804075385e57f63d055b2aed539d943ccc277616d6f932",
"https://deno.land/std@0.200.0/http/method.ts": "e66c2a015cb46c21ab0bb3589aa4fca43143a506cb324ffdfd42d2edef7bc0c4",
"https://deno.land/std@0.200.0/http/negotiation.ts": "46e74a6bad4b857333a58dc5b50fe8e5a4d5267e97292293ea65f980bd918086",
"https://deno.land/std@0.200.0/http/server_sent_event.ts": "29f707c1afa5278ac0315ac115ee679d6b93596d5af3fad5ef33f04254ca76c1",
"https://deno.land/std@0.200.0/http/user_agent.ts": "35d3c70d0926b0e121b8c1bbc324b3522479158acaa4f0c43928362b7bf4e6f4",
"https://deno.land/std@0.200.0/io/buf_reader.ts": "2bccff0878537ef201c5051fc0db0ce8196388c5ea69d2be6be1900fe48c5f4b",
"https://deno.land/std@0.200.0/io/buf_writer.ts": "48c33c8f00b61dcbc7958706741cec8e59810bd307bc6a326cbd474fe8346dfd",
"https://deno.land/std@0.200.0/io/buffer.ts": "4d6883daeb2e698579c4064170515683d69f40f3de019bfe46c5cf31e74ae793",
"https://deno.land/std@0.200.0/io/copy_n.ts": "c055296297b9d4897d90d1ac056b072dc02614e60c67f438e23fbce052ea4c69",
"https://deno.land/std@0.200.0/io/limited_reader.ts": "6c9a216f8eef39c1ee2a6b37a29372c8fc63455b2eeb91f06d9646f8f759fc8b",
"https://deno.land/std@0.200.0/io/mod.ts": "2665bcccc1fd6e8627cca167c3e92aaecbd9897556b6f69e6d258070ef63fd9b",
"https://deno.land/std@0.200.0/io/mod.tsx": "2665bcccc1fd6e8627cca167c3e92aaecbd9897556b6f69e6d258070ef63fd9b",
"https://deno.land/std@0.200.0/io/multi_reader.ts": "9c2a0a31686c44b277e16da1d97b4686a986edcee48409b84be25eedbc39b271",
"https://deno.land/std@0.200.0/io/read_delim.ts": "c02b93cc546ae8caad8682ae270863e7ace6daec24c1eddd6faabc95a9d876a3",
"https://deno.land/std@0.200.0/io/read_int.ts": "7cb8bcdfaf1107586c3bacc583d11c64c060196cb070bb13ae8c2061404f911f",
"https://deno.land/std@0.200.0/io/read_lines.ts": "c526c12a20a9386dc910d500f9cdea43cba974e853397790bd146817a7eef8cc",
"https://deno.land/std@0.200.0/io/read_long.ts": "f0aaa420e3da1261c5d33c5e729f09922f3d9fa49f046258d4ff7a00d800c71e",
"https://deno.land/std@0.200.0/io/read_range.ts": "46a2263d0f8369b6d9abb0b25d99ceb65ff08d621fc57bcc53832e6979295043",
"https://deno.land/std@0.200.0/io/read_short.ts": "805cb329574b850b84bf14a92c052c59b5977a492cd780c41df8ad40826c1a20",
"https://deno.land/std@0.200.0/io/read_string_delim.ts": "5dc9f53bdf78e7d4ee1e56b9b60352238ab236a71c3e3b2a713c3d78472a53ce",
"https://deno.land/std@0.200.0/io/slice_long_to_bytes.ts": "48d9bace92684e880e46aa4a2520fc3867f9d7ce212055f76ecc11b22f9644b7",
"https://deno.land/std@0.200.0/io/string_reader.ts": "da0f68251b3d5b5112485dfd4d1b1936135c9b4d921182a7edaf47f74c25cc8f",
"https://deno.land/std@0.200.0/io/string_writer.ts": "8a03c5858c24965a54c6538bed15f32a7c72f5704a12bda56f83a40e28e5433e",
"https://deno.land/std@0.200.0/media_types/_db.ts": "7606d83e31f23ce1a7968cbaee852810c2cf477903a095696cdc62eaab7ce570",
"https://deno.land/std@0.200.0/media_types/_util.ts": "916efbd30b6148a716f110e67a4db29d6949bf4048997b754415dd7e42c52378",
"https://deno.land/std@0.200.0/media_types/content_type.ts": "ad98a5aa2d95f5965b2796072284258710a25e520952376ed432b0937ce743bc",
"https://deno.land/std@0.200.0/media_types/extension.ts": "a7cd28c9417143387cdfed27d4e8607ebcf5b1ec27eb8473d5b000144689fe65",
"https://deno.land/std@0.200.0/media_types/extensions_by_type.ts": "43806d6a52a0d6d965ada9d20e60a982feb40bc7a82268178d94edb764694fed",
"https://deno.land/std@0.200.0/media_types/format_media_type.ts": "f5e1073c05526a6f5a516ac5c5587a1abd043bf1039c71cde1166aa4328c8baf",
"https://deno.land/std@0.200.0/media_types/get_charset.ts": "18b88274796fda5d353806bf409eb1d2ddb3f004eb4bd311662c4cdd8ac173db",
"https://deno.land/std@0.200.0/media_types/mod.ts": "d3f0b99f85053bc0b98ecc24eaa3546dfa09b856dc0bbaf60d8956d2cdd710c8",
"https://deno.land/std@0.200.0/media_types/mod.tsx": "d3f0b99f85053bc0b98ecc24eaa3546dfa09b856dc0bbaf60d8956d2cdd710c8",
"https://deno.land/std@0.200.0/media_types/parse_media_type.ts": "8cb0144385c555c9ce81881b7cee3fbb746f23b4af988fecdb7bd01ef8cc35b1",
"https://deno.land/std@0.200.0/media_types/type_by_extension.ts": "daa801eb0f11cdf199445d0f1b656cf116d47dcf9e5b85cc1e6b4469f5ee0432",
"https://deno.land/std@0.200.0/media_types/vendor/mime-db.v1.52.0.ts": "6925bbcae81ca37241e3f55908d0505724358cda3384eaea707773b2c7e99586",
"https://deno.land/std@0.200.0/path/_basename.ts": "057d420c9049821f983f784fd87fa73ac471901fb628920b67972b0f44319343",
"https://deno.land/std@0.200.0/path/_constants.ts": "e49961f6f4f48039c0dfed3c3f93e963ca3d92791c9d478ac5b43183413136e0",
"https://deno.land/std@0.200.0/path/_dirname.ts": "355e297236b2218600aee7a5301b937204c62e12da9db4b0b044993d9e658395",
"https://deno.land/std@0.200.0/path/_extname.ts": "eaaa5aae1acf1f03254d681bd6a8ce42a9cb5b7ff2213a9d4740e8ab31283664",
"https://deno.land/std@0.200.0/path/_format.ts": "4a99270d6810f082e614309164fad75d6f1a483b68eed97c830a506cc589f8b4",
"https://deno.land/std@0.200.0/path/_from_file_url.ts": "7e4e5626089785adddb061f1b9f4932d6b21c7df778e7449531a11e32048245c",
"https://deno.land/std@0.200.0/path/_interface.ts": "6471159dfbbc357e03882c2266d21ef9afdb1e4aa771b0545e90db58a0ba314b",
"https://deno.land/std@0.200.0/path/_is_absolute.ts": "05dac10b5e93c63198b92e3687baa2be178df5321c527dc555266c0f4f51558c",
"https://deno.land/std@0.200.0/path/_join.ts": "fd78555bc34d5f188918fc7018dfe8fe2df5bbad94a3b30a433666c03934d77f",
"https://deno.land/std@0.200.0/path/_normalize.ts": "a19ec8706b2707f9dd974662a5cd89fad438e62ab1857e08b314a8eb49a34d81",
"https://deno.land/std@0.200.0/path/_parse.ts": "0f9b0ff43682dd9964eb1c4398610c4e165d8db9d3ac9d594220217adf480cfa",
"https://deno.land/std@0.200.0/path/_relative.ts": "27bdeffb5311a47d85be26d37ad1969979359f7636c5cd9fcf05dcd0d5099dc5",
"https://deno.land/std@0.200.0/path/_resolve.ts": "7a3616f1093735ed327e758313b79c3c04ea921808ca5f19ddf240cb68d0adf6",
"https://deno.land/std@0.200.0/path/_to_file_url.ts": "739bfda583598790b2e77ce227f2bb618f6ebdb939788cea47555b43970ec58c",
"https://deno.land/std@0.200.0/path/_to_namespaced_path.ts": "0d5f4caa2ed98ef7a8786286df6af804b50e38859ae897b5b5b4c8c5930a75c8",
"https://deno.land/std@0.200.0/path/_util.ts": "4e191b1bac6b3bf0c31aab42e5ca2e01a86ab5a0d2e08b75acf8585047a86221",
"https://deno.land/std@0.200.0/path/basename.ts": "6f08fbb90dbfcf320765b3abb01f995b1723f75e2534acfd5380e202c802a3aa",
"https://deno.land/std@0.200.0/path/common.ts": "ee7505ab01fd22de3963b64e46cff31f40de34f9f8de1fff6a1bd2fe79380000",
"https://deno.land/std@0.200.0/path/dirname.ts": "098996822a31b4c46e1eb52a19540d3c6f9f54b772fc8a197939eeabc29fca2f",
"https://deno.land/std@0.200.0/path/extname.ts": "9b83c62fd16505739541f7a3ab447d8972da39dbf668d47af2f93206c2480893",
"https://deno.land/std@0.200.0/path/format.ts": "cb22f95cc7853d590b87708cc9441785e760d711188facff3d225305a8213aca",
"https://deno.land/std@0.200.0/path/from_file_url.ts": "a6221cfc928928ec4d9786d767dfac98fa2ab746af0786446c9834a07b98817e",
"https://deno.land/std@0.200.0/path/glob.ts": "d479e0a695621c94d3fd7fe7abd4f9499caf32a8de13f25073451c6ef420a4e1",
"https://deno.land/std@0.200.0/path/is_absolute.ts": "6b3d36352eb7fa29edb53f9e7b09b1aeb022a3c5465764f6cc5b8c41f9736197",
"https://deno.land/std@0.200.0/path/join.ts": "4a2867ff2f3c81ffc9eb3d56dade16db6f8bd3854f269306d23dad4115089c84",
"https://deno.land/std@0.200.0/path/mod.ts": "7765507696cb321994cdacfc19ee3ba61e8e3ebf4bd98fa75a276cf5dc18ce2a",
"https://deno.land/std@0.200.0/path/mod.tsx": "7765507696cb321994cdacfc19ee3ba61e8e3ebf4bd98fa75a276cf5dc18ce2a",
"https://deno.land/std@0.200.0/path/normalize.ts": "7d992cd262b2deefa842d93a8ba2ed51f3949ba595b1d07f627ac2cddbc74808",
"https://deno.land/std@0.200.0/path/parse.ts": "031fe488b3497fb8312fc1dc3c3d6c2d80707edd9c661e18ee9fd20f95edf322",
"https://deno.land/std@0.200.0/path/posix.ts": "0a1c1952d132323a88736d03e92bd236f3ed5f9f079e5823fae07c8d978ee61b",
"https://deno.land/std@0.200.0/path/relative.ts": "7db80c5035016174267da16321a742d76e875215c317859a383b12f413c6f5d6",
"https://deno.land/std@0.200.0/path/resolve.ts": "103b62207726a27f28177f397008545804ecb20aaf00623af1f622b18cd80b9f",
"https://deno.land/std@0.200.0/path/separator.ts": "0fb679739d0d1d7bf45b68dacfb4ec7563597a902edbaf3c59b50d5bcadd93b1",
"https://deno.land/std@0.200.0/path/to_file_url.ts": "dd32f7a01bbf3b15b5df46796659984b372973d9b2d7d59bcf0eb990763a0cb5",
"https://deno.land/std@0.200.0/path/to_namespaced_path.ts": "4e643ab729bf49ccdc166ad48d2de262ff462938fcf2a44a4425588f4a0bd690",
"https://deno.land/std@0.200.0/path/win32.ts": "8b3f80ef7a462511d5e8020ff490edcaa0a0d118f1b1e9da50e2916bdd73f9dd",
"https://deno.land/std@0.200.0/streams/_common.ts": "f45cba84f0d813de3326466095539602364a9ba521f804cc758f7a475cda692d",
"https://deno.land/std@0.200.0/streams/buffer.ts": "6cd773d22cf21bb988a98cc551b5abfc4c3b03516f93eaa3fb6f2f6e16032deb",
"https://deno.land/std@0.200.0/streams/byte_slice_stream.ts": "c46d7c74836fc8c1a9acd9fe211cbe1bbaaee1b36087c834fb03af4991135c3a",
"https://deno.land/std@0.200.0/streams/copy.ts": "75cbc795ff89291df22ddca5252de88b2e16d40c85d02840593386a8a1454f71",
"https://deno.land/std@0.200.0/streams/delimiter_stream.ts": "f69e849b3d1f59f02424497273f411105a6f76a9f13da92aeeb9a2d554236814",
"https://deno.land/std@0.200.0/streams/early_zip_readable_streams.ts": "4005fa74162b943f79899e5d7cb96adcbc0a6b867f9144974ed12d30e0a556e1",
"https://deno.land/std@0.200.0/streams/iterate_reader.ts": "bbec1d45c2df2c0c5920bad0549351446fdc8e0886d99e95959b259dbcdb6072",
"https://deno.land/std@0.200.0/streams/limited_bytes_transform_stream.ts": "05dc592ffaab83257494d22dd53917e56243c26e5e3129b3f13ddbbbc4785048",
"https://deno.land/std@0.200.0/streams/limited_transform_stream.ts": "d69ab790232c1b86f53621ad41ef03c235f2abb4b7a1cd51960ad6e12ee55e38",
"https://deno.land/std@0.200.0/streams/merge_readable_streams.ts": "dc2db0cbf1b14d999aa2aa2a2a1ba24ce58953878f29845ed9319321d0a01fab",
"https://deno.land/std@0.200.0/streams/mod.ts": "c07ec010e700b9ea887dc36ca08729828bc7912f711e4054e24d33fd46282252",
"https://deno.land/std@0.200.0/streams/mod.tsx": "c07ec010e700b9ea887dc36ca08729828bc7912f711e4054e24d33fd46282252",
"https://deno.land/std@0.200.0/streams/read_all.ts": "ee319772fb0fd28302f97343cc48dfcf948f154fd0d755d8efe65814b70533be",
"https://deno.land/std@0.200.0/streams/readable_stream_from_iterable.ts": "a355e97ba8671a4611ae9671c1f33c4a7e6a1b42fbdc9a399338ac3d6f875364",
"https://deno.land/std@0.200.0/streams/readable_stream_from_reader.ts": "bfc416c4576a30aac6b9af22c9dc292c20c6742141ee7c55b5e85460beb0c54e",
"https://deno.land/std@0.200.0/streams/reader_from_iterable.ts": "55f68110dce3f8f2c87b834d95f153bc904257fc65175f9f2abe78455cb8047c",
"https://deno.land/std@0.200.0/streams/reader_from_stream_reader.ts": "fa4971e5615a010e49492c5d1688ca1a4d17472a41e98b498ab89a64ebd7ac73",
"https://deno.land/std@0.200.0/streams/text_delimiter_stream.ts": "20e680ab8b751390e359288ce764f9c47d164af11a263870746eeca4bc7d976b",
"https://deno.land/std@0.200.0/streams/text_line_stream.ts": "0f2c4b33a5fdb2476f2e060974cba1347cefe99a4af33c28a57524b1a34750fa",
"https://deno.land/std@0.200.0/streams/to_transform_stream.ts": "89fd367cafb3b6d80d61e2f4f1fcf66cc75723ecee8d474b495f022264ec6c3b",
"https://deno.land/std@0.200.0/streams/writable_stream_from_writer.ts": "56fff5c82fb736fdd669b567cc0b2bbbe0351002cd13254eae26c366e2bed89a",
"https://deno.land/std@0.200.0/streams/write_all.ts": "aec90152978581ea62d56bb53a5cbf487e6a89c902f87c5969681ffbdf32b998",
"https://deno.land/std@0.200.0/streams/writer_from_stream_writer.ts": "07c7ee025151a190f37fc42cbb01ff93afc949119ebddc6e0d0df14df1bf6950",
"https://deno.land/std@0.200.0/streams/zip_readable_streams.ts": "a9d81aa451240f79230add674809dbee038d93aabe286e2d9671e66591fc86ca",
"https://deno.land/std@0.84.0/_util/assert.ts": "2f868145a042a11d5ad0a3c748dcf580add8a0dbc0e876eaa0026303a5488f58",
"https://deno.land/std@0.84.0/_util/os.ts": "e282950a0eaa96760c0cf11e7463e66babd15ec9157d4c9ed49cc0925686f6a7",
"https://deno.land/std@0.84.0/path/_constants.ts": "1247fee4a79b70c89f23499691ef169b41b6ccf01887a0abd131009c5581b853",
"https://deno.land/std@0.84.0/path/_interface.ts": "1fa73b02aaa24867e481a48492b44f2598cd9dfa513c7b34001437007d3642e4",
"https://deno.land/std@0.84.0/path/_util.ts": "f4fa69aa3cbbd8568763bfc43c7236875015ba343602d8bafd332b4b4243681b",
"https://deno.land/std@0.84.0/path/common.ts": "eaf03d08b569e8a87e674e4e265e099f237472b6fd135b3cbeae5827035ea14a",
"https://deno.land/std@0.84.0/path/glob.ts": "4a524c1c9da3e79a9fdabdc6e850cd9e41bdf31e442856ffa19c5b123268ca95",
"https://deno.land/std@0.84.0/path/mod.ts": "4465dc494f271b02569edbb4a18d727063b5dbd6ed84283ff906260970a15d12",
"https://deno.land/std@0.84.0/path/mod.tsx": "4465dc494f271b02569edbb4a18d727063b5dbd6ed84283ff906260970a15d12",
"https://deno.land/std@0.84.0/path/posix.ts": "1408f8ba482a4dc5fc0a7cd7be28bbbff9608d2b3b5ffdcf288ae1228d959add",
"https://deno.land/std@0.84.0/path/separator.ts": "8fdcf289b1b76fd726a508f57d3370ca029ae6976fcde5044007f062e643ff1c",
"https://deno.land/std@0.84.0/path/win32.ts": "6ca052f54500f00cd7a5172fde62900626ab620dcd5bdcf4e6f5695d001ddef6",
"https://deno.land/std@0.99.0/_util/assert.ts": "2f868145a042a11d5ad0a3c748dcf580add8a0dbc0e876eaa0026303a5488f58",
"https://deno.land/std@0.99.0/_util/os.ts": "e282950a0eaa96760c0cf11e7463e66babd15ec9157d4c9ed49cc0925686f6a7",
"https://deno.land/std@0.99.0/path/_constants.ts": "1247fee4a79b70c89f23499691ef169b41b6ccf01887a0abd131009c5581b853",
"https://deno.land/std@0.99.0/path/_interface.ts": "1fa73b02aaa24867e481a48492b44f2598cd9dfa513c7b34001437007d3642e4",
"https://deno.land/std@0.99.0/path/_util.ts": "2e06a3b9e79beaf62687196bd4b60a4c391d862cfa007a20fc3a39f778ba073b",
"https://deno.land/std@0.99.0/path/common.ts": "eaf03d08b569e8a87e674e4e265e099f237472b6fd135b3cbeae5827035ea14a",
"https://deno.land/std@0.99.0/path/glob.ts": "314ad9ff263b895795208cdd4d5e35a44618ca3c6dd155e226fb15d065008652",
"https://deno.land/std@0.99.0/path/mod.ts": "4465dc494f271b02569edbb4a18d727063b5dbd6ed84283ff906260970a15d12",
"https://deno.land/std@0.99.0/path/mod.tsx": "4465dc494f271b02569edbb4a18d727063b5dbd6ed84283ff906260970a15d12",
"https://deno.land/std@0.99.0/path/posix.ts": "f56c3c99feb47f30a40ce9d252ef6f00296fa7c0fcb6dd81211bdb3b8b99ca3b",
"https://deno.land/std@0.99.0/path/separator.ts": "8fdcf289b1b76fd726a508f57d3370ca029ae6976fcde5044007f062e643ff1c",
"https://deno.land/std@0.99.0/path/win32.ts": "77f7b3604e0de40f3a7c698e8a79e7f601dc187035a1c21cb1e596666ce112f8",
"https://deno.land/x/logger@v1.1.5/date.ts": "09041dc83c9cddb489b875f45b07336dd894c23b9dd5b47235b94180571a2efa",
"https://deno.land/x/logger@v1.1.5/deps.ts": "1b09212250f8023edd69efb798874ca19bf90c4ed7cdcc1a292dc16c5bb2cf6d",
"https://deno.land/x/logger@v1.1.5/eol.ts": "493acd048c546fd48bcd26365d4dadf3db81ce32c4611ca5b0b19e6de9f9826a",
"https://deno.land/x/logger@v1.1.5/fs.ts": "7d1c7261e9f15d25c6c09df43169a4665bd9da7e2413534aa294f4b184f3fa4e",
"https://deno.land/x/logger@v1.1.5/interface.ts": "7bca0b861b894e914508aab1afdd7e42e598695a50a3efe9db54be8ba4ab3b0e",
"https://deno.land/x/logger@v1.1.5/logger.ts": "d058a83ec4ceb8582449d1a0f1ba4adce9a85d5c05b2fb1cf9920f7f896a0608",
"https://deno.land/x/logger@v1.1.5/stdout.ts": "f11db1f6569681fe58139b07de1f76e205bf28f6e341a50d56d3b13d95c1f6bb",
"https://deno.land/x/logger@v1.1.5/types.ts": "8835d0d56f500112f92b36d8f241f95bccef93f73de203f7cd86de3ab4383d80",
"https://deno.land/x/logger@v1.1.5/writable.ts": "bb60ba4a798a10ac1649e30598c0c346055c0dcacb8f1e9452e4f66ea6680a45",
"https://deno.land/x/logger@v1.1.5/writer.ts": "539ff3a1bdefef897ca1d13d387ee4d84d6491f460020454e9158076f5e09221",
"https://deno.land/x/media_types@v2.7.1/db.ts": "1d95aa3fc1fe076638550640609394f0e157b18b430800e419aa7ece5c151d9c",
"https://deno.land/x/media_types@v2.7.1/deps.ts": "cd4c31e4b5ed8c4d8c61bd2fb38a82d68d3fd2dcf6d43f22511cbe6d9d310e51",
"https://deno.land/x/media_types@v2.7.1/mod.ts": "d63583b978d32eff8b76e1ae5d83cba2fb27baa90cc1bcb0ad15a06122ea8c19",
"https://deno.land/x/media_types@v2.7.1/mod.tsx": "d63583b978d32eff8b76e1ae5d83cba2fb27baa90cc1bcb0ad15a06122ea8c19",
"https://deno.land/x/oak@v12.6.1/application.ts": "3028d3f6fa5ee743de013881550d054372c11d83c45099c2d794033786d27008",
"https://deno.land/x/oak@v12.6.1/body.ts": "1899761b97fc9d776f3710b2637fb047ba29b968609afc6c0e5219b1108e703c",
"https://deno.land/x/oak@v12.6.1/buf_reader.ts": "26640736541598dbd9f2b84a9d0595756afff03c9ca55b66eef1911f7798b56d",
"https://deno.land/x/oak@v12.6.1/content_disposition.ts": "8b8c3cb2fba7138cd5b7f82fc3b5ea39b33db924a824b28261659db7e164621e",
"https://deno.land/x/oak@v12.6.1/context.ts": "895a2d40186b89c28ba3947bf08a9335f1a11fc33133f760082536b74c53d1ca",
"https://deno.land/x/oak@v12.6.1/deps.ts": "267ef76c25592101fe1f6c6d7730664015a9179c974da4f7441297d9367a9514",
"https://deno.land/x/oak@v12.6.1/etag.ts": "32e47726b41698aefdd71faac5aaf2907c9bdd41ef18a7693863be4f8fee115d",
"https://deno.land/x/oak@v12.6.1/forwarded.ts": "e656f96a85574e2a6ee54dc35efc9f72d543c9ae0923760ef426ee7369eef01c",
"https://deno.land/x/oak@v12.6.1/headers.ts": "769fd042d34fbcd5667cbd745b5c65d335cc8430e822dbf1f87d65313cab4b47",
"https://deno.land/x/oak@v12.6.1/helpers.ts": "6b03c6a2be06ec775d54449e442a2bac234aa952948ca758356eab6dc87af618",
"https://deno.land/x/oak@v12.6.1/http_server_native.ts": "98e12c50a959553cfc144bc00999c969fa69ca781cbd96bec563f55691ab82db",
"https://deno.land/x/oak@v12.6.1/http_server_native_request.ts": "552b174b5e13e92de8897d5b6f716b1e5a53543115481d65a651a41e4ca29ec9",
"https://deno.land/x/oak@v12.6.1/isMediaType.ts": "62d638abcf837ece3a8f07a4b7ca59794135cb0d4b73194c7d5837efd4161005",
"https://deno.land/x/oak@v12.6.1/mediaTyper.ts": "042b853fc8e9c3f6c628dd389e03ef481552bf07242efc3f8a1af042102a6105",
"https://deno.land/x/oak@v12.6.1/middleware.ts": "c7f7a0424a6dd99a00e4b8d7d6e131efc0facc8dea781845d713b63df8ef1862",
"https://deno.land/x/oak@v12.6.1/middleware/proxy.ts": "6f2799cf60d926e7a8d13ff757a59d7f0f930407db7ee9b81e7c064138eb89ff",
"https://deno.land/x/oak@v12.6.1/mod.ts": "f6aa47ad1b6099470c9a884cccad9d3ac0fd242ba940896291ab76cd26cf554b",
"https://deno.land/x/oak@v12.6.1/mod.tsx": "f6aa47ad1b6099470c9a884cccad9d3ac0fd242ba940896291ab76cd26cf554b",
"https://deno.land/x/oak@v12.6.1/multipart.ts": "1484e01b98f5135f2aa09f7d0ce1e7be39109bf9f045ac660e941619d04e3d29",
"https://deno.land/x/oak@v12.6.1/range.ts": "1ca15fc1ac21c650c34e6997a75af2af9d9d8eb6fe2d5d1dadeac3dfd4a9c152",
"https://deno.land/x/oak@v12.6.1/request.ts": "32409827e285ee65889b22bbaaea5d6b280258124c2e9a4f724baa8e6d6375b7",
"https://deno.land/x/oak@v12.6.1/response.ts": "094d950a5158f5b3446ca8a7b6e975dd23afb42b38c38517cc2f41dc75b16b4c",
"https://deno.land/x/oak@v12.6.1/router.ts": "0f53d6249f9e8f89f2522b2b810b9302d0f22593c184b16b24b03bf2b7d42ea1",
"https://deno.land/x/oak@v12.6.1/send.ts": "5ec49f106294593f468317a0c885da4f3274bf6d0fe9e16a7304391730b4f4fb",
"https://deno.land/x/oak@v12.6.1/structured_clone.ts": "c3888b14d1eec558345bfbf13d0993d59bd45aaa8588444e35dd558c3a921cd8",
"https://deno.land/x/oak@v12.6.1/testing.ts": "37d684d57bb8e5150fb5eb2677e66b04dcb422709cf2c5a74c1df94d52aa02e2",
"https://deno.land/x/oak@v12.6.1/util.ts": "0a3fdffb114859c2de84e1783efa3a544af4d2af8c6f08e0d25655de9d3e69bb",
"https://deno.land/x/path_to_regexp@v6.2.1/index.ts": "894060567837bae8fc9c5cbd4d0a05e9024672083d5883b525c031eea940e556",
"https://deno.land/x/static_files@1.1.6/mod.ts": "8a9bb05599e53864c54eb22931fe98507818517e0d69f26e099a1d8f4ef2b638",
"https://deno.land/x/static_files@1.1.6/mod.tsx": "8a9bb05599e53864c54eb22931fe98507818517e0d69f26e099a1d8f4ef2b638",
"https://deno.land/x/static_files@1.1.6/src/deps.ts": "fb62be7a780339157bf692a619d6d02ea9662490deca275f488f9f9db917fc4a",
"https://deno.land/x/static_files@1.1.6/src/types.ts": "ef201288626294e9e1b8ee85cdfe2cdfb282e4d78af445df1726050dfa0c0988",
"https://deno.land/x/static_files@1.1.6/src/utils.ts": "9e6172dc97fed01e70a6b063c5afff40e20fe726b3bae0c5f0a962bad74b7107",
"https://esm.sh/preact-render-to-string@5.1.19?deps=preact@10.5.15": "fba6961b9688151eeccc5425e05740009c3e7abee863615e626fb13e1d17e87a",
"https://esm.sh/preact@10.19.2": "41f31ba8eecf666f08289f2205f57c45f74baba5be815a55c15c4cc61086143c",
"https://esm.sh/preact@10.19.2/jsx-runtime": "2a4111d9aa667a3e3776ffd9082d00d63f6960c038d01620d79f80645ecc049d",
"https://esm.sh/stable/preact@10.19.2/denonext/jsx-runtime.js": "f196c14042fc6019f3fed31eec7cfedea4669d0926858939380a5f54bd503798",
"https://esm.sh/stable/preact@10.19.2/denonext/preact.mjs": "dc999b6432dc04d74ad7b692a8801f346294d815266dff915d0f222c120fd0b0",
"https://esm.sh/stable/preact@10.5.15/denonext/preact.mjs": "4e6645aa945a53e44eaa4d882f9f9b4e76c992875fad9ef5791784474a71a116",
"https://esm.sh/v135/preact-render-to-string@5.1.19/X-ZC9wcmVhY3RAMTAuNS4xNQ/denonext/preact-render-to-string.mjs": "3ce1bda513633d15cd313e97ab7eacba9bd50eb4dc95e41861056c6bae1bfac8"
}
}
+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 630 630">
<rect width="630" height="630" fill="#f7df1e"/>
<path d="m423.2 492.19c12.69 20.72 29.2 35.95 58.4 35.95 24.53 0 40.2-12.26 40.2-29.2 0-20.3-16.1-27.49-43.1-39.3l-14.8-6.35c-42.72-18.2-71.1-41-71.1-89.2 0-44.4 33.83-78.2 86.7-78.2 37.64 0 64.7 13.1 84.2 47.4l-46.1 29.6c-10.15-18.2-21.1-25.37-38.1-25.37-17.34 0-28.33 11-28.33 25.37 0 17.76 11 24.95 36.4 35.95l14.8 6.34c50.3 21.57 78.7 43.56 78.7 93 0 53.3-41.87 82.5-98.1 82.5-54.98 0-90.5-26.2-107.88-60.54zm-209.13 5.13c9.3 16.5 17.76 30.45 38.1 30.45 19.45 0 31.72-7.61 31.72-37.2v-201.3h59.2v202.1c0 61.3-35.94 89.2-88.4 89.2-47.4 0-74.85-24.53-88.81-54.075z"/>
</svg>

After

Width:  |  Height:  |  Size: 687 B

+33
View File
@@ -0,0 +1,33 @@
const sessionLocalStorageKey = 'dgt-session';
let cachedPathVariables = null;
function getPathVariables(){
if (cachedPathVariables !== null) {
return cachedPathVariables;
}
const raw = document.getElementById("url-placeholders")?.textContent || "{}"
cachedPathVariables = Object.entries(JSON.parse(raw)?.pathVariables || {})
return cachedPathVariables
}
window.addEventListener('login', function (evt) {
localStorage.setItem(sessionLocalStorageKey, evt.detail.value);
document.location.href = "/";
});
window.addEventListener('logout', function (evt) {
window.localStorage.removeItem(sessionLocalStorageKey);
document.location.href = "/login.html";
});
window.addEventListener('htmx:configRequest', function(evt) {
evt.detail.headers['dgt-session'] = localStorage.getItem(sessionLocalStorageKey);
function reducer(path, [key, value]){
return path.replace(key, value)
}
evt.detail.path = getPathVariables().reduce(reducer, evt.detail.path)
});
+7
View File
@@ -0,0 +1,7 @@
htmx.defineExtension('ajax-header', {
onEvent: function (name, evt) {
if (name === "htmx:configRequest") {
evt.detail.headers['X-Requested-With'] = 'XMLHttpRequest';
}
}
});
+16
View File
@@ -0,0 +1,16 @@
htmx.defineExtension('alpine-morph', {
isInlineSwap: function (swapStyle) {
return swapStyle === 'morph';
},
handleSwap: function (swapStyle, target, fragment) {
if (swapStyle === 'morph') {
if (fragment.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
Alpine.morph(target, fragment.firstElementChild);
return [target];
} else {
Alpine.morph(target, fragment.outerHTML);
return [target];
}
}
}
});
+92
View File
@@ -0,0 +1,92 @@
(function () {
function splitOnWhitespace(trigger) {
return trigger.split(/\s+/);
}
function parseClassOperation(trimmedValue) {
var split = splitOnWhitespace(trimmedValue);
if (split.length > 1) {
var operation = split[0];
var classDef = split[1].trim();
var cssClass;
var delay;
if (classDef.indexOf(":") > 0) {
var splitCssClass = classDef.split(':');
cssClass = splitCssClass[0];
delay = htmx.parseInterval(splitCssClass[1]);
} else {
cssClass = classDef;
delay = 100;
}
return {
operation: operation,
cssClass: cssClass,
delay: delay
}
} else {
return null;
}
}
function performOperation(elt, classOperation, classList, currentRunTime) {
setTimeout(function () {
elt.classList[classOperation.operation].call(elt.classList, classOperation.cssClass);
}, currentRunTime)
}
function toggleOperation(elt, classOperation, classList, currentRunTime) {
setTimeout(function () {
setInterval(function () {
elt.classList[classOperation.operation].call(elt.classList, classOperation.cssClass);
}, classOperation.delay);
}, currentRunTime)
}
function processClassList(elt, classList) {
var runs = classList.split("&");
for (var i = 0; i < runs.length; i++) {
var run = runs[i];
var currentRunTime = 0;
var classOperations = run.split(",");
for (var j = 0; j < classOperations.length; j++) {
var value = classOperations[j];
var trimmedValue = value.trim();
var classOperation = parseClassOperation(trimmedValue);
if (classOperation) {
if (classOperation.operation === "toggle") {
toggleOperation(elt, classOperation, classList, currentRunTime);
currentRunTime = currentRunTime + classOperation.delay;
} else {
currentRunTime = currentRunTime + classOperation.delay;
performOperation(elt, classOperation, classList, currentRunTime);
}
}
}
}
}
function maybeProcessClasses(elt) {
if (elt.getAttribute) {
var classList = elt.getAttribute("classes") || elt.getAttribute("data-classes");
if (classList) {
processClassList(elt, classList);
}
}
}
htmx.defineExtension('class-tools', {
onEvent: function (name, evt) {
if (name === "htmx:afterProcessNode") {
var elt = evt.detail.elt;
maybeProcessClasses(elt);
if (elt.querySelectorAll) {
var children = elt.querySelectorAll("[classes], [data-classes]");
for (var i = 0; i < children.length; i++) {
maybeProcessClasses(children[i]);
}
}
}
}
});
})();
@@ -0,0 +1,96 @@
htmx.defineExtension('client-side-templates', {
transformResponse : function(text, xhr, elt) {
var mustacheTemplate = htmx.closest(elt, "[mustache-template]");
if (mustacheTemplate) {
var data = JSON.parse(text);
var templateId = mustacheTemplate.getAttribute('mustache-template');
var template = htmx.find("#" + templateId);
if (template) {
return Mustache.render(template.innerHTML, data);
} else {
throw "Unknown mustache template: " + templateId;
}
}
var mustacheArrayTemplate = htmx.closest(elt, "[mustache-array-template]");
if (mustacheArrayTemplate) {
var data = JSON.parse(text);
var templateId = mustacheArrayTemplate.getAttribute('mustache-array-template');
var template = htmx.find("#" + templateId);
if (template) {
return Mustache.render(template.innerHTML, {"data": data });
} else {
throw "Unknown mustache template: " + templateId;
}
}
var handlebarsTemplate = htmx.closest(elt, "[handlebars-template]");
if (handlebarsTemplate) {
var data = JSON.parse(text);
var templateId = handlebarsTemplate.getAttribute('handlebars-template');
var templateElement = htmx.find('#' + templateId).innerHTML;
var renderTemplate = Handlebars.compile(templateElement);
if (renderTemplate) {
return renderTemplate(data);
} else {
throw "Unknown handlebars template: " + templateId;
}
}
var handlebarsArrayTemplate = htmx.closest(elt, "[handlebars-array-template]");
if (handlebarsArrayTemplate) {
var data = JSON.parse(text);
var templateId = handlebarsArrayTemplate.getAttribute('handlebars-array-template');
var templateElement = htmx.find('#' + templateId).innerHTML;
var renderTemplate = Handlebars.compile(templateElement);
if (renderTemplate) {
return renderTemplate(data);
} else {
throw "Unknown handlebars template: " + templateId;
}
}
var nunjucksTemplate = htmx.closest(elt, "[nunjucks-template]");
if (nunjucksTemplate) {
var data = JSON.parse(text);
var templateName = nunjucksTemplate.getAttribute('nunjucks-template');
var template = htmx.find('#' + templateName);
if (template) {
return nunjucks.renderString(template.innerHTML, data);
} else {
return nunjucks.render(templateName, data);
}
}
var xsltTemplate = htmx.closest(elt, "[xslt-template]");
if (xsltTemplate) {
var templateId = xsltTemplate.getAttribute('xslt-template');
var template = htmx.find("#" + templateId);
if (template) {
var content = template.innerHTML ? new DOMParser().parseFromString(template.innerHTML, 'application/xml')
: template.contentDocument;
var processor = new XSLTProcessor();
processor.importStylesheet(content);
var data = new DOMParser().parseFromString(text, "application/xml");
var frag = processor.transformToFragment(data, document);
return new XMLSerializer().serializeToString(frag);
} else {
throw "Unknown XSLT template: " + templateId;
}
}
var nunjucksArrayTemplate = htmx.closest(elt, "[nunjucks-array-template]");
if (nunjucksArrayTemplate) {
var data = JSON.parse(text);
var templateName = nunjucksArrayTemplate.getAttribute('nunjucks-array-template');
var template = htmx.find('#' + templateName);
if (template) {
return nunjucks.renderString(template.innerHTML, {"data": data});
} else {
return nunjucks.render(templateName, {"data": data});
}
}
return text;
}
});
+11
View File
@@ -0,0 +1,11 @@
htmx.defineExtension('debug', {
onEvent: function (name, evt) {
if (console.debug) {
console.debug(name, evt);
} else if (console) {
console.log("DEBUG:", name, evt);
} else {
throw "NO CONSOLE SUPPORTED"
}
}
});
+18
View File
@@ -0,0 +1,18 @@
"use strict";
// Disable Submit Button
htmx.defineExtension('disable-element', {
onEvent: function (name, evt) {
let elt = evt.detail.elt;
let target = elt.getAttribute("hx-disable-element");
let targetElements = (target == "self") ? [ elt ] : document.querySelectorAll(target);
for (var i = 0; i < targetElements.length; i++) {
if (name === "htmx:beforeRequest" && targetElements[i]) {
targetElements[i].disabled = true;
} else if (name == "htmx:afterRequest" && targetElements[i]) {
targetElements[i].disabled = false;
}
}
}
});
+37
View File
@@ -0,0 +1,37 @@
(function(){
function stringifyEvent(event) {
var obj = {};
for (var key in event) {
obj[key] = event[key];
}
return JSON.stringify(obj, function(key, value){
if(value instanceof Node){
var nodeRep = value.tagName;
if (nodeRep) {
nodeRep = nodeRep.toLowerCase();
if(value.id){
nodeRep += "#" + value.id;
}
if(value.classList && value.classList.length){
nodeRep += "." + value.classList.toString().replace(" ", ".")
}
return nodeRep;
} else {
return "Node"
}
}
if (value instanceof Window) return 'Window';
return value;
});
}
htmx.defineExtension('event-header', {
onEvent: function (name, evt) {
if (name === "htmx:configRequest") {
if (evt.detail.triggeringEvent) {
evt.detail.headers['Triggering-Event'] = stringifyEvent(evt.detail.triggeringEvent);
}
}
}
});
})();
+141
View File
@@ -0,0 +1,141 @@
//==========================================================
// head-support.js
//
// An extension to htmx 1.0 to add head tag merging.
//==========================================================
(function(){
var api = null;
function log() {
//console.log(arguments);
}
function mergeHead(newContent, defaultMergeStrategy) {
if (newContent && newContent.indexOf('<head') > -1) {
const htmlDoc = document.createElement("html");
// remove svgs to avoid conflicts
var contentWithSvgsRemoved = newContent.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim, '');
// extract head tag
var headTag = contentWithSvgsRemoved.match(/(<head(\s[^>]*>|>)([\s\S]*?)<\/head>)/im);
// if the head tag exists...
if (headTag) {
var added = []
var removed = []
var preserved = []
var nodesToAppend = []
htmlDoc.innerHTML = headTag;
var newHeadTag = htmlDoc.querySelector("head");
var currentHead = document.head;
if (newHeadTag == null) {
return;
} else {
// put all new head elements into a Map, by their outerHTML
var srcToNewHeadNodes = new Map();
for (const newHeadChild of newHeadTag.children) {
srcToNewHeadNodes.set(newHeadChild.outerHTML, newHeadChild);
}
}
// determine merge strategy
var mergeStrategy = api.getAttributeValue(newHeadTag, "hx-head") || defaultMergeStrategy;
// get the current head
for (const currentHeadElt of currentHead.children) {
// If the current head element is in the map
var inNewContent = srcToNewHeadNodes.has(currentHeadElt.outerHTML);
var isReAppended = currentHeadElt.getAttribute("hx-head") === "re-eval";
var isPreserved = api.getAttributeValue(currentHeadElt, "hx-preserve") === "true";
if (inNewContent || isPreserved) {
if (isReAppended) {
// remove the current version and let the new version replace it and re-execute
removed.push(currentHeadElt);
} else {
// this element already exists and should not be re-appended, so remove it from
// the new content map, preserving it in the DOM
srcToNewHeadNodes.delete(currentHeadElt.outerHTML);
preserved.push(currentHeadElt);
}
} else {
if (mergeStrategy === "append") {
// we are appending and this existing element is not new content
// so if and only if it is marked for re-append do we do anything
if (isReAppended) {
removed.push(currentHeadElt);
nodesToAppend.push(currentHeadElt);
}
} else {
// if this is a merge, we remove this content since it is not in the new head
if (api.triggerEvent(document.body, "htmx:removingHeadElement", {headElement: currentHeadElt}) !== false) {
removed.push(currentHeadElt);
}
}
}
}
// Push the tremaining new head elements in the Map into the
// nodes to append to the head tag
nodesToAppend.push(...srcToNewHeadNodes.values());
log("to append: ", nodesToAppend);
for (const newNode of nodesToAppend) {
log("adding: ", newNode);
var newElt = document.createRange().createContextualFragment(newNode.outerHTML);
log(newElt);
if (api.triggerEvent(document.body, "htmx:addingHeadElement", {headElement: newElt}) !== false) {
currentHead.appendChild(newElt);
added.push(newElt);
}
}
// remove all removed elements, after we have appended the new elements to avoid
// additional network requests for things like style sheets
for (const removedElement of removed) {
if (api.triggerEvent(document.body, "htmx:removingHeadElement", {headElement: removedElement}) !== false) {
currentHead.removeChild(removedElement);
}
}
api.triggerEvent(document.body, "htmx:afterHeadMerge", {added: added, kept: preserved, removed: removed});
}
}
}
htmx.defineExtension("head-support", {
init: function(apiRef) {
// store a reference to the internal API.
api = apiRef;
htmx.on('htmx:afterSwap', function(evt){
var serverResponse = evt.detail.xhr.response;
if (api.triggerEvent(document.body, "htmx:beforeHeadMerge", evt.detail)) {
mergeHead(serverResponse, evt.detail.boosted ? "merge" : "append");
}
})
htmx.on('htmx:historyRestore', function(evt){
if (api.triggerEvent(document.body, "htmx:beforeHeadMerge", evt.detail)) {
if (evt.detail.cacheMiss) {
mergeHead(evt.detail.serverResponse, "merge");
} else {
mergeHead(evt.detail.item.head, "merge");
}
}
})
htmx.on('htmx:historyItemCreated', function(evt){
var historyItem = evt.detail.item;
historyItem.head = document.head.outerHTML;
})
}
});
})()
+24
View File
@@ -0,0 +1,24 @@
(function(){
function mergeObjects(obj1, obj2) {
for (var key in obj2) {
if (obj2.hasOwnProperty(key)) {
obj1[key] = obj2[key];
}
}
return obj1;
}
htmx.defineExtension('include-vals', {
onEvent: function (name, evt) {
if (name === "htmx:configRequest") {
var includeValsElt = htmx.closest(evt.detail.elt, "[include-vals],[data-include-vals]");
if (includeValsElt) {
var includeVals = includeValsElt.getAttribute("include-vals") || includeValsElt.getAttribute("data-include-vals");
var valuesToInclude = eval("({" + includeVals + "})");
mergeObjects(evt.detail.parameters, valuesToInclude);
}
}
}
});
})();
+12
View File
@@ -0,0 +1,12 @@
htmx.defineExtension('json-enc', {
onEvent: function (name, evt) {
if (name === "htmx:configRequest") {
evt.detail.headers['Content-Type'] = "application/json";
}
},
encodeParameters : function(xhr, parameters, elt) {
xhr.overrideMimeType('text/json');
return (JSON.stringify(parameters));
}
});
+183
View File
@@ -0,0 +1,183 @@
;(function () {
let loadingStatesUndoQueue = []
function loadingStateContainer(target) {
return htmx.closest(target, '[data-loading-states]') || document.body
}
function mayProcessUndoCallback(target, callback) {
if (document.body.contains(target)) {
callback()
}
}
function mayProcessLoadingStateByPath(elt, requestPath) {
const pathElt = htmx.closest(elt, '[data-loading-path]')
if (!pathElt) {
return true
}
return pathElt.getAttribute('data-loading-path') === requestPath
}
function queueLoadingState(sourceElt, targetElt, doCallback, undoCallback) {
const delayElt = htmx.closest(sourceElt, '[data-loading-delay]')
if (delayElt) {
const delayInMilliseconds =
delayElt.getAttribute('data-loading-delay') || 200
const timeout = setTimeout(function () {
doCallback()
loadingStatesUndoQueue.push(function () {
mayProcessUndoCallback(targetElt, undoCallback)
})
}, delayInMilliseconds)
loadingStatesUndoQueue.push(function () {
mayProcessUndoCallback(targetElt, function () { clearTimeout(timeout) })
})
} else {
doCallback()
loadingStatesUndoQueue.push(function () {
mayProcessUndoCallback(targetElt, undoCallback)
})
}
}
function getLoadingStateElts(loadingScope, type, path) {
return Array.from(htmx.findAll(loadingScope, "[" + type + "]")).filter(
function (elt) { return mayProcessLoadingStateByPath(elt, path) }
)
}
function getLoadingTarget(elt) {
if (elt.getAttribute('data-loading-target')) {
return Array.from(
htmx.findAll(elt.getAttribute('data-loading-target'))
)
}
return [elt]
}
htmx.defineExtension('loading-states', {
onEvent: function (name, evt) {
if (name === 'htmx:beforeRequest') {
const container = loadingStateContainer(evt.target)
const loadingStateTypes = [
'data-loading',
'data-loading-class',
'data-loading-class-remove',
'data-loading-disable',
'data-loading-aria-busy',
]
let loadingStateEltsByType = {}
loadingStateTypes.forEach(function (type) {
loadingStateEltsByType[type] = getLoadingStateElts(
container,
type,
evt.detail.pathInfo.requestPath
)
})
loadingStateEltsByType['data-loading'].forEach(function (sourceElt) {
getLoadingTarget(sourceElt).forEach(function (targetElt) {
queueLoadingState(
sourceElt,
targetElt,
function () {
targetElt.style.display =
sourceElt.getAttribute('data-loading') ||
'inline-block' },
function () { targetElt.style.display = 'none' }
)
})
})
loadingStateEltsByType['data-loading-class'].forEach(
function (sourceElt) {
const classNames = sourceElt
.getAttribute('data-loading-class')
.split(' ')
getLoadingTarget(sourceElt).forEach(function (targetElt) {
queueLoadingState(
sourceElt,
targetElt,
function () {
classNames.forEach(function (className) {
targetElt.classList.add(className)
})
},
function() {
classNames.forEach(function (className) {
targetElt.classList.remove(className)
})
}
)
})
}
)
loadingStateEltsByType['data-loading-class-remove'].forEach(
function (sourceElt) {
const classNames = sourceElt
.getAttribute('data-loading-class-remove')
.split(' ')
getLoadingTarget(sourceElt).forEach(function (targetElt) {
queueLoadingState(
sourceElt,
targetElt,
function () {
classNames.forEach(function (className) {
targetElt.classList.remove(className)
})
},
function() {
classNames.forEach(function (className) {
targetElt.classList.add(className)
})
}
)
})
}
)
loadingStateEltsByType['data-loading-disable'].forEach(
function (sourceElt) {
getLoadingTarget(sourceElt).forEach(function (targetElt) {
queueLoadingState(
sourceElt,
targetElt,
function() { targetElt.disabled = true },
function() { targetElt.disabled = false }
)
})
}
)
loadingStateEltsByType['data-loading-aria-busy'].forEach(
function (sourceElt) {
getLoadingTarget(sourceElt).forEach(function (targetElt) {
queueLoadingState(
sourceElt,
targetElt,
function () { targetElt.setAttribute("aria-busy", "true") },
function () { targetElt.removeAttribute("aria-busy") }
)
})
}
)
}
if (name === 'htmx:beforeOnLoad') {
while (loadingStatesUndoQueue.length > 0) {
loadingStatesUndoQueue.shift()()
}
}
},
})
})()
+11
View File
@@ -0,0 +1,11 @@
htmx.defineExtension('method-override', {
onEvent: function (name, evt) {
if (name === "htmx:configRequest") {
var method = evt.detail.verb;
if (method !== "get" || method !== "post") {
evt.detail.headers['X-HTTP-Method-Override'] = method.toUpperCase();
evt.detail.verb = "post";
}
}
}
});
+17
View File
@@ -0,0 +1,17 @@
htmx.defineExtension('morphdom-swap', {
isInlineSwap: function(swapStyle) {
return swapStyle === 'morphdom';
},
handleSwap: function (swapStyle, target, fragment) {
if (swapStyle === 'morphdom') {
if (fragment.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
// IE11 doesn't support DocumentFragment.firstElementChild
morphdom(target, fragment.firstElementChild || fragment.firstChild);
return [target];
} else {
morphdom(target, fragment.outerHTML);
return [target];
}
}
}
});
+45
View File
@@ -0,0 +1,45 @@
(function () {
/** @type {import("../htmx").HtmxInternalApi} */
var api;
htmx.defineExtension('multi-swap', {
init: function (apiRef) {
api = apiRef;
},
isInlineSwap: function (swapStyle) {
return swapStyle.indexOf('multi:') === 0;
},
handleSwap: function (swapStyle, target, fragment, settleInfo) {
if (swapStyle.indexOf('multi:') === 0) {
var selectorToSwapStyle = {};
var elements = swapStyle.replace(/^multi\s*:\s*/, '').split(/\s*,\s*/);
elements.map(function (element) {
var split = element.split(/\s*:\s*/);
var elementSelector = split[0];
var elementSwapStyle = typeof (split[1]) !== "undefined" ? split[1] : "innerHTML";
if (elementSelector.charAt(0) !== '#') {
console.error("HTMX multi-swap: unsupported selector '" + elementSelector + "'. Only ID selectors starting with '#' are supported.");
return;
}
selectorToSwapStyle[elementSelector] = elementSwapStyle;
});
for (var selector in selectorToSwapStyle) {
var swapStyle = selectorToSwapStyle[selector];
var elementToSwap = fragment.querySelector(selector);
if (elementToSwap) {
api.oobSwap(swapStyle, elementToSwap, settleInfo);
} else {
console.warn("HTMX multi-swap: selector '" + selector + "' not found in source content.");
}
}
return true;
}
}
});
})();
+60
View File
@@ -0,0 +1,60 @@
(function(undefined){
'use strict';
// Save a reference to the global object (window in the browser)
var _root = this;
function dependsOn(pathSpec, url) {
if (pathSpec === "ignore") {
return false;
}
var dependencyPath = pathSpec.split("/");
var urlPath = url.split("/");
for (var i = 0; i < urlPath.length; i++) {
var dependencyElement = dependencyPath.shift();
var pathElement = urlPath[i];
if (dependencyElement !== pathElement && dependencyElement !== "*") {
return false;
}
if (dependencyPath.length === 0 || (dependencyPath.length === 1 && dependencyPath[0] === "")) {
return true;
}
}
return false;
}
function refreshPath(path) {
var eltsWithDeps = htmx.findAll("[path-deps]");
for (var i = 0; i < eltsWithDeps.length; i++) {
var elt = eltsWithDeps[i];
if (dependsOn(elt.getAttribute('path-deps'), path)) {
htmx.trigger(elt, "path-deps");
}
}
}
htmx.defineExtension('path-deps', {
onEvent: function (name, evt) {
if (name === "htmx:beforeOnLoad") {
var config = evt.detail.requestConfig;
// mutating call
if (config.verb !== "get" && evt.target.getAttribute('path-deps') !== 'ignore') {
refreshPath(config.path);
}
}
}
});
/**
* ********************
* Expose functionality
* ********************
*/
_root.PathDeps = {
refresh: function(path) {
refreshPath(path);
}
};
}).call(this);
+11
View File
@@ -0,0 +1,11 @@
htmx.defineExtension('path-params', {
onEvent: function(name, evt) {
if (name === "htmx:configRequest") {
evt.detail.path = evt.detail.path.replace(/{([^}]+)}/g, function (_, param) {
var val = evt.detail.parameters[param];
delete evt.detail.parameters[param];
return val === undefined ? "{" + param + "}" : encodeURIComponent(val);
})
}
}
});
+147
View File
@@ -0,0 +1,147 @@
// This adds the "preload" extension to htmx. By default, this will
// preload the targets of any tags with `href` or `hx-get` attributes
// if they also have a `preload` attribute as well. See documentation
// for more details
htmx.defineExtension("preload", {
onEvent: function(name, event) {
// Only take actions on "htmx:afterProcessNode"
if (name !== "htmx:afterProcessNode") {
return;
}
// SOME HELPER FUNCTIONS WE'LL NEED ALONG THE WAY
// attr gets the closest non-empty value from the attribute.
var attr = function(node, property) {
if (node == undefined) {return undefined;}
return node.getAttribute(property) || node.getAttribute("data-" + property) || attr(node.parentElement, property)
}
// load handles the actual HTTP fetch, and uses htmx.ajax in cases where we're
// preloading an htmx resource (this sends the same HTTP headers as a regular htmx request)
var load = function(node) {
// Called after a successful AJAX request, to mark the
// content as loaded (and prevent additional AJAX calls.)
var done = function(html) {
if (!node.preloadAlways) {
node.preloadState = "DONE"
}
if (attr(node, "preload-images") == "true") {
document.createElement("div").innerHTML = html // create and populate a node to load linked resources, too.
}
}
return function() {
// If this value has already been loaded, then do not try again.
if (node.preloadState !== "READY") {
return;
}
// Special handling for HX-GET - use built-in htmx.ajax function
// so that headers match other htmx requests, then set
// node.preloadState = TRUE so that requests are not duplicated
// in the future
var hxGet = node.getAttribute("hx-get") || node.getAttribute("data-hx-get")
if (hxGet) {
htmx.ajax("GET", hxGet, {
source: node,
handler:function(elt, info) {
done(info.xhr.responseText);
}
});
return;
}
// Otherwise, perform a standard xhr request, then set
// node.preloadState = TRUE so that requests are not duplicated
// in the future.
if (node.getAttribute("href")) {
var r = new XMLHttpRequest();
r.open("GET", node.getAttribute("href"));
r.onload = function() {done(r.responseText);};
r.send();
return;
}
}
}
// This function processes a specific node and sets up event handlers.
// We'll search for nodes and use it below.
var init = function(node) {
// If this node DOES NOT include a "GET" transaction, then there's nothing to do here.
if (node.getAttribute("href") + node.getAttribute("hx-get") + node.getAttribute("data-hx-get") == "") {
return;
}
// Guarantee that we only initialize each node once.
if (node.preloadState !== undefined) {
return;
}
// Get event name from config.
var on = attr(node, "preload") || "mousedown"
const always = on.indexOf("always") !== -1
if (always) {
on = on.replace('always', '').trim()
}
// FALL THROUGH to here means we need to add an EventListener
// Apply the listener to the node
node.addEventListener(on, function(evt) {
if (node.preloadState === "PAUSE") { // Only add one event listener
node.preloadState = "READY"; // Required for the `load` function to trigger
// Special handling for "mouseover" events. Wait 100ms before triggering load.
if (on === "mouseover") {
window.setTimeout(load(node), 100);
} else {
load(node)() // all other events trigger immediately.
}
}
})
// Special handling for certain built-in event handlers
switch (on) {
case "mouseover":
// Mirror `touchstart` events (fires immediately)
node.addEventListener("touchstart", load(node));
// WHhen the mouse leaves, immediately disable the preload
node.addEventListener("mouseout", function(evt) {
if ((evt.target === node) && (node.preloadState === "READY")) {
node.preloadState = "PAUSE";
}
})
break;
case "mousedown":
// Mirror `touchstart` events (fires immediately)
node.addEventListener("touchstart", load(node));
break;
}
// Mark the node as ready to run.
node.preloadState = "PAUSE";
node.preloadAlways = always;
htmx.trigger(node, "preload:init") // This event can be used to load content immediately.
}
// Search for all child nodes that have a "preload" attribute
event.target.querySelectorAll("[preload]").forEach(function(node) {
// Initialize the node with the "preload" attribute
init(node)
// Initialize all child elements that are anchors or have `hx-get` (use with care)
node.querySelectorAll("a,[hx-get],[data-hx-get]").forEach(init)
})
}
})
+10
View File
@@ -0,0 +1,10 @@
htmx.defineExtension('rails-method', {
onEvent: function (name, evt) {
if (name === "configRequest.htmx") {
var methodOverride = evt.detail.headers['X-HTTP-Method-Override'];
if (methodOverride) {
evt.detail.parameters['_method'] = methodOverride;
}
}
}
});
+27
View File
@@ -0,0 +1,27 @@
(function(){
function maybeRemoveMe(elt) {
var timing = elt.getAttribute("remove-me") || elt.getAttribute("data-remove-me");
if (timing) {
setTimeout(function () {
elt.parentElement.removeChild(elt);
}, htmx.parseInterval(timing));
}
}
htmx.defineExtension('remove-me', {
onEvent: function (name, evt) {
if (name === "htmx:afterProcessNode") {
var elt = evt.detail.elt;
if (elt.getAttribute) {
maybeRemoveMe(elt);
if (elt.querySelectorAll) {
var children = elt.querySelectorAll("[remove-me], [data-remove-me]");
for (var i = 0; i < children.length; i++) {
maybeRemoveMe(children[i]);
}
}
}
}
}
});
})();
+130
View File
@@ -0,0 +1,130 @@
(function(){
/** @type {import("../htmx").HtmxInternalApi} */
var api;
var attrPrefix = 'hx-target-';
// IE11 doesn't support string.startsWith
function startsWith(str, prefix) {
return str.substring(0, prefix.length) === prefix
}
/**
* @param {HTMLElement} elt
* @param {number} respCode
* @returns {HTMLElement | null}
*/
function getRespCodeTarget(elt, respCodeNumber) {
if (!elt || !respCodeNumber) return null;
var respCode = respCodeNumber.toString();
// '*' is the original syntax, as the obvious character for a wildcard.
// The 'x' alternative was added for maximum compatibility with HTML
// templating engines, due to ambiguity around which characters are
// supported in HTML attributes.
//
// Start with the most specific possible attribute and generalize from
// there.
var attrPossibilities = [
respCode,
respCode.substr(0, 2) + '*',
respCode.substr(0, 2) + 'x',
respCode.substr(0, 1) + '*',
respCode.substr(0, 1) + 'x',
respCode.substr(0, 1) + '**',
respCode.substr(0, 1) + 'xx',
'*',
'x',
'***',
'xxx',
];
if (startsWith(respCode, '4') || startsWith(respCode, '5')) {
attrPossibilities.push('error');
}
for (var i = 0; i < attrPossibilities.length; i++) {
var attr = attrPrefix + attrPossibilities[i];
var attrValue = api.getClosestAttributeValue(elt, attr);
if (attrValue) {
if (attrValue === "this") {
return api.findThisElement(elt, attr);
} else {
return api.querySelectorExt(elt, attrValue);
}
}
}
return null;
}
/** @param {Event} evt */
function handleErrorFlag(evt) {
if (evt.detail.isError) {
if (htmx.config.responseTargetUnsetsError) {
evt.detail.isError = false;
}
} else if (htmx.config.responseTargetSetsError) {
evt.detail.isError = true;
}
}
htmx.defineExtension('response-targets', {
/** @param {import("../htmx").HtmxInternalApi} apiRef */
init: function (apiRef) {
api = apiRef;
if (htmx.config.responseTargetUnsetsError === undefined) {
htmx.config.responseTargetUnsetsError = true;
}
if (htmx.config.responseTargetSetsError === undefined) {
htmx.config.responseTargetSetsError = false;
}
if (htmx.config.responseTargetPrefersExisting === undefined) {
htmx.config.responseTargetPrefersExisting = false;
}
if (htmx.config.responseTargetPrefersRetargetHeader === undefined) {
htmx.config.responseTargetPrefersRetargetHeader = true;
}
},
/**
* @param {string} name
* @param {Event} evt
*/
onEvent: function (name, evt) {
if (name === "htmx:beforeSwap" &&
evt.detail.xhr &&
evt.detail.xhr.status !== 200) {
if (evt.detail.target) {
if (htmx.config.responseTargetPrefersExisting) {
evt.detail.shouldSwap = true;
handleErrorFlag(evt);
return true;
}
if (htmx.config.responseTargetPrefersRetargetHeader &&
evt.detail.xhr.getAllResponseHeaders().match(/HX-Retarget:/i)) {
evt.detail.shouldSwap = true;
handleErrorFlag(evt);
return true;
}
}
if (!evt.detail.requestConfig) {
return true;
}
var target = getRespCodeTarget(evt.detail.requestConfig.elt, evt.detail.xhr.status);
if (target) {
handleErrorFlag(evt);
evt.detail.shouldSwap = true;
evt.detail.target = target;
}
return true;
}
}
});
})();
+15
View File
@@ -0,0 +1,15 @@
htmx.defineExtension('restored', {
onEvent : function(name, evt) {
if (name === 'htmx:restored'){
var restoredElts = evt.detail.document.querySelectorAll(
"[hx-trigger='restored'],[data-hx-trigger='restored']"
);
// need a better way to do this, would prefer to just trigger from evt.detail.elt
var foundElt = Array.from(restoredElts).find(
(x) => (x.outerHTML === evt.detail.elt.outerHTML)
);
var restoredEvent = evt.detail.triggerEvent(foundElt, 'restored');
}
return;
}
})
+355
View File
@@ -0,0 +1,355 @@
/*
Server Sent Events Extension
============================
This extension adds support for Server Sent Events to htmx. See /www/extensions/sse.md for usage instructions.
*/
(function() {
/** @type {import("../htmx").HtmxInternalApi} */
var api;
htmx.defineExtension("sse", {
/**
* Init saves the provided reference to the internal HTMX API.
*
* @param {import("../htmx").HtmxInternalApi} api
* @returns void
*/
init: function(apiRef) {
// store a reference to the internal API.
api = apiRef;
// set a function in the public API for creating new EventSource objects
if (htmx.createEventSource == undefined) {
htmx.createEventSource = createEventSource;
}
},
/**
* onEvent handles all events passed to this extension.
*
* @param {string} name
* @param {Event} evt
* @returns void
*/
onEvent: function(name, evt) {
switch (name) {
case "htmx:beforeCleanupElement":
var internalData = api.getInternalData(evt.target)
// Try to remove remove an EventSource when elements are removed
if (internalData.sseEventSource) {
internalData.sseEventSource.close();
}
return;
// Try to create EventSources when elements are processed
case "htmx:afterProcessNode":
ensureEventSourceOnElement(evt.target);
registerSSE(evt.target);
}
}
});
///////////////////////////////////////////////
// HELPER FUNCTIONS
///////////////////////////////////////////////
/**
* createEventSource is the default method for creating new EventSource objects.
* it is hoisted into htmx.config.createEventSource to be overridden by the user, if needed.
*
* @param {string} url
* @returns EventSource
*/
function createEventSource(url) {
return new EventSource(url, { withCredentials: true });
}
function splitOnWhitespace(trigger) {
return trigger.trim().split(/\s+/);
}
function getLegacySSEURL(elt) {
var legacySSEValue = api.getAttributeValue(elt, "hx-sse");
if (legacySSEValue) {
var values = splitOnWhitespace(legacySSEValue);
for (var i = 0; i < values.length; i++) {
var value = values[i].split(/:(.+)/);
if (value[0] === "connect") {
return value[1];
}
}
}
}
function getLegacySSESwaps(elt) {
var legacySSEValue = api.getAttributeValue(elt, "hx-sse");
var returnArr = [];
if (legacySSEValue != null) {
var values = splitOnWhitespace(legacySSEValue);
for (var i = 0; i < values.length; i++) {
var value = values[i].split(/:(.+)/);
if (value[0] === "swap") {
returnArr.push(value[1]);
}
}
}
return returnArr;
}
/**
* registerSSE looks for attributes that can contain sse events, right
* now hx-trigger and sse-swap and adds listeners based on these attributes too
* the closest event source
*
* @param {HTMLElement} elt
*/
function registerSSE(elt) {
// Find closest existing event source
var sourceElement = api.getClosestMatch(elt, hasEventSource);
if (sourceElement == null) {
// api.triggerErrorEvent(elt, "htmx:noSSESourceError")
return null; // no eventsource in parentage, orphaned element
}
// Set internalData and source
var internalData = api.getInternalData(sourceElement);
var source = internalData.sseEventSource;
// Add message handlers for every `sse-swap` attribute
queryAttributeOnThisOrChildren(elt, "sse-swap").forEach(function(child) {
var sseSwapAttr = api.getAttributeValue(child, "sse-swap");
if (sseSwapAttr) {
var sseEventNames = sseSwapAttr.split(",");
} else {
var sseEventNames = getLegacySSESwaps(child);
}
for (var i = 0; i < sseEventNames.length; i++) {
var sseEventName = sseEventNames[i].trim();
var listener = function(event) {
// If the source is missing then close SSE
if (maybeCloseSSESource(sourceElement)) {
return;
}
// If the body no longer contains the element, remove the listener
if (!api.bodyContains(child)) {
source.removeEventListener(sseEventName, listener);
}
// swap the response into the DOM and trigger a notification
swap(child, event.data);
api.triggerEvent(elt, "htmx:sseMessage", event);
};
// Register the new listener
api.getInternalData(child).sseEventListener = listener;
source.addEventListener(sseEventName, listener);
}
});
// Add message handlers for every `hx-trigger="sse:*"` attribute
queryAttributeOnThisOrChildren(elt, "hx-trigger").forEach(function(child) {
var sseEventName = api.getAttributeValue(child, "hx-trigger");
if (sseEventName == null) {
return;
}
// Only process hx-triggers for events with the "sse:" prefix
if (sseEventName.slice(0, 4) != "sse:") {
return;
}
// remove the sse: prefix from here on out
sseEventName = sseEventName.substr(4);
var listener = function() {
if (maybeCloseSSESource(sourceElement)) {
return
}
if (!api.bodyContains(child)) {
source.removeEventListener(sseEventName, listener);
}
}
});
}
/**
* ensureEventSourceOnElement creates a new EventSource connection on the provided element.
* If a usable EventSource already exists, then it is returned. If not, then a new EventSource
* is created and stored in the element's internalData.
* @param {HTMLElement} elt
* @param {number} retryCount
* @returns {EventSource | null}
*/
function ensureEventSourceOnElement(elt, retryCount) {
if (elt == null) {
return null;
}
// handle extension source creation attribute
queryAttributeOnThisOrChildren(elt, "sse-connect").forEach(function(child) {
var sseURL = api.getAttributeValue(child, "sse-connect");
if (sseURL == null) {
return;
}
ensureEventSource(child, sseURL, retryCount);
});
// handle legacy sse, remove for HTMX2
queryAttributeOnThisOrChildren(elt, "hx-sse").forEach(function(child) {
var sseURL = getLegacySSEURL(child);
if (sseURL == null) {
return;
}
ensureEventSource(child, sseURL, retryCount);
});
}
function ensureEventSource(elt, url, retryCount) {
var source = htmx.createEventSource(url);
source.onerror = function(err) {
// Log an error event
api.triggerErrorEvent(elt, "htmx:sseError", { error: err, source: source });
// If parent no longer exists in the document, then clean up this EventSource
if (maybeCloseSSESource(elt)) {
return;
}
// Otherwise, try to reconnect the EventSource
if (source.readyState === EventSource.CLOSED) {
retryCount = retryCount || 0;
var timeout = Math.random() * (2 ^ retryCount) * 500;
window.setTimeout(function() {
ensureEventSourceOnElement(elt, Math.min(7, retryCount + 1));
}, timeout);
}
};
source.onopen = function(evt) {
api.triggerEvent(elt, "htmx:sseOpen", { source: source });
}
api.getInternalData(elt).sseEventSource = source;
}
/**
* maybeCloseSSESource confirms that the parent element still exists.
* If not, then any associated SSE source is closed and the function returns true.
*
* @param {HTMLElement} elt
* @returns boolean
*/
function maybeCloseSSESource(elt) {
if (!api.bodyContains(elt)) {
var source = api.getInternalData(elt).sseEventSource;
if (source != undefined) {
source.close();
// source = null
return true;
}
}
return false;
}
/**
* queryAttributeOnThisOrChildren returns all nodes that contain the requested attributeName, INCLUDING THE PROVIDED ROOT ELEMENT.
*
* @param {HTMLElement} elt
* @param {string} attributeName
*/
function queryAttributeOnThisOrChildren(elt, attributeName) {
var result = [];
// If the parent element also contains the requested attribute, then add it to the results too.
if (api.hasAttribute(elt, attributeName)) {
result.push(elt);
}
// Search all child nodes that match the requested attribute
elt.querySelectorAll("[" + attributeName + "], [data-" + attributeName + "]").forEach(function(node) {
result.push(node);
});
return result;
}
/**
* @param {HTMLElement} elt
* @param {string} content
*/
function swap(elt, content) {
api.withExtensions(elt, function(extension) {
content = extension.transformResponse(content, null, elt);
});
var swapSpec = api.getSwapSpecification(elt);
var target = api.getTarget(elt);
var settleInfo = api.makeSettleInfo(elt);
api.selectAndSwap(swapSpec.swapStyle, target, elt, content, settleInfo);
settleInfo.elts.forEach(function(elt) {
if (elt.classList) {
elt.classList.add(htmx.config.settlingClass);
}
api.triggerEvent(elt, 'htmx:beforeSettle');
});
// Handle settle tasks (with delay if requested)
if (swapSpec.settleDelay > 0) {
setTimeout(doSettle(settleInfo), swapSpec.settleDelay);
} else {
doSettle(settleInfo)();
}
}
/**
* doSettle mirrors much of the functionality in htmx that
* settles elements after their content has been swapped.
* TODO: this should be published by htmx, and not duplicated here
* @param {import("../htmx").HtmxSettleInfo} settleInfo
* @returns () => void
*/
function doSettle(settleInfo) {
return function() {
settleInfo.tasks.forEach(function(task) {
task.call();
});
settleInfo.elts.forEach(function(elt) {
if (elt.classList) {
elt.classList.remove(htmx.config.settlingClass);
}
api.triggerEvent(elt, 'htmx:afterSettle');
});
}
}
function hasEventSource(node) {
return api.getInternalData(node).sseEventSource != null;
}
})();
+477
View File
@@ -0,0 +1,477 @@
/*
WebSockets Extension
============================
This extension adds support for WebSockets to htmx. See /www/extensions/ws.md for usage instructions.
*/
(function () {
/** @type {import("../htmx").HtmxInternalApi} */
var api;
htmx.defineExtension("ws", {
/**
* init is called once, when this extension is first registered.
* @param {import("../htmx").HtmxInternalApi} apiRef
*/
init: function (apiRef) {
// Store reference to internal API
api = apiRef;
// Default function for creating new EventSource objects
if (!htmx.createWebSocket) {
htmx.createWebSocket = createWebSocket;
}
// Default setting for reconnect delay
if (!htmx.config.wsReconnectDelay) {
htmx.config.wsReconnectDelay = "full-jitter";
}
},
/**
* onEvent handles all events passed to this extension.
*
* @param {string} name
* @param {Event} evt
*/
onEvent: function (name, evt) {
switch (name) {
// Try to close the socket when elements are removed
case "htmx:beforeCleanupElement":
var internalData = api.getInternalData(evt.target)
if (internalData.webSocket) {
internalData.webSocket.close();
}
return;
// Try to create websockets when elements are processed
case "htmx:beforeProcessNode":
var parent = evt.target;
forEach(queryAttributeOnThisOrChildren(parent, "ws-connect"), function (child) {
ensureWebSocket(child)
});
forEach(queryAttributeOnThisOrChildren(parent, "ws-send"), function (child) {
ensureWebSocketSend(child)
});
}
}
});
function splitOnWhitespace(trigger) {
return trigger.trim().split(/\s+/);
}
function getLegacyWebsocketURL(elt) {
var legacySSEValue = api.getAttributeValue(elt, "hx-ws");
if (legacySSEValue) {
var values = splitOnWhitespace(legacySSEValue);
for (var i = 0; i < values.length; i++) {
var value = values[i].split(/:(.+)/);
if (value[0] === "connect") {
return value[1];
}
}
}
}
/**
* ensureWebSocket creates a new WebSocket on the designated element, using
* the element's "ws-connect" attribute.
* @param {HTMLElement} socketElt
* @returns
*/
function ensureWebSocket(socketElt) {
// If the element containing the WebSocket connection no longer exists, then
// do not connect/reconnect the WebSocket.
if (!api.bodyContains(socketElt)) {
return;
}
// Get the source straight from the element's value
var wssSource = api.getAttributeValue(socketElt, "ws-connect")
if (wssSource == null || wssSource === "") {
var legacySource = getLegacyWebsocketURL(socketElt);
if (legacySource == null) {
return;
} else {
wssSource = legacySource;
}
}
// Guarantee that the wssSource value is a fully qualified URL
if (wssSource.indexOf("/") === 0) {
var base_part = location.hostname + (location.port ? ':' + location.port : '');
if (location.protocol === 'https:') {
wssSource = "wss://" + base_part + wssSource;
} else if (location.protocol === 'http:') {
wssSource = "ws://" + base_part + wssSource;
}
}
var socketWrapper = createWebsocketWrapper(socketElt, function () {
return htmx.createWebSocket(wssSource)
});
socketWrapper.addEventListener('message', function (event) {
if (maybeCloseWebSocketSource(socketElt)) {
return;
}
var response = event.data;
if (!api.triggerEvent(socketElt, "htmx:wsBeforeMessage", {
message: response,
socketWrapper: socketWrapper.publicInterface
})) {
return;
}
api.withExtensions(socketElt, function (extension) {
response = extension.transformResponse(response, null, socketElt);
});
var settleInfo = api.makeSettleInfo(socketElt);
var fragment = api.makeFragment(response);
if (fragment.children.length) {
var children = Array.from(fragment.children);
for (var i = 0; i < children.length; i++) {
api.oobSwap(api.getAttributeValue(children[i], "hx-swap-oob") || "true", children[i], settleInfo);
}
}
api.settleImmediately(settleInfo.tasks);
api.triggerEvent(socketElt, "htmx:wsAfterMessage", { message: response, socketWrapper: socketWrapper.publicInterface })
});
// Put the WebSocket into the HTML Element's custom data.
api.getInternalData(socketElt).webSocket = socketWrapper;
}
/**
* @typedef {Object} WebSocketWrapper
* @property {WebSocket} socket
* @property {Array<{message: string, sendElt: Element}>} messageQueue
* @property {number} retryCount
* @property {(message: string, sendElt: Element) => void} sendImmediately sendImmediately sends message regardless of websocket connection state
* @property {(message: string, sendElt: Element) => void} send
* @property {(event: string, handler: Function) => void} addEventListener
* @property {() => void} handleQueuedMessages
* @property {() => void} init
* @property {() => void} close
*/
/**
*
* @param socketElt
* @param socketFunc
* @returns {WebSocketWrapper}
*/
function createWebsocketWrapper(socketElt, socketFunc) {
var wrapper = {
socket: null,
messageQueue: [],
retryCount: 0,
/** @type {Object<string, Function[]>} */
events: {},
addEventListener: function (event, handler) {
if (this.socket) {
this.socket.addEventListener(event, handler);
}
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(handler);
},
sendImmediately: function (message, sendElt) {
if (!this.socket) {
api.triggerErrorEvent()
}
if (!sendElt || api.triggerEvent(sendElt, 'htmx:wsBeforeSend', {
message: message,
socketWrapper: this.publicInterface
})) {
this.socket.send(message);
sendElt && api.triggerEvent(sendElt, 'htmx:wsAfterSend', {
message: message,
socketWrapper: this.publicInterface
})
}
},
send: function (message, sendElt) {
if (this.socket.readyState !== this.socket.OPEN) {
this.messageQueue.push({ message: message, sendElt: sendElt });
} else {
this.sendImmediately(message, sendElt);
}
},
handleQueuedMessages: function () {
while (this.messageQueue.length > 0) {
var queuedItem = this.messageQueue[0]
if (this.socket.readyState === this.socket.OPEN) {
this.sendImmediately(queuedItem.message, queuedItem.sendElt);
this.messageQueue.shift();
} else {
break;
}
}
},
init: function () {
if (this.socket && this.socket.readyState === this.socket.OPEN) {
// Close discarded socket
this.socket.close()
}
// Create a new WebSocket and event handlers
/** @type {WebSocket} */
var socket = socketFunc();
// The event.type detail is added for interface conformance with the
// other two lifecycle events (open and close) so a single handler method
// can handle them polymorphically, if required.
api.triggerEvent(socketElt, "htmx:wsConnecting", { event: { type: 'connecting' } });
this.socket = socket;
socket.onopen = function (e) {
wrapper.retryCount = 0;
api.triggerEvent(socketElt, "htmx:wsOpen", { event: e, socketWrapper: wrapper.publicInterface });
wrapper.handleQueuedMessages();
}
socket.onclose = function (e) {
// If socket should not be connected, stop further attempts to establish connection
// If Abnormal Closure/Service Restart/Try Again Later, then set a timer to reconnect after a pause.
if (!maybeCloseWebSocketSource(socketElt) && [1006, 1012, 1013].indexOf(e.code) >= 0) {
var delay = getWebSocketReconnectDelay(wrapper.retryCount);
setTimeout(function () {
wrapper.retryCount += 1;
wrapper.init();
}, delay);
}
// Notify client code that connection has been closed. Client code can inspect `event` field
// to determine whether closure has been valid or abnormal
api.triggerEvent(socketElt, "htmx:wsClose", { event: e, socketWrapper: wrapper.publicInterface })
};
socket.onerror = function (e) {
api.triggerErrorEvent(socketElt, "htmx:wsError", { error: e, socketWrapper: wrapper });
maybeCloseWebSocketSource(socketElt);
};
var events = this.events;
Object.keys(events).forEach(function (k) {
events[k].forEach(function (e) {
socket.addEventListener(k, e);
})
});
},
close: function () {
this.socket.close()
}
}
wrapper.init();
wrapper.publicInterface = {
send: wrapper.send.bind(wrapper),
sendImmediately: wrapper.sendImmediately.bind(wrapper),
queue: wrapper.messageQueue
};
return wrapper;
}
/**
* ensureWebSocketSend attaches trigger handles to elements with
* "ws-send" attribute
* @param {HTMLElement} elt
*/
function ensureWebSocketSend(elt) {
var legacyAttribute = api.getAttributeValue(elt, "hx-ws");
if (legacyAttribute && legacyAttribute !== 'send') {
return;
}
var webSocketParent = api.getClosestMatch(elt, hasWebSocket)
processWebSocketSend(webSocketParent, elt);
}
/**
* hasWebSocket function checks if a node has webSocket instance attached
* @param {HTMLElement} node
* @returns {boolean}
*/
function hasWebSocket(node) {
return api.getInternalData(node).webSocket != null;
}
/**
* processWebSocketSend adds event listeners to the <form> element so that
* messages can be sent to the WebSocket server when the form is submitted.
* @param {HTMLElement} socketElt
* @param {HTMLElement} sendElt
*/
function processWebSocketSend(socketElt, sendElt) {
var nodeData = api.getInternalData(sendElt);
var triggerSpecs = api.getTriggerSpecs(sendElt);
triggerSpecs.forEach(function (ts) {
api.addTriggerHandler(sendElt, ts, nodeData, function (elt, evt) {
if (maybeCloseWebSocketSource(socketElt)) {
return;
}
/** @type {WebSocketWrapper} */
var socketWrapper = api.getInternalData(socketElt).webSocket;
var headers = api.getHeaders(sendElt, api.getTarget(sendElt));
var results = api.getInputValues(sendElt, 'post');
var errors = results.errors;
var rawParameters = results.values;
var expressionVars = api.getExpressionVars(sendElt);
var allParameters = api.mergeObjects(rawParameters, expressionVars);
var filteredParameters = api.filterValues(allParameters, sendElt);
var sendConfig = {
parameters: filteredParameters,
unfilteredParameters: allParameters,
headers: headers,
errors: errors,
triggeringEvent: evt,
messageBody: undefined,
socketWrapper: socketWrapper.publicInterface
};
if (!api.triggerEvent(elt, 'htmx:wsConfigSend', sendConfig)) {
return;
}
if (errors && errors.length > 0) {
api.triggerEvent(elt, 'htmx:validation:halted', errors);
return;
}
var body = sendConfig.messageBody;
if (body === undefined) {
var toSend = Object.assign({}, sendConfig.parameters);
if (sendConfig.headers)
toSend['HEADERS'] = headers;
body = JSON.stringify(toSend);
}
socketWrapper.send(body, elt);
if (evt && api.shouldCancel(evt, elt)) {
evt.preventDefault();
}
});
});
}
/**
* getWebSocketReconnectDelay is the default easing function for WebSocket reconnects.
* @param {number} retryCount // The number of retries that have already taken place
* @returns {number}
*/
function getWebSocketReconnectDelay(retryCount) {
/** @type {"full-jitter" | ((retryCount:number) => number)} */
var delay = htmx.config.wsReconnectDelay;
if (typeof delay === 'function') {
return delay(retryCount);
}
if (delay === 'full-jitter') {
var exp = Math.min(retryCount, 6);
var maxDelay = 1000 * Math.pow(2, exp);
return maxDelay * Math.random();
}
logError('htmx.config.wsReconnectDelay must either be a function or the string "full-jitter"');
}
/**
* maybeCloseWebSocketSource checks to the if the element that created the WebSocket
* still exists in the DOM. If NOT, then the WebSocket is closed and this function
* returns TRUE. If the element DOES EXIST, then no action is taken, and this function
* returns FALSE.
*
* @param {*} elt
* @returns
*/
function maybeCloseWebSocketSource(elt) {
if (!api.bodyContains(elt)) {
api.getInternalData(elt).webSocket.close();
return true;
}
return false;
}
/**
* createWebSocket is the default method for creating new WebSocket objects.
* it is hoisted into htmx.createWebSocket to be overridden by the user, if needed.
*
* @param {string} url
* @returns WebSocket
*/
function createWebSocket(url) {
var sock = new WebSocket(url, []);
sock.binaryType = htmx.config.wsBinaryType;
return sock;
}
/**
* queryAttributeOnThisOrChildren returns all nodes that contain the requested attributeName, INCLUDING THE PROVIDED ROOT ELEMENT.
*
* @param {HTMLElement} elt
* @param {string} attributeName
*/
function queryAttributeOnThisOrChildren(elt, attributeName) {
var result = []
// If the parent element also contains the requested attribute, then add it to the results too.
if (api.hasAttribute(elt, attributeName) || api.hasAttribute(elt, "hx-ws")) {
result.push(elt);
}
// Search all child nodes that match the requested attribute
elt.querySelectorAll("[" + attributeName + "], [data-" + attributeName + "], [data-hx-ws], [hx-ws]").forEach(function (node) {
result.push(node)
})
return result
}
/**
* @template T
* @param {T[]} arr
* @param {(T) => void} func
*/
function forEach(arr, func) {
if (arr) {
for (var i = 0; i < arr.length; i++) {
func(arr[i]);
}
}
}
})();
+450
View File
@@ -0,0 +1,450 @@
// https://htmx.org/reference/#api
/**
* This method adds a class to the given element.
*
* https://htmx.org/api/#addClass
*
* @param elt the element to add the class to
* @param clazz the class to add
* @param delay the delay (in milliseconds before class is added)
*/
export function addClass(elt: Element, clazz: string, delay?: number): void;
/**
* Issues an htmx-style AJAX request
*
* https://htmx.org/api/#ajax
*
* @param verb 'GET', 'POST', etc.
* @param path the URL path to make the AJAX
* @param element the element to target (defaults to the **body**)
* @returns Promise that resolves immediately if no request is sent, or when the request is complete
*/
export function ajax(verb: string, path: string, element: Element): Promise<void>;
/**
* Issues an htmx-style AJAX request
*
* https://htmx.org/api/#ajax
*
* @param verb 'GET', 'POST', etc.
* @param path the URL path to make the AJAX
* @param selector a selector for the target
* @returns Promise that resolves immediately if no request is sent, or when the request is complete
*/
export function ajax(verb: string, path: string, selector: string): Promise<void>;
/**
* Issues an htmx-style AJAX request
*
* https://htmx.org/api/#ajax
*
* @param verb 'GET', 'POST', etc.
* @param path the URL path to make the AJAX
* @param context a context object that contains any of the following
* @returns Promise that resolves immediately if no request is sent, or when the request is complete
*/
export function ajax(
verb: string,
path: string,
context: Partial<{ source: any; event: any; handler: any; target: any; swap: any; values: any; headers: any; select: any }>
): Promise<void>;
/**
* Finds the closest matching element in the given elements parentage, inclusive of the element
*
* https://htmx.org/api/#closest
*
* @param elt the element to find the selector from
* @param selector the selector to find
*/
export function closest(elt: Element, selector: string): Element | null;
/**
* A property holding the configuration htmx uses at runtime.
*
* Note that using a [meta tag](https://htmx.org/docs/#config) is the preferred mechanism for setting these properties.
*
* https://htmx.org/api/#config
*/
export var config: HtmxConfig;
/**
* A property used to create new [Server Sent Event](https://htmx.org/docs/#sse) sources. This can be updated to provide custom SSE setup.
*
* https://htmx.org/api/#createEventSource
*/
export var createEventSource: (url: string) => EventSource;
/**
* A property used to create new [WebSocket](https://htmx.org/docs/#websockets). This can be updated to provide custom WebSocket setup.
*
* https://htmx.org/api/#createWebSocket
*/
export var createWebSocket: (url: string) => WebSocket;
/**
* Defines a new htmx [extension](https://htmx.org/extensions).
*
* https://htmx.org/api/#defineExtension
*
* @param name the extension name
* @param ext the extension definition
*/
export function defineExtension(name: string, ext: HtmxExtension): void;
/**
* Finds an element matching the selector
*
* https://htmx.org/api/#find
*
* @param selector the selector to match
*/
export function find(selector: string): Element | null;
/**
* Finds an element matching the selector
*
* https://htmx.org/api/#find
*
* @param elt the root element to find the matching element in, inclusive
* @param selector the selector to match
*/
export function find(elt: Element, selector: string): Element | null;
/**
* Finds all elements matching the selector
*
* https://htmx.org/api/#findAll
*
* @param selector the selector to match
*/
export function findAll(selector: string): NodeListOf<Element>;
/**
* Finds all elements matching the selector
*
* https://htmx.org/api/#findAll
*
* @param elt the root element to find the matching elements in, inclusive
* @param selector the selector to match
*/
export function findAll(elt: Element, selector: string): NodeListOf<Element>;
/**
* Log all htmx events, useful for debugging.
*
* https://htmx.org/api/#logAll
*/
export function logAll(): void;
/**
* The logger htmx uses to log with
*
* https://htmx.org/api/#logger
*/
export var logger: (elt: Element, eventName: string, detail: any) => void | null;
/**
* Removes an event listener from an element
*
* https://htmx.org/api/#off
*
* @param eventName the event name to remove the listener from
* @param listener the listener to remove
*/
export function off(eventName: string, listener: (evt: Event) => void): (evt: Event) => void;
/**
* Removes an event listener from an element
*
* https://htmx.org/api/#off
*
* @param target the element to remove the listener from
* @param eventName the event name to remove the listener from
* @param listener the listener to remove
*/
export function off(target: string, eventName: string, listener: (evt: Event) => void): (evt: Event) => void;
/**
* Adds an event listener to an element
*
* https://htmx.org/api/#on
*
* @param eventName the event name to add the listener for
* @param listener the listener to add
*/
export function on(eventName: string, listener: (evt: Event) => void): (evt: Event) => void;
/**
* Adds an event listener to an element
*
* https://htmx.org/api/#on
*
* @param target the element to add the listener to
* @param eventName the event name to add the listener for
* @param listener the listener to add
*/
export function on(target: string, eventName: string, listener: (evt: Event) => void): (evt: Event) => void;
/**
* Adds a callback for the **htmx:load** event. This can be used to process new content, for example initializing the content with a javascript library
*
* https://htmx.org/api/#onLoad
*
* @param callback the callback to call on newly loaded content
*/
export function onLoad(callback: (element: Element) => void): void;
/**
* Parses an interval string consistent with the way htmx does. Useful for plugins that have timing-related attributes.
*
* Caution: Accepts an int followed by either **s** or **ms**. All other values use **parseFloat**
*
* https://htmx.org/api/#parseInterval
*
* @param str timing string
*/
export function parseInterval(str: string): number;
/**
* Processes new content, enabling htmx behavior. This can be useful if you have content that is added to the DOM outside of the normal htmx request cycle but still want htmx attributes to work.
*
* https://htmx.org/api/#process
*
* @param element element to process
*/
export function process(element: Element): void;
/**
* Removes an element from the DOM
*
* https://htmx.org/api/#remove
*
* @param elt element to remove
* @param delay the delay (in milliseconds before element is removed)
*/
export function remove(elt: Element, delay?: number): void;
/**
* Removes a class from the given element
*
* https://htmx.org/api/#removeClass
*
* @param elt element to remove the class from
* @param clazz the class to remove
* @param delay the delay (in milliseconds before class is removed)
*/
export function removeClass(elt: Element, clazz: string, delay?: number): void;
/**
* Removes the given extension from htmx
*
* https://htmx.org/api/#removeExtension
*
* @param name the name of the extension to remove
*/
export function removeExtension(name: string): void;
/**
* Takes the given class from its siblings, so that among its siblings, only the given element will have the class.
*
* https://htmx.org/api/#takeClass
*
* @param elt the element that will take the class
* @param clazz the class to take
*/
export function takeClass(elt: Element, clazz: string): void;
/**
* Toggles the given class on an element
*
* https://htmx.org/api/#toggleClass
*
* @param elt the element to toggle the class on
* @param clazz the class to toggle
*/
export function toggleClass(elt: Element, clazz: string): void;
/**
* Triggers a given event on an element
*
* https://htmx.org/api/#trigger
*
* @param elt the element to trigger the event on
* @param name the name of the event to trigger
* @param detail details for the event
*/
export function trigger(elt: Element, name: string, detail: any): void;
/**
* Returns the input values that would resolve for a given element via the htmx value resolution mechanism
*
* https://htmx.org/api/#values
*
* @param elt the element to resolve values on
* @param requestType the request type (e.g. **get** or **post**) non-GET's will include the enclosing form of the element. Defaults to **post**
*/
export function values(elt: Element, requestType?: string): any;
export const version: string;
export interface HtmxConfig {
/**
* The attributes to settle during the settling phase.
* @default ["class", "style", "width", "height"]
*/
attributesToSettle?: ["class", "style", "width", "height"] | string[];
/**
* If the focused element should be scrolled into view.
* @default false
*/
defaultFocusScroll?: boolean;
/**
* The default delay between completing the content swap and settling attributes.
* @default 20
*/
defaultSettleDelay?: number;
/**
* The default delay between receiving a response from the server and doing the swap.
* @default 0
*/
defaultSwapDelay?: number;
/**
* The default swap style to use if **[hx-swap](https://htmx.org/attributes/hx-swap)** is omitted.
* @default "innerHTML"
*/
defaultSwapStyle?: "innerHTML" | string;
/**
* The number of pages to keep in **localStorage** for history support.
* @default 10
*/
historyCacheSize?: number;
/**
* Whether or not to use history.
* @default true
*/
historyEnabled?: boolean;
/**
* If true, htmx will inject a small amount of CSS into the page to make indicators invisible unless the **htmx-indicator** class is present.
* @default true
*/
includeIndicatorStyles?: boolean;
/**
* The class to place on indicators when a request is in flight.
* @default "htmx-indicator"
*/
indicatorClass?: "htmx-indicator" | string;
/**
* The class to place on triggering elements when a request is in flight.
* @default "htmx-request"
*/
requestClass?: "htmx-request" | string;
/**
* The class to temporarily place on elements that htmx has added to the DOM.
* @default "htmx-added"
*/
addedClass?: "htmx-added" | string;
/**
* The class to place on target elements when htmx is in the settling phase.
* @default "htmx-settling"
*/
settlingClass?: "htmx-settling" | string;
/**
* The class to place on target elements when htmx is in the swapping phase.
* @default "htmx-swapping"
*/
swappingClass?: "htmx-swapping" | string;
/**
* Allows the use of eval-like functionality in htmx, to enable **hx-vars**, trigger conditions & script tag evaluation. Can be set to **false** for CSP compatibility.
* @default true
*/
allowEval?: boolean;
/**
* Use HTML template tags for parsing content from the server. This allows you to use Out of Band content when returning things like table rows, but it is *not* IE11 compatible.
* @default false
*/
useTemplateFragments?: boolean;
/**
* Allow cross-site Access-Control requests using credentials such as cookies, authorization headers or TLS client certificates.
* @default false
*/
withCredentials?: boolean;
/**
* The default implementation of **getWebSocketReconnectDelay** for reconnecting after unexpected connection loss by the event code **Abnormal Closure**, **Service Restart** or **Try Again Later**.
* @default "full-jitter"
*/
wsReconnectDelay?: "full-jitter" | string | ((retryCount: number) => number);
// following don't appear in the docs
/** @default false */
refreshOnHistoryMiss?: boolean;
/** @default 0 */
timeout?: number;
/** @default "[hx-disable], [data-hx-disable]" */
disableSelector?: "[hx-disable], [data-hx-disable]" | string;
/** @default "smooth" */
scrollBehavior?: "smooth" | "auto";
/**
* If set to false, disables the interpretation of script tags.
* @default true
*/
allowScriptTags?: boolean;
/**
* If set to true, disables htmx-based requests to non-origin hosts.
* @default false
*/
selfRequestsOnly?: boolean;
/**
* Whether or not the target of a boosted element is scrolled into the viewport.
* @default true
*/
scrollIntoViewOnBoost?: boolean;
/**
* If set, the nonce will be added to inline scripts.
* @default ''
*/
inlineScriptNonce?: string;
/**
* The type of binary data being received over the WebSocket connection
* @default 'blob'
*/
wsBinaryType?: 'blob' | 'arraybuffer';
/**
* If set to true htmx will include a cache-busting parameter in GET requests to avoid caching partial responses by the browser
* @default false
*/
getCacheBusterParam?: boolean;
/**
* If set to true, htmx will use the View Transition API when swapping in new content.
* @default false
*/
globalViewTransitions?: boolean;
/**
* htmx will format requests with these methods by encoding their parameters in the URL, not the request body
* @default ["get"]
*/
methodsThatUseUrlParams?: ('get' | 'head' | 'post' | 'put' | 'delete' | 'connect' | 'options' | 'trace' | 'patch' )[];
/**
* If set to true htmx will not update the title of the document when a title tag is found in new content
* @default false
*/
ignoreTitle:? boolean;
/**
* The cache to store evaluated trigger specifications into.
* You may define a simple object to use a never-clearing cache, or implement your own system using a [proxy object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy)
* @default null
*/
triggerSpecsCache?: {[trigger: string]: HtmxTriggerSpecification[]};
}
/**
* https://htmx.org/extensions/#defining
*/
export interface HtmxExtension {
onEvent?: (name: string, evt: CustomEvent) => any;
transformResponse?: (text: any, xhr: XMLHttpRequest, elt: any) => any;
isInlineSwap?: (swapStyle: any) => any;
handleSwap?: (swapStyle: any, target: any, fragment: any, settleInfo: any) => any;
encodeParameters?: (xhr: XMLHttpRequest, parameters: any, elt: any) => any;
}
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
(function(e,t){if(typeof define==="function"&&define.amd){define([],t)}else if(typeof module==="object"&&module.exports){module.exports=t()}else{e.htmx=e.htmx||t()}})(typeof self!=="undefined"?self:this,function(){return function(){"use strict";var Q={onLoad:j,process:Wt,on:me,off:pe,trigger:ce,ajax:kr,find:C,findAll:f,closest:v,values:function(e,t){var r=mr(e,t||"post");return r.values},remove:$,addClass:W,removeClass:n,toggleClass:G,takeClass:J,defineExtension:Fr,removeExtension:Vr,logAll:_,logNone:z,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",useTemplateFragments:false,scrollBehavior:"smooth",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get"],selfRequestsOnly:false,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null},parseInterval:d,_:t,createEventSource:function(e){return new EventSource(e,{withCredentials:true})},createWebSocket:function(e){var t=new WebSocket(e,[]);t.binaryType=Q.config.wsBinaryType;return t},version:"1.9.10"};var r={addTriggerHandler:Nt,bodyContains:se,canAccessLocalStorage:F,findThisElement:be,filterValues:wr,hasAttribute:o,getAttributeValue:te,getClosestAttributeValue:ne,getClosestMatch:c,getExpressionVars:Ar,getHeaders:br,getInputValues:mr,getInternalData:ae,getSwapSpecification:Er,getTriggerSpecs:ot,getTarget:we,makeFragment:l,mergeObjects:le,makeSettleInfo:T,oobSwap:Re,querySelectorExt:ue,selectAndSwap:ze,settleImmediately:ar,shouldCancel:ct,triggerEvent:ce,triggerErrorEvent:fe,withExtensions:R};var w=["g","circle","rect"];var S=["get","post","put","delete","patch"];var i=S.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");var q=e("head"),H=e("title"),L=e("svg",true);function e(e,t=false){return new RegExp(`<${e}(\\s[^>]*>|>)([\\s\\S]*?)<\\/${e}>`,t?"gim":"im")}function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e.getAttribute&&e.getAttribute(t)}function o(e,t){return e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function u(e){return e.parentElement}function re(){return document}function c(e,t){while(e&&!t(e)){e=u(e)}return e?e:null}function A(e,t,r){var n=te(t,r);var i=te(t,"hx-disinherit");if(e!==t&&i&&(i==="*"||i.split(" ").indexOf(r)>=0)){return"unset"}else{return n}}function ne(t,r){var n=null;c(t,function(e){return n=A(t,e,r)});if(n!=="unset"){return n}}function h(e,t){var r=e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector;return r&&r.call(e,t)}function N(e){var t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;var r=t.exec(e);if(r){return r[1].toLowerCase()}else{return""}}function a(e,t){var r=new DOMParser;var n=r.parseFromString(e,"text/html");var i=n.body;while(t>0){t--;i=i.firstChild}if(i==null){i=re().createDocumentFragment()}return i}function I(e){return a('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">'+e+"</svg>",1)}function k(e){return/<body/.test(e)}function l(e){var t=!k(e);var r=N(e);var n=e;if(r==="head"){n=n.replace(q,"")}if(Q.config.useTemplateFragments&&t){var i=a("<body><template>"+n+"</template></body>",0);return i.querySelector("template").content}switch(r){case"thead":case"tbody":case"tfoot":case"colgroup":case"caption":return a("<table>"+n+"</table>",1);case"col":return a("<table><colgroup>"+n+"</colgroup></table>",2);case"tr":return a("<table><tbody>"+n+"</tbody></table>",2);case"td":case"th":return a("<table><tbody><tr>"+n+"</tr></tbody></table>",3);case"script":case"style":return a("<div>"+n+"</div>",1);default:return w.indexOf(r)!==-1?I(n):a(n,0)}}function ie(e){if(e){e()}}function P(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function M(e){return P(e,"Function")}function X(e){return P(e,"Object")}function ae(e){var t="htmx-internal-data";var r=e[t];if(!r){r=e[t]={}}return r}function D(e){var t=[];if(e){for(var r=0;r<e.length;r++){t.push(e[r])}}return t}function oe(e,t){if(e){for(var r=0;r<e.length;r++){t(e[r])}}}function U(e){var t=e.getBoundingClientRect();var r=t.top;var n=t.bottom;return r<window.innerHeight&&n>=0}function se(e){if(e.getRootNode&&e.getRootNode()instanceof window.ShadowRoot){return re().body.contains(e.getRootNode().host)}Line truncated
Binary file not shown.
+96
View File
@@ -0,0 +1,96 @@
import htmx from "./htmx";
// add the class 'myClass' to the element with the id 'demo'
htmx.addClass(htmx.find("#demo"), "myClass");
// issue a GET to /example and put the response HTML into #myDiv
htmx.ajax("GET", "/example", "#myDiv");
// find the closest enclosing div of the element with the id 'demo'
htmx.closest(htmx.find("#demo"), "div");
// update the history cache size to 30
htmx.config.historyCacheSize = 30;
// override SSE event sources to not use credentials
htmx.createEventSource = function (url) {
return new EventSource(url, { withCredentials: false });
};
// override WebSocket to use a specific protocol
htmx.createWebSocket = function (url) {
return new WebSocket(url, ["wss"]);
};
// defines a silly extension that just logs the name of all events triggered
htmx.defineExtension("silly", {
onEvent: function (name, evt) {
console.log("Event " + name + " was triggered!");
}
});
// find div with id my-div
var div = htmx.find("#my-div");
// find div with id another-div within that div
var anotherDiv = htmx.find(div, "#another-div");
// find all divs
var allDivs = htmx.findAll("div");
// find all paragraphs within a given div
var allParagraphsInMyDiv = htmx.findAll(htmx.find("#my-div"), "p");
htmx.logAll();
// remove this click listener from the body
htmx.off("click", myEventListener);
// remove this click listener from the given div
htmx.off("#my-div", "click", myEventListener);
// add a click listener to the body
var myEventListener = htmx.on("click", function (evt) {
console.log(evt);
});
// add a click listener to the given div
var myEventListener = htmx.on("#my-div", "click", function (evt) {
console.log(evt);
});
const MyLibrary: any = null;
htmx.onLoad(function (elt) {
MyLibrary.init(elt);
});
// returns 3000
var milliseconds = htmx.parseInterval("3s");
// returns 3 - Caution
var milliseconds = htmx.parseInterval("3m");
document.body.innerHTML = "<div hx-get='/example'>Get it!</div>";
// process the newly added content
htmx.process(document.body);
// removes my-div from the DOM
htmx.remove(htmx.find("#my-div"));
// removes .myClass from my-div
htmx.removeClass(htmx.find("#my-div"), "myClass");
htmx.removeExtension("my-extension");
// takes the selected class from tab2"s siblings
htmx.takeClass(htmx.find("#tab2"), "selected");
// toggles the selected class on tab2
htmx.toggleClass(htmx.find("#tab2"), "selected");
// triggers the myEvent event on #tab2 with the answer 42
htmx.trigger(htmx.find("#tab2"), "myEvent", { answer: 42 });
// gets the values associated with this form
var values = htmx.values(htmx.find("#myForm"));
+9
View File
@@ -0,0 +1,9 @@
import {app} from "./src/server.ts";
import Logger from "https://deno.land/x/logger@v1.1.5/logger.ts";
const logger = new Logger()
const port = 8000
logger.info(`Starting web server on port ${port}`)
await app.listen({ port });
+65
View File
@@ -0,0 +1,65 @@
import {Router} from "https://deno.land/x/oak/mod.ts";
import {FileMatchService} from "../services/matches.ts";
import {ViewTabService} from "./tab.tsx";
export const apiRouter = new Router( {prefix: '/api/v1'});
async function getMatchService(): Promise<FileMatchService> {
const f = "/home/didier/all-dressed-programming/dodgeball-tracker/outputs/index.json"
return new FileMatchService(f)
}
apiRouter.get('/ping', (ctx) => {
ctx.response.body = <span>pong</span>
})
apiRouter.get("/match/:id/title", async function(ctx){
const service = await getMatchService()
const match = await service.getMatchInfoById(ctx.params.id)
ctx.response.body = (<span>Match: {match.label}</span>)
});
apiRouter.get("/match/:id/pane/info", async function(ctx){
const service = await getMatchService()
const match = await service.getMatchInfoById(ctx.params.id)
const viewService = new ViewTabService();
ctx.response.body = viewService.infoTab(match)
});
apiRouter.get("/match/:id/pane/player", async function(ctx){
const service = await getMatchService()
const match = await service.getMatchInfoById(ctx.params.id)
const viewService = new ViewTabService();
ctx.response.body = viewService.playerTab(match)
});
apiRouter.get("/match/:id/pane/player/data", async function(ctx){
ctx.response.body = <rect width="100" height="100"/>
});
apiRouter.get('/list-matches', async (ctx) => {
const matchService = await getMatchService()
const rows = [];
for await (const match of matchService.getAllMatchInfo()){
rows.push(
<tr>
<td><a href={`/match/${match.id}/info`}>{ match.label }</a></td>
<td><a href={match.originalVideoUrl}>{ match.originalVideoUrl }</a></td>
</tr>
)
}
ctx.response.body = (<div>
<table class="table is-bordered is-striped is-fullwidth">
<thead>
<tr>
<th>Label</th>
<th>Video Link</th>
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>
</div>)
})
+74
View File
@@ -0,0 +1,74 @@
import {MatchInfo} from "../services/matches.ts";
export class ViewTabService {
infoTab(matchInfo: MatchInfo){
return (<table class="table is-bordered is-striped is-fullwidth">
<tbody>
<tr>
<td>Label</td>
<td>{matchInfo.label}</td>
</tr>
<tr>
<td>Id</td>
<td>{matchInfo.id}</td>
</tr>
<tr>
<td>Date</td>
<td>{matchInfo.matchDate}</td>
</tr>
<tr>
<td>Video URL</td>
<td>
<a href={matchInfo.originalVideoUrl}>{matchInfo.originalVideoUrl}</a>
</td>
</tr>
</tbody>
</table>)
}
playerTab(matchInfo: MatchInfo){
return (<div>
<div id="foo"></div>
<form hx-swap="innerHTML"
hx-get={"/api/v1/match/:id/pane/player/data"}
hx-target="#court-content">
<div class="field is-horizontal">
<div class="field-label is-normal">
<label class="label">Min Time</label>
</div>
<div class="field-body">
<div class="field">
<div class="control">
<input class="input is-danger" type="range" min="0" max="100" />
</div>
</div>
</div>
</div>
<div class="field is-horizontal">
<div class="field-label is-normal">
<label class="label">Max Time</label>
</div>
<div class="field-body">
<div class="field">
<div class="control">
<input class="input is-danger" type="range" min="0" max="100" />
</div>
</div>
</div>
</div>
<div class="field">
<div class="control">
<button class="button"> Show </button>
</div>
</div>
</form>
</div>)
}
}
+25
View File
@@ -0,0 +1,25 @@
import { Router } from "https://deno.land/x/oak/mod.ts";
export const loginRouter = new Router();
export function isLoggedIn(ctx){
return ctx.request.headers.get('dgt-session')
}
loginRouter.post("/api/v1/login", async (ctx)=> {
const username = (await ctx.request.body().value).get("username");
ctx.response.headers.append("HX-Trigger", JSON.stringify({'login': username}));
ctx.response.body = username;
});
loginRouter.post("/api/v1/logout", (ctx)=> {
ctx.response.headers.append("HX-Trigger", "logout");
ctx.response.body = "";
});
+45
View File
@@ -0,0 +1,45 @@
import { Application } from "https://deno.land/x/oak/mod.ts";
import staticFiles from "https://deno.land/x/static_files@1.1.6/mod.ts";
import {loginRouter, isLoggedIn} from "./login.ts";
import {apiRouter} from "./api/mod.tsx";
import {viewRouter} from "./views/mod.tsx";
import {renderToString} from "https://esm.sh/preact-render-to-string@5.1.19?deps=preact@10.5.15";
import Logger from "https://deno.land/x/logger@v1.1.5/logger.ts";
const logger = new Logger();
export const app = new Application();
function isReactComponent(x){
return !!x && Object.hasOwn(x, "type") && Object.hasOwn(x, "props")
}
async function reactRendererMiddleware(ctx, next){
await next();
if(isReactComponent(ctx.response.body)){
logger.info("Converting react component to string.")
ctx.response.body = renderToString(ctx.response.body)
}
}
async function loggingMiddleware(ctx, next){
if(!isLoggedIn(ctx)){
logger.info("user not logged in.")
ctx.response.headers.append("HX-Redirect", "/login.html");
return
}
logger.info('user logged in')
await next();
}
app.use(loginRouter.routes());
app.use(viewRouter.routes());
app.use(staticFiles("public", {brotli: true, fetch: true}));
app.use(loggingMiddleware)
app.use(reactRendererMiddleware)
app.use(apiRouter.routes());
+41
View File
@@ -0,0 +1,41 @@
export type MatchInfo = {
id: string,
originalVideoUrl: string,
matchDate: string,
label: string
}
export interface MatchService {
getAllMatchInfo(): AsyncIterator<MatchInfo>;
getMatchInfoById(id: string): Promise<MatchInfo|undefined>;
}
export class FileMatchService implements MatchService{
readonly #indexFile: string
constructor(indexFile: string) {
this.#indexFile = indexFile;
}
async *getAllMatchInfo(): AsyncIterator<MatchInfo>{
const data = await Deno.readTextFile(this.#indexFile)
const ret = JSON.parse(data) as {matches: MatchInfo[]}
yield* ret.matches
}
async getMatchInfoById(id: string): Promise<MatchInfo|undefined>{
for await(const mi of this.getAllMatchInfo()){
if(mi.id === id){
return mi
}
}
}
}
+48
View File
@@ -0,0 +1,48 @@
export function Head(){
return (<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta http-equiv="X-UA-Compatible" content="ie=edge"/>
<title>JS Reading App</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/styles/default.min.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-light.min.css"/>
<script src="/vendor/htmx/htmx.js"></script>
</head>)
}
export function NavBar(){
return (<nav class="navbar" role="navigation" aria-label="main navigation">
<div class="navbar-menu is-active">
<div class="navbar-start">
<span class="navbar-item">
<a href="/">
<img src="/images/logo.png" alt="js logo" style="height: 100%"/>
</a>
</span>
</div>
<div class="navbar-end">
<a class="navbar-item" href="#" hx-post="/api/v1/logout">
Way Out
</a>
</div>
</div>
</nav>)
}
export function Body({pathVariables, children}){
const urlPlaceHolders = {
pathVariables: Object.fromEntries(Object.entries(pathVariables ?? {}).map(([k, v]) => [`:${k}`, v]))
}
return (<body>
{ children }
<script src="/scripts/auth.js" type="module"> </script>
<script
type="json"
id="url-placeholders"
dangerouslySetInnerHTML={{__html: JSON.stringify(urlPlaceHolders, null, 4)}}></script>
</body>)
}
+125
View File
@@ -0,0 +1,125 @@
import { Router } from "https://deno.land/x/oak/mod.ts";
import {renderToString} from "https://esm.sh/preact-render-to-string@5.1.19?deps=preact@10.5.15";
import * as base from './base.tsx';
import {Head} from "./base.tsx";
export const viewRouter = new Router();
function renderPageToString(page){
return `<!DOCTYPE html>${renderToString(page)}`
}
function Court(){
const margin = 50;
const returnLine = {stroke: 'blue', strokeWidth: '2px'}
const courtBorder = {stroke: 'red', strokeWidth: '4px', fill: 'gray' }
const lines = [
<line x1={450} x2={450} y1={0} y2={450} style={courtBorder}></line>,
<line x1={300} x2={300} y1={0} y2={450} style={returnLine}></line>,
<line x1={600} x2={600} y1={0} y2={450} style={returnLine}></line>,
]
return (<svg class="court-side"
xmlns="http://www.w3.org/2000/svg"
style={{width: 900 + 2 * margin, height: 450 + 2 * margin, backgroundColor: 'pink'}}>
<g class="court-border" id="court" transform = {`translate(${margin} ${margin})`}>
<rect width={900} height={450} style={courtBorder}/>
{ lines }
<g id="court-content"></g>
</g>
</svg>)
}
viewRouter.get("/match/:id/:tab", (ctx) => {
const page = (<html lang="en">
<base.Head/>
<base.Body pathVariables={ctx.params}>
<base.NavBar></base.NavBar>
<div class="columns is-centered">
<div class="column is-two-thirds">
<div class="columns">
<div class="column">
<h4 class="title is-4"
hx-get="/api/v1/match/:id/title"
hx-trigger="load"> &nbsp; </h4>
</div>
</div>
<div class="columns">
<div class="column" style={{textAlign: "center"}}>
<Court></Court>
</div>
</div>
<div class="columns">
<div class="column" style={{textAlign: "center"}}>
<div class="tabs">
<ul>
<li className={ctx.params.tab === 'info' ? "is-active": ""}>
<a href={`/match/${ctx.params.id}/info`}>Information</a>
</li>
<li className={ctx.params.tab === 'player' ? "is-active": ""}>
<a href={`/match/${ctx.params.id}/player`}>Player</a>
</li>
</ul>
</div>
</div>
</div>
<div class="columns">
<div class="column"
hx-get={`/api/v1/match/${ctx.params.id}/pane/${ctx.params.tab}`}
hx-trigger="load">
foo bar toto
</div>
</div>
</div>
</div>
</base.Body>
</html>)
ctx.response.body = renderPageToString(page)
})
viewRouter.get("/index.html", (ctx) => {
const page = (<html lang="en">
<base.Head/>
<base.Body>
<base.NavBar></base.NavBar>
<div class="columns is-centered">
<div class="column is-two-thirds"
id="main-block"
hx-get="/api/v1/list-matches"
hx-trigger="load">
</div>
</div>
</base.Body>
</html>)
ctx.response.body = renderPageToString(page)
})
viewRouter.redirect("/", "/index.html")
viewRouter.get("/login.html", (ctx) => {
const page = (<html lang="en">
<base.Head/>
<base.Body>
<base.NavBar></base.NavBar>
<div class="columns is-centered">
<div class="column is-half">
<form hx-post="/api/v1/login" hx-swap="none">
<div class="field has-addons">
<div class="control">
<input class="input" id="username" type="text" placeholder="bob.l.eponge@ocean.com" name="username" required />
</div>
<div class="control">
<input type="submit" class="button" value="Login" />
</div>
</div>
</form>
</div>
</div>
</base.Body>
</html>)
ctx.response.body = renderPageToString(page)
})