Spaces:
Sleeping
Sleeping
File size: 37,184 Bytes
9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9e75b1f 9345109 a19bf9a 9345109 9e75b1f a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9e75b1f a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 9e75b1f 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 52af442 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9e75b1f a19bf9a 9e75b1f a19bf9a 9345109 52af442 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 52af442 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 a19bf9a 9345109 | 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 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 | /*!
* Eolas — Screen Ireland assistant widget
* ----------------------------------------------------------------------------
* Self-mounting chat widget. Renders inside a Shadow DOM so it can't be
* styled or broken by the host page's CSS.
*
* Embed (production, on screenireland.ie):
* <script>window.SCREENIRELAND_BOT_API = "https://your-api.example";</script>
* <script src="https://cdn.example/widget.js"></script>
*
* Embed (local dev against the running backend):
* <script src="http://127.0.0.1:8000/widget.js"></script>
*
* Standalone demo with NO backend (streams a canned answer so the UI is alive):
* <script>window.SCREENIRELAND_BOT_DEMO = true;</script>
* <script src="widget.js"></script>
*
* ============================================================================
* HANDOFF NOTES FOR CLAUDE CODE
* ----------------------------------------------------------------------------
* The transport layer is intentionally unchanged from Stage 1D. Do NOT alter:
* - the fetch + ReadableStream + SSE parsing in ask()
* - the Shadow DOM mount
* - the window.SCREENIRELAND_BOT_API override hook
* - the request shape POST {API}/chat body {"question": "..."}
* - the response events token {delta} · sources {sources[]} · done {reason}
*
* Everything else (markup, styles, chips, feedback, nudge, mobile) is the UI
* layer and is safe to tweak. The DEMO MOCK block is for the standalone demo
* only — delete it (and the window.SCREENIRELAND_BOT_DEMO flag) for production.
* ============================================================================
*/
(function () {
"use strict";
if (window.__eolasBotMounted) return;
window.__eolasBotMounted = true;
// ── API origin resolution (PRESERVED) ──────────────────────────────────────
// Infer the API origin from this script's src, unless explicitly overridden.
const me = document.currentScript || (function () {
const s = document.getElementsByTagName("script");
return s[s.length - 1];
})();
const apiBase = (window.SCREENIRELAND_BOT_API
|| (me && me.src ? new URL(me.src).origin : ""));
const DEMO = !!window.SCREENIRELAND_BOT_DEMO; // standalone demo, no backend
// ── Brand font (injected once into the host document) ───────────────────────
if (!document.getElementById("eolas-font")) {
const fl = document.createElement("link");
fl.id = "eolas-font";
fl.rel = "stylesheet";
fl.href = "https://fonts.googleapis.com/css2?family=Hanken+Grotesk:wght@400;500;600;700&family=Outfit:wght@300;400;500;600&display=swap";
document.head.appendChild(fl);
}
// ── Host element + shadow root (PRESERVED mount approach) ────────────────────
const host = document.createElement("div");
host.id = "eolas-bot-host";
// NOTE: `all:initial` MUST come first — it resets every property, so any
// positioning listed before it would be wiped (that caused the panel to
// open bottom-LEFT). Position/anchor are applied AFTER the reset.
host.style.cssText = [
"all:initial",
"position:fixed",
"right:24px",
"bottom:24px",
"left:auto",
"top:auto",
"width:auto",
"height:auto",
"margin:0",
"z-index:2147483647",
].join(";");
document.body.appendChild(host);
const shadow = host.attachShadow({ mode: "open" });
// ── Styles ───────────────────────────────────────────────────────────────
const style = document.createElement("style");
style.textContent = `
:host {
--navy: #131A2E;
--navy-soft: #232c46;
--ink: #1B2138;
--muted: #6A7088;
--paper: #ffffff;
--paper-2: #F6F6FA;
--line: #E8E8F0;
--link: #4A3E8E;
--grad: linear-gradient(96deg, #FCE0C8 0%, #F4B7C9 46%, #C8B5E8 100%);
--grad-strong: linear-gradient(96deg, #FAD2B0 0%, #EFA0B8 46%, #B69CE2 100%);
font-family: "Hanken Grotesk", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
:host, * { box-sizing: border-box; }
button { font-family: inherit; }
@keyframes eolas-pop { 0%{ opacity:0; transform: translateY(14px) scale(.96);} 100%{ opacity:1; transform: translateY(0) scale(1);} }
@keyframes eolas-msg-in { 0%{ opacity:0; transform: translateY(8px);} 100%{ opacity:1; transform:none;} }
@keyframes eolas-nudge-in { 0%{ opacity:0; transform: translateY(10px) scale(.95);} 100%{ opacity:1; transform:none;} }
@keyframes eolas-dot { 0%,80%,100%{ transform: translateY(0); opacity:.4;} 40%{ transform: translateY(-4px); opacity:1;} }
@keyframes eolas-ring { 0%{ transform: rotate(0);} 100%{ transform: rotate(360deg);} }
/* ── Launcher bubble ────────────────────────────────────────────── */
.launcher {
display: flex; align-items: center; gap: 10px;
justify-content: flex-end;
}
.bubble {
position: relative;
width: 62px; height: 62px; border-radius: 50%;
padding: 2px; border: 0; cursor: pointer;
background: var(--grad);
box-shadow: 0 10px 30px rgba(19,26,46,0.30);
transition: transform .16s ease, box-shadow .16s ease;
}
.bubble:hover { transform: translateY(-2px) scale(1.04); box-shadow: 0 16px 38px rgba(19,26,46,0.36); }
.bubble:focus-visible { outline: 3px solid #C8B5E8; outline-offset: 3px; }
.bubble .inner {
width: 100%; height: 100%; border-radius: 50%;
background: var(--navy); color: #fff;
display: flex; align-items: center; justify-content: center;
}
.bubble .inner svg { width: 27px; height: 27px; }
.nudge {
position: relative;
max-width: 230px; background: #fff; color: var(--ink);
border: 1px solid var(--line);
border-radius: 14px; padding: 11px 30px 11px 14px;
font-size: 13.5px; line-height: 1.4; font-weight: 500;
box-shadow: 0 10px 28px rgba(19,26,46,0.16);
animation: eolas-nudge-in .35s ease both;
}
.nudge b { font-weight: 700; }
.nudge::after {
content: ""; position: absolute; right: -6px; bottom: 18px;
width: 12px; height: 12px; background: #fff;
border-right: 1px solid var(--line); border-bottom: 1px solid var(--line);
transform: rotate(-45deg);
}
.nudge .x {
position: absolute; top: 6px; right: 6px;
width: 20px; height: 20px; border: 0; background: transparent;
color: var(--muted); cursor: pointer; border-radius: 6px;
display: flex; align-items: center; justify-content: center;
}
.nudge .x:hover { background: var(--paper-2); color: var(--ink); }
.hidden { display: none !important; }
/* ── Panel ──────────────────────────────────────────────────────── */
.panel {
width: 392px; height: min(620px, calc(100vh - 48px));
background: var(--paper);
border-radius: 22px; overflow: hidden;
box-shadow: 0 24px 70px rgba(19,26,46,0.30), 0 2px 8px rgba(19,26,46,0.10);
display: none; flex-direction: column;
animation: eolas-pop .26s cubic-bezier(.2,.8,.25,1) both;
transform-origin: bottom right;
}
.panel.open { display: flex; }
.header {
position: relative; background: var(--grad);
padding: 16px 16px 16px 16px;
display: flex; align-items: center; gap: 11px;
}
.header .avatar {
width: 38px; height: 38px; border-radius: 50%;
background: var(--navy); color: #fff; flex: none;
display: flex; align-items: center; justify-content: center;
box-shadow: 0 2px 8px rgba(19,26,46,0.25);
}
.header .avatar svg { width: 20px; height: 20px; }
.header .htext { flex: 1; min-width: 0; }
.header .title { font-family: "Outfit", sans-serif; font-weight: 600; font-size: 18px; color: var(--navy); letter-spacing: .2px; }
.header .subtitle { font-size: 11.5px; color: rgba(19,26,46,.66); margin-top: 1px; font-weight: 500; }
.header .hbtn {
width: 32px; height: 32px; flex: none; border: 0; border-radius: 9px;
background: rgba(19,26,46,.10); color: var(--navy);
cursor: pointer; display: flex; align-items: center; justify-content: center;
transition: background .14s ease;
}
.header .hbtn:hover { background: rgba(19,26,46,.18); }
.header .hbtn:focus-visible { outline: 2px solid var(--navy); outline-offset: 2px; }
/* ── Messages ───────────────────────────────────────────────────── */
.messages {
flex: 1; overflow-y: auto; padding: 18px 16px 8px;
background: var(--paper-2);
display: flex; flex-direction: column; gap: 14px;
scroll-behavior: smooth;
}
.messages::-webkit-scrollbar { width: 8px; }
.messages::-webkit-scrollbar-thumb { background: #d7d7e2; border-radius: 8px; }
.row { display: flex; gap: 9px; align-items: flex-end; animation: eolas-msg-in .26s ease both; }
.row.user { flex-direction: row-reverse; }
.row .mini {
width: 28px; height: 28px; flex: none; border-radius: 50%;
background: var(--navy); color: #fff;
display: flex; align-items: center; justify-content: center;
}
.row .mini svg { width: 15px; height: 15px; }
.row.user .mini { display: none; }
.stack { max-width: 80%; display: flex; flex-direction: column; }
.row.user .stack { align-items: flex-end; }
.text {
padding: 11px 13px; border-radius: 15px;
white-space: pre-wrap; word-wrap: break-word;
font-size: 14.5px; line-height: 1.5;
}
.row.bot .text { background: #fff; color: var(--ink); border: 1px solid var(--line); border-bottom-left-radius: 5px; }
.row.user .text { background: var(--navy); color: #fff; border-bottom-right-radius: 5px; }
.row.bot.placeholder .text { color: var(--muted); }
.dots { display: inline-flex; gap: 4px; padding: 4px 2px; }
.dots span { width: 7px; height: 7px; border-radius: 50%; background: var(--muted); animation: eolas-dot 1.2s infinite ease-in-out; }
.dots span:nth-child(2){ animation-delay: .16s; }
.dots span:nth-child(3){ animation-delay: .32s; }
.sources {
margin-top: 8px; font-size: 12.5px;
background: #fff; border: 1px solid var(--line);
border-radius: 12px; padding: 10px 12px;
}
.sources .label {
font-weight: 700; color: var(--ink); margin-bottom: 6px;
font-size: 11px; letter-spacing: .6px; text-transform: uppercase;
display: flex; align-items: center; gap: 6px;
}
.sources .label::before { content:""; width: 14px; height: 14px; border-radius: 4px; background: var(--grad); flex:none; }
.sources ul { margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; gap: 5px; }
.sources a {
color: var(--link); text-decoration: none; font-weight: 600;
display: inline-flex; align-items: center; gap: 5px;
}
.sources a:hover { text-decoration: underline; }
.sources a svg { width: 12px; height: 12px; opacity: .8; }
.sources li { padding: 4px 6px; margin: -4px -6px; border-radius: 8px; transition: background .25s ease; }
.sources li.hl { background: #faf3e7; }
.cite {
display: inline-block; min-width: 18px; padding: 0 5px;
font-size: 11px; font-weight: 700; line-height: 16px; text-align: center;
color: var(--link); background: #f1eefb; border-radius: 6px;
text-decoration: none; vertical-align: 1px; margin: 0 1px;
transition: background .12s ease, color .12s ease;
}
.cite:hover { background: var(--link); color: #fff; }
.cite:focus-visible { outline: 2px solid var(--link); outline-offset: 1px; }
.feedback { display: flex; align-items: center; gap: 6px; margin-top: 9px; padding-left: 2px; }
.feedback .fq { font-size: 11.5px; color: var(--muted); margin-right: 2px; }
.feedback button {
width: 28px; height: 28px; border: 1px solid var(--line); background: #fff;
border-radius: 8px; cursor: pointer; color: var(--muted);
display: flex; align-items: center; justify-content: center;
transition: all .14s ease;
}
.feedback button:hover { border-color: #c9b5e8; color: var(--ink); background: #faf7fd; }
.feedback button.sel { border-color: var(--navy); color: var(--navy); background: #f1eefb; }
.feedback button svg { width: 15px; height: 15px; }
.feedback .thanks { font-size: 11.5px; color: var(--muted); }
/* ── Suggested chips ────────────────────────────────────────────── */
.chips { display: flex; flex-wrap: wrap; gap: 8px; padding: 2px 2px 4px 37px; }
.chips.gone { display: none; }
.chip {
border: 1px solid var(--line); background: #fff; color: var(--ink);
border-radius: 999px; padding: 8px 13px; font-size: 13px; font-weight: 600;
cursor: pointer; transition: all .14s ease; line-height: 1;
}
.chip:hover { border-color: #c9b5e8; background: #faf7fd; transform: translateY(-1px); }
.chip:focus-visible { outline: 2px solid #c9b5e8; outline-offset: 2px; }
/* ── Composer ───────────────────────────────────────────────────── */
.composer {
border-top: 1px solid var(--line);
padding: 12px; display: flex; gap: 9px; align-items: flex-end;
background: #fff;
}
.composer textarea {
flex: 1; resize: none; border: 1px solid var(--line);
border-radius: 13px; padding: 11px 13px;
font-family: inherit; font-size: 14.5px; line-height: 1.4; color: var(--ink);
outline: none; height: 44px; max-height: 110px; background: var(--paper-2);
transition: border-color .14s ease, background .14s ease;
}
.composer textarea::placeholder { color: #9aa0b4; }
.composer textarea:focus { border-color: #c9b5e8; background: #fff; }
.composer .send {
width: 44px; height: 44px; flex: none; border: 0; border-radius: 13px;
background: var(--navy); color: #fff; cursor: pointer;
display: flex; align-items: center; justify-content: center;
transition: transform .12s ease, background .14s ease, opacity .14s ease;
}
.composer .send:hover:not(:disabled) { background: var(--navy-soft); transform: translateY(-1px); }
.composer .send:focus-visible { outline: 2px solid #c9b5e8; outline-offset: 2px; }
.composer .send:disabled { background: #c2c6d4; cursor: not-allowed; }
.composer .send svg { width: 19px; height: 19px; }
.disclaimer {
font-size: 10.5px; color: var(--muted); padding: 0 14px 11px; text-align: center;
background: #fff; line-height: 1.4;
}
.disclaimer a { color: var(--link); }
/* ── Mobile full-screen ─────────────────────────────────────────── */
@media (max-width: 480px) {
.panel.open {
position: fixed; inset: 0;
width: 100vw; height: 100vh; height: 100dvh;
border-radius: 0; animation: none;
}
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { animation-duration: .001ms !important; transition-duration: .001ms !important; }
}
`;
shadow.appendChild(style);
// ── Icons ───────────────────────────────────────────────────────────────
const SPARK = '<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 2.2l1.9 6.4 6.4 1.9-6.4 1.9L12 18.8l-1.9-6.4L3.7 10.5l6.4-1.9z"/></svg>';
const CHAT_SPARK = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 11.5a8.4 8.4 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.4 8.4 0 0 1-3.8-.9L3 21l1.9-5.7a8.4 8.4 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.4 8.4 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8z"/><path d="M12 8.5l.7 2.3 2.3.7-2.3.7-.7 2.3-.7-2.3L9 11.5l2.3-.7z" fill="currentColor" stroke="none"/></svg>';
// ── Markup ──────────────────────────────────────────────────────────────
const wrap = document.createElement("div");
wrap.innerHTML = `
<div class="launcher">
<div class="nudge" role="status">
<button class="x" aria-label="Dismiss">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
</button>
Hi, I'm <b>Eolas</b> — ask me anything about Screen Ireland funding, filming or skills.
</div>
<button class="bubble" aria-label="Open Eolas, the Screen Ireland assistant">
<span class="inner">${CHAT_SPARK}</span>
</button>
</div>
<section class="panel" role="dialog" aria-modal="true" aria-label="Eolas — Screen Ireland assistant">
<header class="header">
<div class="avatar">${SPARK}</div>
<div class="htext">
<div class="title">Eolas</div>
<div class="subtitle">Screen Ireland assistant · cites every source</div>
</div>
<button class="hbtn close" aria-label="Close assistant">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
</button>
</header>
<div class="messages" aria-live="polite" aria-label="Conversation"></div>
<div class="chips" role="group" aria-label="Suggested questions"></div>
<form class="composer">
<textarea placeholder="Ask about funding, filming, skills…" rows="1" maxlength="500" aria-label="Type your question"></textarea>
<button type="submit" class="send" aria-label="Send message">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
</button>
</form>
<div class="disclaimer">
Answers are sourced from screenireland.ie. Always verify funding amounts and deadlines on the linked page.
</div>
</section>
`;
shadow.appendChild(wrap);
// ── Refs ────────────────────────────────────────────────────────────────
const launcher = shadow.querySelector(".launcher");
const bubble = shadow.querySelector(".bubble");
const nudge = shadow.querySelector(".nudge");
const nudgeX = shadow.querySelector(".nudge .x");
const panel = shadow.querySelector(".panel");
const closeBtn= shadow.querySelector(".close");
const messages= shadow.querySelector(".messages");
const chipsBox= shadow.querySelector(".chips");
const form = shadow.querySelector(".composer");
const ta = shadow.querySelector("textarea");
const sendBtn = shadow.querySelector(".send");
const STARTERS = [
"Development funding limit?",
"How does Section 481 work?",
"Find filming locations",
"Skills & training courses",
];
// ── Open / close (focus-managed) ────────────────────────────────────────
let lastFocus = null;
function open() {
lastFocus = document.activeElement;
dismissNudge();
panel.classList.add("open");
bubble.parentElement.classList.add("hidden");
setTimeout(() => ta.focus(), 60);
}
function shut() {
panel.classList.remove("open");
bubble.parentElement.classList.remove("hidden");
if (lastFocus && lastFocus.focus) lastFocus.focus(); else bubble.focus();
}
function dismissNudge() {
nudge.classList.add("hidden");
try { sessionStorage.setItem("eolas_nudge_dismissed", "1"); } catch (e) {}
}
// ── Message rendering ───────────────────────────────────────────────────
function addMessage(role, text, opts = {}) {
const row = document.createElement("div");
row.className = "row " + role + (opts.placeholder ? " placeholder" : "");
if (role === "bot") {
const mini = document.createElement("div");
mini.className = "mini";
mini.innerHTML = SPARK;
row.appendChild(mini);
}
const stack = document.createElement("div");
stack.className = "stack";
const inner = document.createElement("div");
inner.className = "text";
if (opts.typing) {
inner.innerHTML = '<span class="dots"><span></span><span></span><span></span></span>';
} else {
inner.textContent = text;
}
stack.appendChild(inner);
row.appendChild(stack);
messages.appendChild(row);
scrollDown();
return { row, stack, inner };
}
function scrollDown() { messages.scrollTop = messages.scrollHeight; }
// Per-bot-message counter so anchor IDs don't collide across multiple Q&A turns.
let msgSeq = 0;
function escapeHtml(s) {
return s.replace(/[&<>"']/g, (c) => (
{ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]
));
}
// Convert "answer [1] and [2,3]" into HTML where every [N] becomes
// <a class="cite" href="#srcN"> — markers outside [1..sourceCount] are
// left as plain text.
function linkifyCitations(rawText, sourceCount, idPrefix) {
const safe = escapeHtml(rawText);
return safe.replace(/\[(\d+(?:\s*,\s*\d+)*)\]/g, (full, group) => {
const nums = group.split(",").map((n) => parseInt(n.trim(), 10))
.filter((n) => Number.isFinite(n) && n >= 1 && n <= sourceCount);
if (!nums.length) return full;
return nums.map((n) =>
`<a class="cite" data-cite="${n}" href="#${idPrefix}-${n}">[${n}]</a>`
).join("");
});
}
function renderSources(stack, sources, idPrefix) {
if (!sources || !sources.length) return;
const box = document.createElement("div");
box.className = "sources";
const label = document.createElement("div");
label.className = "label";
label.textContent = "Sources";
box.appendChild(label);
const ul = document.createElement("ul");
sources.forEach((s, i) => {
const li = document.createElement("li");
if (idPrefix) li.id = `${idPrefix}-${i + 1}`;
const a = document.createElement("a");
a.href = s.url; a.target = "_blank"; a.rel = "noopener noreferrer";
a.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 17L17 7M9 7h8v8"/></svg>';
const span = document.createElement("span");
span.textContent = `[${i + 1}] ` + s.title + (s.page ? ` (page ${s.page})` : "");
a.appendChild(span);
li.appendChild(a);
ul.appendChild(li);
});
box.appendChild(ul);
stack.appendChild(box);
scrollDown();
}
function renderFeedback(stack) {
const fb = document.createElement("div");
fb.className = "feedback";
const q = document.createElement("span");
q.className = "fq"; q.textContent = "Was this helpful?";
const up = document.createElement("button");
up.setAttribute("aria-label", "Helpful");
up.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M7 11v9H4a1 1 0 0 1-1-1v-7a1 1 0 0 1 1-1zM7 11l4-7a2 2 0 0 1 2 2v3h5a2 2 0 0 1 2 2.3l-1.2 6A2 2 0 0 1 16.8 20H7"/></svg>';
const down = document.createElement("button");
down.setAttribute("aria-label", "Not helpful");
down.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" style="transform:rotate(180deg)"><path d="M7 11v9H4a1 1 0 0 1-1-1v-7a1 1 0 0 1 1-1zM7 11l4-7a2 2 0 0 1 2 2v3h5a2 2 0 0 1 2 2.3l-1.2 6A2 2 0 0 1 16.8 20H7"/></svg>';
fb.appendChild(q); fb.appendChild(up); fb.appendChild(down);
function vote(val, btn) {
up.classList.remove("sel"); down.classList.remove("sel");
btn.classList.add("sel");
// HANDOFF: wire this to a backend feedback endpoint.
try { console.info("[Eolas] feedback:", val); } catch (e) {}
q.textContent = "Thanks for your feedback.";
}
up.addEventListener("click", () => vote("up", up));
down.addEventListener("click", () => vote("down", down));
stack.appendChild(fb);
scrollDown();
}
function renderChips() {
chipsBox.innerHTML = "";
chipsBox.classList.remove("gone");
for (const s of STARTERS) {
const c = document.createElement("button");
c.className = "chip"; c.type = "button"; c.textContent = s;
c.addEventListener("click", () => { submit(s); });
chipsBox.appendChild(c);
}
}
function hideChips() { chipsBox.classList.add("gone"); }
// ── SSE block parser (PRESERVED) ────────────────────────────────────────
function parseSseBlock(block) {
const lines = block.split("\n");
let event = "message";
const dataLines = [];
for (const line of lines) {
if (line.startsWith("event:")) event = line.slice(6).trim();
else if (line.startsWith("data:")) dataLines.push(line.slice(5).trim());
}
try { return { event, data: JSON.parse(dataLines.join("\n")) }; }
catch { return null; }
}
// ── Transport (PRESERVED: fetch + ReadableStream + SSE) ─────────────────
let inflight = false;
// Multi-turn memory: last N Q&A pairs, oldest first. Server is stateless —
// the widget is the only place this lives, so it resets on page reload
// (matches session-scoped conversation, no server-side session store).
const HISTORY_MAX_TURNS = 2;
let history = [];
async function ask(question) {
if (inflight) return;
inflight = true;
sendBtn.disabled = true;
hideChips();
addMessage("user", question);
const botMsg = addMessage("bot", "", { placeholder: true, typing: true });
let receivedAny = false;
let rawAnswer = "";
const idPrefix = `eolas-src-${++msgSeq}`;
// Shared handlers used by BOTH the real stream and the demo mock.
const onToken = (delta) => {
if (!receivedAny) {
botMsg.row.classList.remove("placeholder");
botMsg.inner.textContent = "";
receivedAny = true;
}
rawAnswer += (delta || "");
botMsg.inner.textContent = rawAnswer; // plain text while streaming
scrollDown();
};
const onSources = (list) => {
// Once sources arrive, re-render the bot text as HTML with clickable [N] markers.
if (list && list.length && rawAnswer) {
botMsg.inner.innerHTML = linkifyCitations(rawAnswer, list.length, idPrefix);
}
renderSources(botMsg.stack, list, idPrefix);
};
const onDone = () => { if (receivedAny) renderFeedback(botMsg.stack); };
// Citation click → scroll the matching source into view and briefly highlight it.
botMsg.inner.addEventListener("click", (e) => {
const a = e.target.closest("a.cite");
if (!a) return;
e.preventDefault();
const n = a.getAttribute("data-cite");
const target = botMsg.stack.querySelector(`#${idPrefix}-${n}`);
if (!target) return;
target.scrollIntoView({ behavior: "smooth", block: "nearest" });
target.classList.add("hl");
setTimeout(() => target.classList.remove("hl"), 1400);
});
// ── DEMO MOCK (remove for production) ──────────────────────────────
if (DEMO && !window.SCREENIRELAND_BOT_API) {
await mockAnswer(question, { onToken, onSources, onDone });
inflight = false; sendBtn.disabled = false;
return;
}
try {
const resp = await fetch(apiBase + "/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ question, history }),
});
if (!resp.ok || !resp.body) throw new Error("HTTP " + resp.status);
const reader = resp.body.getReader();
const decoder = new TextDecoder();
let buf = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true }).replace(/\r\n/g, "\n");
let idx;
while ((idx = buf.indexOf("\n\n")) >= 0) {
const block = buf.slice(0, idx);
buf = buf.slice(idx + 2);
if (!block.trim()) continue;
const evt = parseSseBlock(block);
if (!evt) continue;
if (evt.event === "token") onToken(evt.data.delta);
else if (evt.event === "sources") onSources(evt.data.sources || []);
else if (evt.event === "done") onDone();
}
}
if (receivedAny && !botMsg.stack.querySelector(".feedback")) onDone();
// Record this turn for follow-up context. Real backend answers only —
// errored/empty turns aren't remembered (nothing useful to condense from).
if (receivedAny && rawAnswer) {
history.push({ q: question, a: rawAnswer });
if (history.length > HISTORY_MAX_TURNS) history = history.slice(-HISTORY_MAX_TURNS);
}
} catch (e) {
botMsg.row.classList.remove("placeholder");
botMsg.inner.textContent = "Sorry — the assistant is temporarily unavailable. Please try again in a moment.";
} finally {
inflight = false;
sendBtn.disabled = false;
}
}
// ════════════════════════════════════════════════════════════════════════
// DEMO MOCK — streams a canned, grounded-looking answer so the standalone
// demo is alive without a backend. DELETE this whole block for production.
// ════════════════════════════════════════════════════════════════════════
function mockAnswer(question, h) {
const q = question.toLowerCase();
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const OFF_TOPIC = /(weather|football|stock|recipe|capital of|bitcoin|joke|score)/;
let answer, sources = [];
if (OFF_TOPIC.test(q)) {
answer = "I don't have that in Screen Ireland's published material, so I can't answer it reliably. You can browse the site, or contact the team at info@screenireland.ie and they'll point you in the right direction.";
sources = [{ title: "Contact Screen Ireland", url: "https://www.screenireland.ie/about/contact-us" }];
} else if (/(481|tax|credit)/.test(q)) {
answer = "Section 481 is Ireland's film and television tax credit. It offers relief on eligible Irish production expenditure and is administered through Revenue rather than by Screen Ireland directly. Screen Ireland's site outlines how it sits alongside their funding. Rates and caps can change, so please verify the current figures on the linked page.";
sources = [{ title: "Section 481 — Film & TV tax credit", url: "https://www.screenireland.ie/filming/incentives" }];
} else if (/(fund|loan|grant|develop|money|amount|limit)/.test(q)) {
answer = "Screen Ireland development funding is generally offered as a repayable loan toward writing, research and packaging. Awards above a set threshold are subject to additional regulations and limits laid out in the funding guidelines, and exact amounts depend on the scheme and project stage. As these limits can change, always confirm the current figure on the linked guidelines page.";
sources = [{ title: "Funding — Regulations and Limits", url: "https://www.screenireland.ie/funding" }];
} else if (/(film|location|shoot|where|region)/.test(q)) {
answer = "Screen Ireland's filming resources help you scout locations across Ireland and connect with regional film offices, along with guidance on permits and crew. The locations section is the best starting point for planning a shoot.";
sources = [{ title: "Filming in Ireland — Locations", url: "https://www.screenireland.ie/filming" }];
} else if (/(skill|course|train|talent|career|learn)/.test(q)) {
answer = "Screen Ireland's Skills programmes support training and professional development across writing, directing, producing and crew roles. Availability and application deadlines vary by programme, so check the Skills section for what's currently open.";
sources = [{ title: "Skills & Talent Development", url: "https://www.screenireland.ie/skills" }];
} else {
answer = "I can help with questions about Screen Ireland — funding, filming in Ireland, skills and training, festivals, and industry programmes. Could you tell me a little more about what you're looking for?";
sources = [];
}
return (async () => {
await sleep(650); // simulate retrieval + relevance gate
const words = answer.split(" ");
for (let i = 0; i < words.length; i++) {
h.onToken(words[i] + (i < words.length - 1 ? " " : ""));
await sleep(22 + Math.random() * 30);
}
if (sources.length) { await sleep(220); h.onSources(sources); }
await sleep(180);
h.onDone();
})();
}
// ════════════════════════════════════════════════════════════════════════
// ── Submit ──────────────────────────────────────────────────────────────
function submit(text) {
const q = (text != null ? text : ta.value || "").trim();
if (!q) return;
ta.value = "";
ta.style.height = "44px";
ask(q);
}
// ── Events ──────────────────────────────────────────────────────────────
bubble.addEventListener("click", open);
closeBtn.addEventListener("click", shut);
nudgeX.addEventListener("click", (e) => { e.stopPropagation(); dismissNudge(); });
nudge.addEventListener("click", open);
ta.addEventListener("input", () => {
ta.style.height = "44px";
ta.style.height = Math.min(ta.scrollHeight, 110) + "px";
});
ta.addEventListener("keydown", (e) => {
if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); form.requestSubmit(); }
});
form.addEventListener("submit", (e) => { e.preventDefault(); submit(); });
// Esc closes; basic focus trap inside the open panel.
shadow.addEventListener("keydown", (e) => {
if (e.key === "Escape" && panel.classList.contains("open")) { shut(); return; }
if (e.key === "Tab" && panel.classList.contains("open")) {
const f = panel.querySelectorAll('a[href], button:not([disabled]), textarea');
if (!f.length) return;
const first = f[0], last = f[f.length - 1];
if (e.shiftKey && shadow.activeElement === first) { e.preventDefault(); last.focus(); }
else if (!e.shiftKey && shadow.activeElement === last) { e.preventDefault(); first.focus(); }
}
});
// ── Boot ────────────────────────────────────────────────────────────────
addMessage("bot",
"Hello, I'm Eolas. Ask me anything about Screen Ireland — funding, filming, skills or programmes. I only answer from the published Screen Ireland website, and I cite every source."
);
renderChips();
// Subtle open nudge (once per session).
let nudgeDismissed = false;
try { nudgeDismissed = sessionStorage.getItem("eolas_nudge_dismissed") === "1"; } catch (e) {}
if (nudgeDismissed) {
nudge.classList.add("hidden");
} else {
nudge.classList.add("hidden");
setTimeout(() => {
if (!panel.classList.contains("open")) nudge.classList.remove("hidden");
}, 1400);
}
})();
|