File size: 8,941 Bytes
466ed0d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 |
<script lang="ts">
import { createEventDispatcher, tick } from "svelte";
import Handlebars from "handlebars";
let {
elem_classes = [],
props = {},
html_template = "${value}",
css_template = "",
js_on_load = null,
visible = true,
autoscroll = false,
apply_default_css = true,
component_class_name = "HTML"
} = $props();
let old_props = $state(props);
const dispatch = createEventDispatcher<{
event: { type: "click" | "submit"; data: any };
update_value: { data: any; property: "value" | "label" | "visible" };
}>();
const trigger = (
event_type: "click" | "submit",
event_data: any = {}
): void => {
dispatch("event", { type: event_type, data: event_data });
};
let element: HTMLDivElement;
let scrollable_parent: HTMLElement | null = null;
let random_id = `html-${Math.random().toString(36).substring(2, 11)}`;
let style_element: HTMLStyleElement | null = null;
let reactiveProps: Record<string, any> = {};
let currentHtml = $state("");
let currentCss = $state("");
let renderScheduled = $state(false);
let mounted = $state(false);
let error_message: string | null = $state(null);
function get_scrollable_parent(element: HTMLElement): HTMLElement | null {
let parent = element.parentElement;
while (parent) {
const style = window.getComputedStyle(parent);
if (
style.overflow === "auto" ||
style.overflow === "scroll" ||
style.overflowY === "auto" ||
style.overflowY === "scroll"
) {
return parent;
}
parent = parent.parentElement;
}
return null;
}
function is_at_bottom(): boolean {
if (!element) return true;
if (!scrollable_parent) {
return (
window.innerHeight + window.scrollY >=
document.documentElement.scrollHeight - 100
);
}
return (
scrollable_parent.offsetHeight + scrollable_parent.scrollTop >=
scrollable_parent.scrollHeight - 100
);
}
function scroll_to_bottom(): void {
if (!element) return;
if (scrollable_parent) {
scrollable_parent.scrollTo(0, scrollable_parent.scrollHeight);
} else {
window.scrollTo(0, document.documentElement.scrollHeight);
}
}
async function scroll_on_html_update(): Promise<void> {
if (!autoscroll || !element) return;
if (!scrollable_parent) {
scrollable_parent = get_scrollable_parent(element);
}
if (is_at_bottom()) {
await new Promise((resolve) => setTimeout(resolve, 300));
scroll_to_bottom();
}
}
function render_template(
template: string,
props: Record<string, any>
): string {
try {
const handlebarsTemplate = Handlebars.compile(template);
const handlebarsRendered = handlebarsTemplate(props);
const propKeys = Object.keys(props);
const propValues = Object.values(props);
const templateFunc = new Function(
...propKeys,
`return \`${handlebarsRendered}\`;`
);
error_message = null;
return templateFunc(...propValues);
} catch (e) {
console.error("Error evaluating template:", e);
error_message = e instanceof Error ? e.message : String(e);
return "";
}
}
function update_css(): void {
if (typeof document === "undefined") return;
if (!style_element) {
style_element = document.createElement("style");
document.head.appendChild(style_element);
}
currentCss = render_template(css_template, reactiveProps);
if (currentCss) {
style_element.textContent = `#${random_id} { ${currentCss} }`;
} else {
style_element.textContent = "";
}
}
function updateDOM(oldHtml: string, newHtml: string): void {
if (!element || oldHtml === newHtml) return;
const tempContainer = document.createElement("div");
tempContainer.innerHTML = newHtml;
const oldNodes = Array.from(element.childNodes);
const newNodes = Array.from(tempContainer.childNodes);
const maxLength = Math.max(oldNodes.length, newNodes.length);
for (let i = 0; i < maxLength; i++) {
const oldNode = oldNodes[i];
const newNode = newNodes[i];
if (!oldNode && newNode) {
element.appendChild(newNode.cloneNode(true));
} else if (oldNode && !newNode) {
element.removeChild(oldNode);
} else if (oldNode && newNode) {
updateNode(oldNode, newNode);
}
}
}
// eslint-disable-next-line complexity
function updateNode(oldNode: Node, newNode: Node): void {
if (
oldNode.nodeType === Node.TEXT_NODE &&
newNode.nodeType === Node.TEXT_NODE
) {
if (oldNode.textContent !== newNode.textContent) {
oldNode.textContent = newNode.textContent;
}
return;
}
if (
oldNode.nodeType === Node.ELEMENT_NODE &&
newNode.nodeType === Node.ELEMENT_NODE
) {
const oldElement = oldNode as Element;
const newElement = newNode as Element;
if (oldElement.tagName !== newElement.tagName) {
oldNode.parentNode?.replaceChild(newNode.cloneNode(true), oldNode);
return;
}
const oldAttrs = Array.from(oldElement.attributes);
const newAttrs = Array.from(newElement.attributes);
for (const attr of oldAttrs) {
if (!newElement.hasAttribute(attr.name)) {
oldElement.removeAttribute(attr.name);
}
}
for (const attr of newAttrs) {
if (oldElement.getAttribute(attr.name) !== attr.value) {
oldElement.setAttribute(attr.name, attr.value);
if (
attr.name === "value" &&
(oldElement.tagName === "INPUT" ||
oldElement.tagName === "TEXTAREA" ||
oldElement.tagName === "SELECT")
) {
(
oldElement as
| HTMLInputElement
| HTMLTextAreaElement
| HTMLSelectElement
).value = attr.value;
}
}
}
const oldChildren = Array.from(oldElement.childNodes);
const newChildren = Array.from(newElement.childNodes);
const maxChildren = Math.max(oldChildren.length, newChildren.length);
for (let i = 0; i < maxChildren; i++) {
const oldChild = oldChildren[i];
const newChild = newChildren[i];
if (!oldChild && newChild) {
oldElement.appendChild(newChild.cloneNode(true));
} else if (oldChild && !newChild) {
oldElement.removeChild(oldChild);
} else if (oldChild && newChild) {
updateNode(oldChild, newChild);
}
}
} else {
oldNode.parentNode?.replaceChild(newNode.cloneNode(true), oldNode);
}
}
function renderHTML(): void {
console.trace(
"re-rendering HTML with props:",
JSON.stringify(reactiveProps)
);
const newHtml = render_template(html_template, reactiveProps);
if (element) {
updateDOM(currentHtml, newHtml);
}
currentHtml = newHtml;
if (autoscroll) {
scroll_on_html_update();
}
}
function scheduleRender(): void {
if (!renderScheduled) {
renderScheduled = true;
queueMicrotask(() => {
renderScheduled = false;
renderHTML();
update_css();
});
}
}
// Mount effect
$effect(() => {
if (!element || mounted) return;
mounted = true;
reactiveProps = new Proxy(
{ ...props },
{
set(target, property, value) {
const oldValue = target[property as string];
target[property as string] = value;
if (oldValue !== value) {
scheduleRender();
if (
property === "value" ||
property === "label" ||
property === "visible"
) {
props[property] = value;
old_props[property] = value;
dispatch("update_value", { data: value, property });
}
}
return true;
}
}
);
currentHtml = render_template(html_template, reactiveProps);
element.innerHTML = currentHtml;
update_css();
if (autoscroll) {
scroll_to_bottom();
}
scroll_on_html_update();
if (js_on_load && element) {
try {
const func = new Function("element", "trigger", "props", js_on_load);
func(element, trigger, reactiveProps);
} catch (error) {
console.error("Error executing js_on_load:", error);
}
}
});
// Props update effect
$effect(() => {
if (
reactiveProps &&
props &&
JSON.stringify(old_props) !== JSON.stringify(props)
) {
for (const key in props) {
if (reactiveProps[key] !== props[key]) {
reactiveProps[key] = props[key];
}
}
old_props = props;
}
});
</script>
{#if error_message}
<div class="error-container">
<strong class="error-title"
>Error rendering <code class="error-component-name"
>{component_class_name}</code
>:</strong
>
<code class="error-message">{error_message}</code>
</div>
{:else}
<div
bind:this={element}
id={random_id}
class="{apply_default_css ? 'prose gradio-style' : ''} {elem_classes.join(
' '
)}"
class:hide={!visible}
></div>
{/if}
<style>
.hide {
display: none;
}
.error-container {
padding: 12px;
background-color: #fee;
border: 1px solid #fcc;
border-radius: 4px;
color: #c33;
font-family: monospace;
font-size: 13px;
}
.error-title {
display: block;
margin-bottom: 8px;
}
.error-component-name {
background-color: #fdd;
padding: 2px 4px;
border-radius: 2px;
}
.error-message {
white-space: pre-wrap;
word-break: break-word;
}
</style>
|