11 Commits

Author SHA1 Message Date
claude 36759d8fee refactor: Add strategic comments to organize CSS (Step 5 of 6)
Build and Push Docker Images Staging / build (push) Successful in 4m41s
Added inline comments throughout myai.css to:
- Clarify complex CSS selectors (input:not selectors, specificity explanations)
- Explain design patterns (.is-invalid error state pattern)
- Document focus and error states
- Describe layout decisions (sticky result panel, hamburger dropdown)
- Clarify responsive breakpoints and what changes at each
- Explain the relationship between CSS and JS (e.g., .is-open, .is-invalid)

Comments are strategic and concise—added to complex/non-obvious sections
without bloating the file. All CSS rules remain unchanged—purely additive
documentation.

Key sections now have better context:
- Form field selectors and state handling
- Hamburger menu responsive behavior
- Result panel sticky positioning strategy
- Responsive grid layout changes at 900px and 560px
- Cookie banner and loader overlay behavior

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-05-29 09:15:20 +03:00
claude d0bba19a17 refactor: Refactor legal.js with improved comments (Step 4 of 6)
Refactored legal.js from 135 → 124 lines (8% reduction) by:
- Removing local browserLang() and getLang() that are now in utils
- Simplifying to focus on page-specific injection logic

Kept legal page-specific functionality:
- Local LANG_KEY storage for page language preference
- injectTopbar() with language switcher buttons
- injectFooter() with language-aware copyright and legal links
- Event delegation for language link clicks
- DOMContentLoaded handler

Added clear JSDoc comments explaining the injection pattern and
how legal pages dynamically reuse common UI elements while supporting
language switching via event delegation.

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-05-29 09:14:02 +03:00
claude 0742694900 refactor: Refactor cv-matcher.js to use shared utilities (Step 3 of 6)
Refactored cv-matcher.js from 257 → 213 lines (17% reduction) by:
- Removing duplicate helper functions now in utils/form-helpers.js
- Removing duplicate i18n logic now in utils/i18n.js
- Removing API loading code now in utils/api.js

Kept CV matcher-specific logic:
- CV file input change handler
- Async CV upload and match flow with two captcha tokens
- Match result rendering with score badge and lists
- escapeHtml() XSS prevention utility
- $(window).on('load') to load reCaptcha

All function calls updated to use window.MyAi.* utilities for consistency.
Added detailed JSDoc comments explaining the two-step async flow.

Updated cv-matcher/index.html to load all utilities before cv-matcher.js.

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-05-29 09:13:22 +03:00
claude ce05426452 refactor: Refactor main.js to use shared utilities (Step 2 of 6)
Refactored main.js from 544 → 266 lines (51% reduction) by:
- Removing duplicate functions now in utils/form-helpers.js
- Removing duplicate i18n logic now in utils/i18n.js
- Removing API loading code now in utils/api.js
- Removing cookie consent handlers now in modules/cookie-consent.js

Kept only page-specific form handlers:
- Contact form submission with reCaptcha
- Subscribe form submission with reCaptcha
- Language switcher initialization
- Footer year and version display

All calls now use window.MyAi.* utilities for consistency.

Updated index.html to load all utilities before main.js.

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-05-29 09:12:19 +03:00
claude 98979b58f8 refactor: Extract shared JavaScript utilities (Step 1 of 6)
Create reusable utility modules to eliminate duplication across main.js,
cv-matcher.js, and legal.js:

- js/utils/form-helpers.js: showFieldError, clearFieldErrors, isValidEmail,
  extractApiError — shared form validation and error handling
- js/utils/i18n.js: currentLang, t, applyLanguage, updateLegalLinks,
  browserLang — shared translation and language switching
- js/utils/api.js: checkApiLive, getRecaptchaWebKey, getGoogleTagManagerId,
  loadGoogleTagManager — shared API configuration loading
- js/modules/cookie-consent.js: getConsent, setConsent, initConsent,
  setupConsentHandlers — cookie banner and consent management

All utilities exposed on window.MyAi namespace for use by existing pages.
Full JSDoc headers and inline comments for maintainability.

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-05-29 09:05:51 +03:00
claude 57e8cb3f4b fix: Configure EF Core migration history tables with schema-qualified names
Each DbContext now explicitly configures its migration history table to use
the schema-qualified name pattern [schemaName].[_Migrations]:
- [cvMatcher].[_Migrations] for CvMatcherDbContext
- [emailApi].[_Migrations] for EmailApiDbContext
- [cvSearch].[_Migrations] for CvSearchDbContext
- [rag].[_Migrations] for RagDbContext
- [myAi].[_Migrations] for MyAiDbContext

This is done via OnConfiguring() with UseSqlServer().MigrationsHistoryTable(name, schema).

Removed incorrect rename migrations that were created due to misunderstanding
of the proper EF Core configuration approach.

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-05-29 08:37:23 +03:00
claude e7bb803ae2 fix: Standardize EF Core migrations table names for consistency
- Rename EmailApiDbContext MigrationTableName from '_EmailApiMigrations' to '_Migrations'
- Rename MyAiDbContext MigrationTableName from '_MyAiMigrations' to '_Migrations'
- Add migrations to rename tables in database: emailApi._EmailApiMigrations → emailApi._Migrations, myAi._MyAiMigrations → myAi._Migrations
- Aligns with naming convention used in other schemas (cvMatcher, cvSearch, rag)

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-05-28 18:26:39 +03:00
claude e8633ec52c Merge production branch into main: integrate production build updates 2026-05-28 18:05:46 +03:00
claude 270deaaef6 Production build
Build and Push Docker Images Production / build (push) Successful in 9s
2026-05-20 21:14:47 +03:00
claude 2d9f05cf33 Production build 2026-05-20 21:13:16 +03:00
claude 0829eba2b1 Production build 2026-05-20 21:12:58 +03:00
15 changed files with 610 additions and 453 deletions
@@ -16,6 +16,13 @@ public sealed class CvMatcherDbContext : DbContext
public DbSet<CvMatcherChatCacheEntity> CvMatcherChatCache => Set<CvMatcherChatCacheEntity>();
public DbSet<AiPromptEntity> AiPrompts => Set<AiPromptEntity>();
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
// Configure migration history table to use schema-qualified name: [cvMatcher].[_Migrations]
optionsBuilder.UseSqlServer(x => x.MigrationsHistoryTable(MigrationTableName, SchemaName));
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema(SchemaName);
@@ -14,6 +14,13 @@ public sealed class CvSearchDbContext : DbContext
public DbSet<JobSearchSessionEntity> JobSearchSessions => Set<JobSearchSessionEntity>();
public DbSet<JobSearchResultEntity> JobSearchResults => Set<JobSearchResultEntity>();
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
// Configure migration history table to use schema-qualified name: [cvSearch].[_Migrations]
optionsBuilder.UseSqlServer(x => x.MigrationsHistoryTable(MigrationTableName, SchemaName));
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema(SchemaName);
+8 -1
View File
@@ -6,12 +6,19 @@ namespace EmailApi.Data;
public sealed class EmailApiDbContext : DbContext
{
public const string SchemaName = "emailApi";
public const string MigrationTableName = "_EmailApiMigrations";
public const string MigrationTableName = "_Migrations";
public EmailApiDbContext(DbContextOptions<EmailApiDbContext> options) : base(options) { }
public DbSet<EmailTemplateEntity> EmailTemplates => Set<EmailTemplateEntity>();
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
// Configure migration history table to use schema-qualified name: [emailApi].[_Migrations]
optionsBuilder.UseSqlServer(x => x.MigrationsHistoryTable(MigrationTableName, SchemaName));
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema(SchemaName);
+8 -1
View File
@@ -6,12 +6,19 @@ namespace MyAi.Data;
public sealed class MyAiDbContext : DbContext
{
public const string SchemaName = "myAi";
public const string MigrationTableName = "_MyAiMigrations";
public const string MigrationTableName = "_Migrations";
public MyAiDbContext(DbContextOptions<MyAiDbContext> options) : base(options) { }
public DbSet<TemplateEntity> Templates => Set<TemplateEntity>();
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
// Configure migration history table to use schema-qualified name: [myAi].[_Migrations]
optionsBuilder.UseSqlServer(x => x.MigrationsHistoryTable(MigrationTableName, SchemaName));
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema(SchemaName);
+7
View File
@@ -17,6 +17,13 @@ public sealed class RagDbContext : DbContext
public DbSet<RagEmbeddingCacheEntity> RagEmbeddingCache => Set<RagEmbeddingCacheEntity>();
public DbSet<RagChatCompletionCacheEntity> RagChatCompletionCache => Set<RagChatCompletionCacheEntity>();
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
// Configure migration history table to use schema-qualified name: [rag].[_Migrations]
optionsBuilder.UseSqlServer(x => x.MigrationsHistoryTable(MigrationTableName, SchemaName));
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema(SchemaName);
+30 -6
View File
@@ -152,7 +152,7 @@ img {
color: #fff
}
/* Hamburger — hidden on desktop, shown via media query */
/* Hamburger menu button — hidden on desktop, shown in responsive via media query */
.menu-toggle {
display: none;
background: transparent;
@@ -160,6 +160,7 @@ img {
padding: 8px
}
/* Three horizontal lines that make up the hamburger icon */
.menu-toggle span {
display: block;
width: 24px;
@@ -168,7 +169,7 @@ img {
margin: 5px 0
}
/* Language selector */
/* Language selector (right side of header) */
.nav-actions {
display: flex;
align-items: center;
@@ -430,13 +431,15 @@ img {
margin-bottom: 18px
}
.ai-panel label span, .contact-form label span {
/* Label text styling */
.ai-panel label span, .contact-form label span {
display: block;
margin-bottom: 8px;
color: #c3d4f2;
font-weight: 700
}
/* Input fields: text, textarea, email. Excludes checkboxes and file inputs. */
.ai-panel input:not([type="checkbox"]):not([type="file"]),
.ai-panel textarea,
.contact-form input:not([type="checkbox"]):not([type="file"]),
@@ -455,6 +458,7 @@ img {
transition: border-color .15s ease, box-shadow .15s ease
}
/* Placeholder text color */
.ai-panel input:not([type="checkbox"]):not([type="file"])::placeholder,
.ai-panel textarea::placeholder,
.contact-form input:not([type="checkbox"]):not([type="file"])::placeholder,
@@ -463,6 +467,7 @@ img {
color: #97a4b8
}
/* Focus state: blue border and glow */
.ai-panel input:not([type="checkbox"]):not([type="file"]):focus,
.ai-panel textarea:focus,
.contact-form input:not([type="checkbox"]):not([type="file"]):focus,
@@ -472,6 +477,7 @@ img {
box-shadow: 0 0 0 3px rgba(95,160,255,.18)
}
/* Error state (is-invalid): red border and red glow when parent has .is-invalid class */
.ai-panel label.is-invalid input:not([type="checkbox"]):not([type="file"]),
.ai-panel label.is-invalid textarea,
.contact-form label.is-invalid input:not([type="checkbox"]):not([type="file"]),
@@ -498,6 +504,7 @@ img {
color: #ff8a8a
}
/* File upload drop zone */
.file-drop {
display: block;
border: 1px dashed rgba(143,184,255,.45);
@@ -507,6 +514,7 @@ img {
cursor: pointer
}
/* File drop zone error state */
.file-drop.is-invalid {
border-color: #ff8a8a;
background: rgba(255,138,138,.06)
@@ -544,12 +552,13 @@ img {
margin: 0
}
/* Result panel */
/* Match result panel — sticky positioning keeps it visible while scrolling the form */
.result-panel {
position: sticky;
top: 110px
}
/* Empty state message (before results generated) */
.empty-result {
color: var(--muted);
line-height: 1.8;
@@ -558,6 +567,7 @@ img {
background: rgba(0,0,0,.25)
}
/* Large circular match score percentage badge */
.score-badge {
display: inline-flex;
align-items: center;
@@ -571,6 +581,7 @@ img {
margin: 10px 0 20px
}
/* Bulleted lists for strengths, gaps, evidence */
.result-list {
padding-left: 18px;
color: #d7e3fb;
@@ -862,18 +873,20 @@ img {
/* ============================================================
RESPONSIVE — tablets and below (≤900px)
Changes: Single-column layouts, hamburger nav, adjusted spacing
============================================================ */
@media (max-width:900px) {
/* Single-column layouts */
/* All grids switch from multi-column to single column */
.hero-grid, .matcher-grid, .contact-grid, .demo-grid {
grid-template-columns: 1fr
}
/* Result panel no longer sticky on tablets (would interfere with form) */
.result-panel {
position: static
}
/* Nav becomes a dropdown */
/* Navigation becomes a hidden dropdown, shown on hamburger click via .is-open class */
.nav {
position: absolute;
top: 84px;
@@ -889,10 +902,12 @@ img {
z-index: 30
}
/* .is-open class added by JS on hamburger click */
.nav.is-open {
display: flex
}
/* Show hamburger button on tablets */
.menu-toggle {
display: block;
order: 4
@@ -906,11 +921,13 @@ img {
position: relative
}
/* Cookie banner stacks vertically on tablets */
.cookie-box {
align-items: flex-start;
flex-direction: column
}
/* Language flags get smaller */
.lang-switch {
padding: 4px
}
@@ -923,8 +940,10 @@ img {
/* ============================================================
RESPONSIVE — mobile (≤560px)
Changes: Reduced padding, smaller text, full-width buttons, hide subtitle
============================================================ */
@media (max-width:560px) {
/* Tighter padding on small screens */
.hero {
padding-top: 46px
}
@@ -933,16 +952,19 @@ img {
padding: 56px 0
}
/* Footer goes vertical on mobile */
.footer-wrap {
align-items: flex-start;
flex-direction: column
}
/* Action buttons take full width */
.hero-actions .btn {
width: 100%;
text-align: center
}
/* Brand logo smaller, subtitle hidden */
.brand-text {
font-size: 1.35rem
}
@@ -956,6 +978,7 @@ img {
height: 42px
}
/* Tighter gaps in nav and language selector */
.nav-actions {
gap: 6px
}
@@ -969,6 +992,7 @@ img {
height: 27px
}
/* Slightly smaller banner border radius on mobile */
.showcase-banner {
border-radius: 18px
}
+4
View File
@@ -221,6 +221,10 @@
<a href="#" id="cookieManage" class="cookie-manage btn btn-dark btn-sm shadow" data-i18n="cookies.settings">Cookie settings</a>
<script src="/js/vendor/jquery-4.0.0.min.js"></script>
<script src="/js/i18n.js"></script>
<script src="/js/utils/form-helpers.js"></script>
<script src="/js/utils/i18n.js"></script>
<script src="/js/utils/api.js"></script>
<script src="/js/modules/cookie-consent.js"></script>
<script src="/js/main.js"></script>
<script src="/js/cv-matcher.js"></script>
</body>
+4
View File
@@ -217,6 +217,10 @@
<a href="#" id="cookieManage" class="cookie-manage btn btn-dark btn-sm shadow" data-i18n="cookies.settings">Cookie settings</a>
<script src="/js/vendor/jquery-4.0.0.min.js"></script>
<script src="/js/i18n.js"></script>
<script src="/js/utils/form-helpers.js"></script>
<script src="/js/utils/i18n.js"></script>
<script src="/js/utils/api.js"></script>
<script src="/js/modules/cookie-consent.js"></script>
<script src="/js/main.js"></script>
</body>
</html>
+56 -99
View File
@@ -2,70 +2,32 @@
* MyAi CV Matcher Form
*
* Handles CV upload, job description input, and match result rendering.
* Depends on: jQuery, i18n.js, main.js (for shared utilities)
* Uses shared utilities from: utils/form-helpers.js, utils/i18n.js, utils/api.js
*
* Depends on: jQuery, i18n.js (translation dict), shared utility modules
*/
(function ($) {
"use strict";
var reCaptchaSiteKey = null;
var LANG_KEY = "myai_lang";
/**
* Retrieve translation by key.
* Falls back to English if key not found in current language.
*/
function t(key) {
var lang = localStorage.getItem(LANG_KEY) || 'en';
return (window.MyAi.i18n[lang] && window.MyAi.i18n[lang][key]) ||
window.MyAi.i18n.en[key] || key;
}
/**
* Get current language from localStorage or detect from browser.
*/
function currentLang() {
return localStorage.getItem(LANG_KEY) ||
(((navigator.language || navigator.userLanguage || 'en').toLowerCase().indexOf('ro') === 0) ? 'ro' : 'en');
}
/**
* Display field error message and mark container with is-invalid class.
*/
function showFieldError(errorId, msg) {
var $el = $('#' + errorId);
$el.text(msg || '');
var $parent = $el.parent();
var $container = $parent.is('label, .consent-inline') ? $parent : $el.prev();
if (!$container.length || !$container.is('label, .consent-inline, .file-drop, .subscribe-row')) {
$container = $el.closest('form');
}
$container.toggleClass('is-invalid', !!msg);
}
/**
* Clear multiple field errors at once.
*/
function clearFieldErrors(errorIds) {
for (var i = 0; i < errorIds.length; i++) showFieldError(errorIds[i], '');
}
/**
* Validate email format with simple regex.
*/
function isValidEmail(value) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(value || '').trim());
}
/* ============================================================
CV FILE INPUT HANDLER
============================================================ */
/**
* Update displayed CV filename when file is selected.
*/
$('#cvFile').on('change', function () {
var file = this.files && this.files[0];
$('#cvFileName').text(file ? file.name : t('cv.fileHint'));
$('#cvFileName').text(file ? file.name : window.MyAi.t('cv.fileHint'));
});
/* ============================================================
CV MATCHER FORM HANDLER
============================================================ */
/**
* Handle CV Matcher form submission.
* Handle CV Matcher form submission with async upload and match flow.
* Requires reCaptcha verification for both CV upload and match actions.
*/
$('#cvMatcherForm').on('submit', async function (event) {
event.preventDefault();
@@ -78,38 +40,39 @@
$button = $('#matchSubmit'),
$result = $('#matchResult');
clearFieldErrors(['cvFileError', 'cvJobError', 'cvConsentError']);
window.MyAi.clearFieldErrors(['cvFileError', 'cvJobError', 'cvConsentError']);
$msg.removeClass().addClass('form-message').text('');
// Validate inputs
var hasError = false;
if (!file) { showFieldError('cvFileError', t('cv.noFile')); hasError = true; }
if (!jobUrl && !jobDescription) { showFieldError('cvJobError', t('cv.noJob')); hasError = true; }
if (!consent) { showFieldError('cvConsentError', t('cv.noConsent')); hasError = true; }
if (!file) { window.MyAi.showFieldError('cvFileError', window.MyAi.t('cv.noFile')); hasError = true; }
if (!jobUrl && !jobDescription) { window.MyAi.showFieldError('cvJobError', window.MyAi.t('cv.noJob')); hasError = true; }
if (!consent) { window.MyAi.showFieldError('cvConsentError', window.MyAi.t('cv.noConsent')); hasError = true; }
if (hasError) return;
var $cvLoader = $('#cvLoader');
$button.prop('disabled', true).text(t('cv.processing'));
$msg.removeClass().addClass('form-message').text(t('cv.extracting'));
$result.html('<div class="empty-result">' + escapeHtml(t('cv.processingLong')) + '</div>');
$button.prop('disabled', true).text(window.MyAi.t('cv.processing'));
$msg.removeClass().addClass('form-message').text(window.MyAi.t('cv.extracting'));
$result.html('<div class="empty-result">' + escapeHtml(window.MyAi.t('cv.processingLong')) + '</div>');
$cvLoader.addClass('loader-visible');
// Require reCaptcha and get CV upload token
if (window.grecaptcha && reCaptchaSiteKey) {
if (window.grecaptcha && window.MyAi.getReCaptchaSiteKey()) {
grecaptcha.ready(function () {
grecaptcha.execute(reCaptchaSiteKey, {
grecaptcha.execute(window.MyAi.getReCaptchaSiteKey(), {
action: 'cv_upload'
}).then(postCv);
});
} else {
$cvLoader.removeClass('loader-visible');
$msg.removeClass().addClass('form-message text-danger').text(t('form.captchaFailed'));
$button.prop('disabled', false).text(t('cv.submit'));
$msg.removeClass().addClass('form-message text-danger').text(window.MyAi.t('form.captchaFailed'));
$button.prop('disabled', false).text(window.MyAi.t('cv.submit'));
return;
}
/**
* Upload CV and request match score.
* Two-step process: upload CV PDF, then submit match request with fresh captcha token.
*/
async function postCv(token) {
try {
@@ -125,18 +88,18 @@
if (!cvResponse.ok) {
var cvErrBody = null;
try { cvErrBody = await cvResponse.json(); } catch (_) {}
throw new Error(extractApiError(cvErrBody, cvResponse.status, 'cv.cvFailed', 'cv.rateLimited'));
throw new Error(window.MyAi.extractApiError(cvErrBody, cvResponse.status, 'cv.cvFailed', 'cv.rateLimited'));
}
var cvData = await cvResponse.json();
// Get fresh captcha token for match action
if (!(window.grecaptcha && reCaptchaSiteKey)) {
throw new Error(t('form.captchaFailed'));
if (!(window.grecaptcha && window.MyAi.getReCaptchaSiteKey())) {
throw new Error(window.MyAi.t('form.captchaFailed'));
}
var matchToken = await new Promise(function (resolve, reject) {
try {
grecaptcha.ready(function () {
grecaptcha.execute(reCaptchaSiteKey, { action: 'match_job' }).then(resolve).catch(reject);
grecaptcha.execute(window.MyAi.getReCaptchaSiteKey(), { action: 'match_job' }).then(resolve).catch(reject);
});
} catch (e) { reject(e); }
});
@@ -154,36 +117,41 @@
email: matchEmail,
gdprConsent: consent,
captchaToken: matchToken,
language: currentLang()
language: window.MyAi.currentLang()
})
});
if (!matchResponse.ok) {
var matchErrBody = null;
try { matchErrBody = await matchResponse.json(); } catch (_) {}
throw new Error(extractApiError(matchErrBody, matchResponse.status, 'cv.matchFailed', 'cv.rateLimited'));
throw new Error(window.MyAi.extractApiError(matchErrBody, matchResponse.status, 'cv.matchFailed', 'cv.rateLimited'));
}
var match = await matchResponse.json();
renderMatchResult(match);
$msg.removeClass().addClass('form-message text-success').text(t('cv.completed'));
$msg.removeClass().addClass('form-message text-success').text(window.MyAi.t('cv.completed'));
} catch (err) {
console.error(err);
var isRateLimited = err && err.message === t('cv.rateLimited');
var isRateLimited = err && err.message === window.MyAi.t('cv.rateLimited');
var tone = isRateLimited ? 'text-warning' : 'text-danger';
$msg.removeClass().addClass('form-message ' + tone).text(err.message || t('cv.matchFailed'));
$result.html('<div class="empty-result">' + escapeHtml(isRateLimited ? t('cv.rateLimited') : t('cv.backendMissing')) + '</div>');
$msg.removeClass().addClass('form-message ' + tone).text(err.message || window.MyAi.t('cv.matchFailed'));
$result.html('<div class="empty-result">' + escapeHtml(isRateLimited ? window.MyAi.t('cv.rateLimited') : window.MyAi.t('cv.backendMissing')) + '</div>');
} finally {
$cvLoader.removeClass('loader-visible');
$button.prop('disabled', false).text(t('cv.submit'));
$button.prop('disabled', false).text(window.MyAi.t('cv.submit'));
}
}
});
/* ============================================================
MATCH RESULT RENDERING
============================================================ */
/**
* Render CV match result into #matchResult panel.
* Displays match score percentage, summary, strengths, gaps, and evidence excerpts.
*/
function renderMatchResult(match) {
var score = match.score || match.matchScore || 0;
var summary = match.summary || t('cv.noSummary');
var summary = match.summary || window.MyAi.t('cv.noSummary');
var strengths = match.strengths || [];
var gaps = match.gaps || match.missingSkills || [];
var evidence = match.evidence || match.retrievedChunks || [];
@@ -193,7 +161,7 @@
*/
function list(items) {
if (!items || !items.length) {
return '<p class="empty-result">' + escapeHtml(t('cv.noItems')) + '</p>';
return '<p class="empty-result">' + escapeHtml(window.MyAi.t('cv.noItems')) + '</p>';
}
return '<ul class="result-list">' + items.map(function (x) {
var text = typeof x === 'string' ? x : (x.text || x.title || JSON.stringify(x));
@@ -204,14 +172,19 @@
$('#matchResult').html(
'<div class="score-badge">' + Number(score).toFixed(0) + '%</div>' +
'<p>' + escapeHtml(summary) + '</p>' +
'<h3>' + t('cv.strengths') + '</h3>' + list(strengths) +
'<h3>' + t('cv.gaps') + '</h3>' + list(gaps) +
'<h3>' + t('cv.evidence') + '</h3>' + list(evidence)
'<h3>' + window.MyAi.t('cv.strengths') + '</h3>' + list(strengths) +
'<h3>' + window.MyAi.t('cv.gaps') + '</h3>' + list(gaps) +
'<h3>' + window.MyAi.t('cv.evidence') + '</h3>' + list(evidence)
);
}
/* ============================================================
UTILITY FUNCTIONS
============================================================ */
/**
* Escape HTML special characters to prevent XSS.
* Replaces &, <, >, ", ' with their HTML entity equivalents.
*/
function escapeHtml(value) {
return String(value).replace(/[&<>'"]/g, function (char) {
@@ -225,32 +198,16 @@
});
}
/**
* Extract user-facing error message from failed API response.
* For 4xx: show server's error field (intentional user feedback).
* For 5xx or missing body: show generic i18n fallback.
*/
function extractApiError(body, status, fallbackKey, rateLimitKey) {
if (status === 429) return t(rateLimitKey || 'form.rateLimited');
var msg = body && (body.error || body.Error || body.title);
return (status >= 400 && status < 500 && msg) ? msg : t(fallbackKey);
}
/* ============================================================
API CONFIGURATION LOADING (from utils/api.js)
============================================================ */
/**
* Load reCaptcha site key on page load (needed for CV upload).
* Uses shared utility: window.MyAi.getRecaptchaWebKey()
*/
$(window).on('load', function () {
$.get('/api/captcha').done(function (res) {
reCaptchaSiteKey = res;
if (reCaptchaSiteKey && !window.__recaptcha_loaded) {
window.__recaptcha_loaded = true;
var script = document.createElement('script');
script.setAttribute('src', 'https://www.google.com/recaptcha/api.js?render=' + reCaptchaSiteKey);
document.head.appendChild(script);
}
}).fail(function () {
console.warn('Could not load reCaptcha site key from /api/captcha');
});
window.MyAi.getRecaptchaWebKey();
});
})(jQuery);
+45 -322
View File
@@ -1,94 +1,14 @@
/**
* MyAi Main Application Logic
*
* Core responsibilities:
* - i18n initialization and language switching
* - Header/nav behavior
* - Cookie consent management
* - Contact and subscribe forms (with reCaptcha)
* - API health checks and configuration loading
* Page-specific form handlers for contact and subscribe forms.
* Uses shared utilities from: i18n.js, utils/form-helpers.js, utils/api.js, modules/cookie-consent.js
*
* Depends on: jQuery, i18n.js (translation dict)
* Shared utilities exposed on window.MyAi for use by other scripts.
* Depends on: jQuery, i18n.js (translation dict), shared utility modules
*/
(function ($) {
"use strict";
/* ============================================================
INITIALIZATION & STATE
============================================================ */
var reCaptchaSiteKey = null;
var gTagManagerId = null;
var CONSENT_KEY = "myai_cookie_consent";
var LANG_KEY = "myai_lang";
window.MyAi = window.MyAi || {};
/* ============================================================
TRANSLATION HELPERS
============================================================ */
/**
* Get current language preference from localStorage or browser detection.
* Defaults to English.
*/
function browserLang() {
return ((navigator.language || navigator.userLanguage || 'en').toLowerCase().indexOf('ro') === 0) ? 'ro' : 'en';
}
/**
* Get the active language (localStorage takes precedence).
*/
function currentLang() {
return localStorage.getItem(LANG_KEY) || browserLang();
}
/**
* Translate a key into the current language.
* Falls back to English if key not found in the current language.
*/
function t(key) {
var lang = currentLang();
return (window.MyAi.i18n[lang] && window.MyAi.i18n[lang][key]) ||
window.MyAi.i18n.en[key] || key;
}
// Expose shared translation helpers for other scripts
window.MyAi.currentLang = currentLang;
window.MyAi.t = t;
/**
* Update all legal page links to point to the active language.
*/
function updateLegalLinks(lang) {
$('[data-legal]').each(function () {
var page = $(this).data('legal');
$(this).attr('href', '/legal/' + page + '-' + lang + '.html');
});
}
/**
* Apply language across the entire page:
* - Update localStorage and <html lang> attribute
* - Translate all [data-i18n] and [data-i18n-placeholder] elements
* - Update legal page links
* - Update language button states
*/
function applyLanguage(lang) {
localStorage.setItem(LANG_KEY, lang);
document.documentElement.lang = lang;
updateLegalLinks(lang);
$('[data-i18n]').each(function () {
$(this).text(t($(this).data('i18n')));
});
$('[data-i18n-placeholder]').each(function () {
$(this).attr('placeholder', t($(this).data('i18n-placeholder')));
});
$('.lang-flag').attr('aria-pressed', 'false');
$('.lang-flag[data-lang="' + lang + '"]').attr('aria-pressed', 'true');
}
/* ============================================================
PAGE INITIALIZATION
============================================================ */
@@ -103,10 +23,10 @@
}
});
// Initialize language
applyLanguage(currentLang());
// Initialize language using shared utility
window.MyAi.applyLanguage(window.MyAi.currentLang());
$('.lang-flag').on('click', function () {
applyLanguage($(this).data('lang'));
window.MyAi.applyLanguage($(this).data('lang'));
});
/* ============================================================
@@ -132,74 +52,25 @@
});
/* ============================================================
SHARED FORM HELPERS
FORM HELPERS (imported from utils/form-helpers.js)
============================================================ */
/**
* Display a field error and mark its container with is-invalid class.
* @param {string} errorId - ID of the error element
* @param {string} msg - Error message to display (or empty to clear)
*/
function showFieldError(errorId, msg) {
var $el = $('#' + errorId);
$el.text(msg || '');
var $parent = $el.parent();
var $container = $parent.is('label, .consent-inline') ? $parent : $el.prev();
if (!$container.length || !$container.is('label, .consent-inline, .file-drop, .subscribe-row')) {
$container = $el.closest('form');
}
$container.toggleClass('is-invalid', !!msg);
}
/**
* Clear multiple field errors at once.
* @param {string[]} errorIds - Array of error element IDs
*/
function clearFieldErrors(errorIds) {
for (var i = 0; i < errorIds.length; i++) showFieldError(errorIds[i], '');
}
/**
* Validate email format with simple regex.
* @param {string} value - Email address to validate
* @returns {boolean} - True if email format is valid
*/
function isValidEmail(value) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(value || '').trim());
}
/**
* Extract a user-facing error message from a failed API response.
* For 4xx responses, the server's error field is shown (intentional feedback).
* For 5xx or missing body, a generic i18n fallback is returned.
* @param {object|null} body - Parsed JSON response body
* @param {number} status - HTTP status code
* @param {string} fallbackKey - i18n key for 5xx/unknown errors
* @param {string} [rateLimitKey] - i18n key for 429 responses
* @returns {string} - User-facing error message
*/
function extractApiError(body, status, fallbackKey, rateLimitKey) {
if (status === 429) return t(rateLimitKey || 'form.rateLimited');
var msg = body && (body.error || body.Error || body.title);
return (status >= 400 && status < 500 && msg) ? msg : t(fallbackKey);
}
// Expose shared helpers for other scripts
window.MyAi.showFieldError = showFieldError;
window.MyAi.clearFieldErrors = clearFieldErrors;
window.MyAi.isValidEmail = isValidEmail;
window.MyAi.extractApiError = extractApiError;
// showFieldError, clearFieldErrors, isValidEmail, extractApiError
// are now loaded from utils/form-helpers.js and exposed on window.MyAi
/* ============================================================
CONTACT FORM
============================================================ */
/* ============================================================
CONTACT FORM HANDLER
============================================================ */
/**
* Display success message and reset form.
*/
function formSuccess() {
$('#contactForm')[0].reset();
submitMSG(true, t('form.thanks'));
submitMSG(true, window.MyAi.t('form.thanks'));
}
/**
@@ -233,15 +104,15 @@
var name = $('#name').val().trim();
var email = $('#email').val().trim();
var message = $('#message').val().trim();
clearFieldErrors(['nameError', 'emailError', 'messageError']);
window.MyAi.clearFieldErrors(['nameError', 'emailError', 'messageError']);
$('#msgSubmit').removeClass().addClass('form-message').text('');
// Validate inputs
var hasError = false;
if (!name) { showFieldError('nameError', t('form.required.name')); hasError = true; }
if (!email) { showFieldError('emailError', t('form.required.email')); hasError = true; }
else if (!isValidEmail(email)) { showFieldError('emailError', t('form.required.emailInvalid')); hasError = true; }
if (!message) { showFieldError('messageError', t('form.required.message')); hasError = true; }
if (!name) { window.MyAi.showFieldError('nameError', window.MyAi.t('form.required.name')); hasError = true; }
if (!email) { window.MyAi.showFieldError('emailError', window.MyAi.t('form.required.email')); hasError = true; }
else if (!window.MyAi.isValidEmail(email)) { window.MyAi.showFieldError('emailError', window.MyAi.t('form.required.emailInvalid')); hasError = true; }
if (!message) { window.MyAi.showFieldError('messageError', window.MyAi.t('form.required.message')); hasError = true; }
if (hasError) return;
loader.addClass('loader-visible');
@@ -266,9 +137,9 @@
dataType: 'json'
}).done(function (resp) {
if (resp && resp.ok === true) formSuccess();
else submitMSG(false, t('form.captchaFailed'));
else submitMSG(false, window.MyAi.t('form.captchaFailed'));
}).fail(function (jqXHR) {
submitMSG(false, extractApiError(jqXHR.responseJSON, jqXHR.status, 'form.failed'), jqXHR.status === 429 ? 'warning' : 'danger');
submitMSG(false, window.MyAi.extractApiError(jqXHR.responseJSON, jqXHR.status, 'form.failed'), jqXHR.status === 429 ? 'warning' : 'danger');
formError();
}).always(function () {
loader.removeClass('loader-visible');
@@ -276,12 +147,12 @@
});
}
if (window.grecaptcha && reCaptchaSiteKey) {
if (window.grecaptcha && window.MyAi.getReCaptchaSiteKey()) {
grecaptcha.ready(function () {
grecaptcha.execute(reCaptchaSiteKey, { action: 'contact' }).then(postContact);
grecaptcha.execute(window.MyAi.getReCaptchaSiteKey(), { action: 'contact' }).then(postContact);
});
} else {
submitMSG(false, t('form.captchaFailed'));
submitMSG(false, window.MyAi.t('form.captchaFailed'));
formError();
loader.removeClass('loader-visible');
button.prop('disabled', false);
@@ -289,7 +160,7 @@
});
/* ============================================================
SUBSCRIBE FORM
SUBSCRIBE FORM HANDLER
============================================================ */
/**
@@ -307,23 +178,23 @@
* Update subscribe form message.
*/
function setMsg(severity, key) {
$msg.removeClass().addClass('form-message text-' + severity).text(t(key));
$msg.removeClass().addClass('form-message text-' + severity).text(window.MyAi.t(key));
}
clearFieldErrors(['subscribeEmailError', 'subscribeConsentError']);
window.MyAi.clearFieldErrors(['subscribeEmailError', 'subscribeConsentError']);
$msg.removeClass().addClass('form-message').text('');
// Validate inputs
var hasError = false;
if (!email) {
showFieldError('subscribeEmailError', t('form.required.email'));
window.MyAi.showFieldError('subscribeEmailError', window.MyAi.t('form.required.email'));
hasError = true;
} else if (!isValidEmail(email)) {
showFieldError('subscribeEmailError', t('form.required.emailInvalid'));
} else if (!window.MyAi.isValidEmail(email)) {
window.MyAi.showFieldError('subscribeEmailError', window.MyAi.t('form.required.emailInvalid'));
hasError = true;
}
if (!consent) {
showFieldError('subscribeConsentError', t('subscribe.noConsent'));
window.MyAi.showFieldError('subscribeConsentError', window.MyAi.t('subscribe.noConsent'));
hasError = true;
}
if (hasError) return;
@@ -350,16 +221,16 @@
}
}).fail(function (jqXHR) {
$msg.removeClass().addClass('form-message text-' + (jqXHR.status === 429 ? 'warning' : 'danger'))
.text(extractApiError(jqXHR.responseJSON, jqXHR.status, 'subscribe.failed'));
.text(window.MyAi.extractApiError(jqXHR.responseJSON, jqXHR.status, 'subscribe.failed'));
}).always(function () {
$loader.removeClass('loader-visible');
$button.prop('disabled', false);
});
}
if (window.grecaptcha && reCaptchaSiteKey) {
if (window.grecaptcha && window.MyAi.getReCaptchaSiteKey()) {
grecaptcha.ready(function () {
grecaptcha.execute(reCaptchaSiteKey, { action: 'subscribe' }).then(postSubscribe);
grecaptcha.execute(window.MyAi.getReCaptchaSiteKey(), { action: 'subscribe' }).then(postSubscribe);
});
} else {
$loader.removeClass('loader-visible');
@@ -369,175 +240,27 @@
});
/* ============================================================
COOKIE CONSENT
COOKIE CONSENT (handled by modules/cookie-consent.js)
============================================================ */
/**
* Parse consent object from localStorage.
* @returns {object|null} - Parsed consent object or null if not found
*/
function getConsent() {
try {
return JSON.parse(localStorage.getItem(CONSENT_KEY));
} catch (e) {
return null;
}
}
/**
* Persist consent object to localStorage.
*/
function setConsent(consent) {
localStorage.setItem(CONSENT_KEY, JSON.stringify(consent));
}
/**
* Apply stored consent preferences (e.g., load Google Tag Manager).
*/
function applyConsent(consent) {
if (consent && consent.analytics === true) loadGoogleTagManager();
}
/**
* Show cookie banner.
*/
function showBanner() {
$('#cookieBanner').fadeIn(200);
}
/**
* Hide cookie banner.
*/
function hideBanner() {
$('#cookieBanner').fadeOut(200);
}
/**
* Show "manage cookies" button.
*/
function showManage() {
$('#cookieManage').show();
}
$('#cookieReject, #cookieNecessary').on('click', function () {
setConsent({
necessary: true,
analytics: false,
ts: new Date().toISOString()
});
hideBanner();
showManage();
});
$('#cookieAccept').on('click', function () {
var consent = {
necessary: true,
analytics: true,
ts: new Date().toISOString()
};
setConsent(consent);
applyConsent(consent);
hideBanner();
showManage();
});
$('#cookieManage').on('click', function (e) {
e.preventDefault();
showBanner();
});
/**
* Initialize consent banner based on stored preferences.
*/
function initConsent() {
var consent = getConsent();
if (!consent) showBanner();
else {
applyConsent(consent);
showManage();
}
}
// Cookie banner, consent handlers, and storage are managed by
// modules/cookie-consent.js and exposed via window.MyAi
/* ============================================================
API & CONFIGURATION LOADING
API & CONFIGURATION LOADING (from utils/api.js)
============================================================ */
/**
* Check API /health/live endpoint and update status indicator.
*/
function checkApiLive() {
var $statusEl = $('#api-status');
return $.ajax({
url: '/api/health/live',
method: 'GET',
dataType: 'json',
timeout: 5000
}).done(function (data) {
var status = (data && data.status) ? data.status : 'unknown';
if ($statusEl.length) {
$statusEl.text('API: ' + status).removeClass('text-danger').addClass('text-success');
} else {
console.log('API live status:', status);
}
}).fail(function (jqXHR, textStatus, errorThrown) {
if ($statusEl.length) {
$statusEl.text('API: offline').removeClass('text-success').addClass('text-danger');
}
console.error('API health check failed:', textStatus, errorThrown);
});
}
/**
* Load reCaptcha public site key from API.
*/
function getRecaptchaWebKey() {
return $.get('/api/captcha').done(function (res) {
reCaptchaSiteKey = res;
if (reCaptchaSiteKey && !window.__recaptcha_loaded) {
window.__recaptcha_loaded = true;
var script = document.createElement('script');
script.setAttribute('src', 'https://www.google.com/recaptcha/api.js?render=' + reCaptchaSiteKey);
document.head.appendChild(script);
}
}).fail(function () {
console.warn('Could not load reCaptcha site key from /api/captcha');
});
}
/**
* Load Google Tag Manager ID from API.
*/
function getGoogleTagManagerId() {
return $.get('/api/google/tagmanager').done(function (res) {
gTagManagerId = res;
}).fail(function () {
console.warn('Could not load Google Tag Manager id from /api/google/tagmanager');
});
}
/**
* Load Google Tag Manager script if consent given and not already loaded.
*/
function loadGoogleTagManager() {
if (window.__gtm_loaded || !gTagManagerId) return;
window.__gtm_loaded = true;
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'gtm.start': new Date().getTime(),
event: 'gtm.js'
});
var script = document.createElement('script');
script.async = true;
script.src = 'https://www.googletagmanager.com/gtm/js?id=' + gTagManagerId;
document.head.appendChild(script);
}
// API utilities (checkApiLive, getRecaptchaWebKey, getGoogleTagManagerId, loadGoogleTagManager)
// are loaded from utils/api.js and exposed via window.MyAi
/* ============================================================
STARTUP
============================================================ */
$(window).on('load', function () {
$.when(checkApiLive(), getRecaptchaWebKey(), getGoogleTagManagerId()).always(initConsent);
$.when(
window.MyAi.checkApiLive(),
window.MyAi.getRecaptchaWebKey(),
window.MyAi.getGoogleTagManagerId()
).always(window.MyAi.initConsent);
});
})(jQuery);
+131
View File
@@ -0,0 +1,131 @@
/**
* Cookie Consent Management
*
* Handles cookie banner display, user consent preferences, and localStorage persistence.
* Integrates with analytics loading via applyConsent() callback.
*/
var CONSENT_KEY = "myai_cookie_consent";
/**
* Parse consent object from localStorage.
* Expected format: { necessary: true, analytics: bool, ts: iso-timestamp }
*
* @returns {object|null} - Parsed consent object or null if not found or invalid JSON
*/
function getConsent() {
try {
return JSON.parse(localStorage.getItem(CONSENT_KEY));
} catch (e) {
return null;
}
}
/**
* Persist consent object to localStorage as JSON.
* Stores { necessary, analytics, ts } properties.
*
* @param {object} consent - Consent object with necessary, analytics, ts properties
*/
function setConsent(consent) {
localStorage.setItem(CONSENT_KEY, JSON.stringify(consent));
}
/**
* Apply stored consent preferences.
* Currently loads Google Tag Manager if analytics consent is true.
* Hook for extending to other tracking/analytics systems.
*
* @param {object} consent - Consent object from localStorage
*/
function applyConsent(consent) {
if (window.MyAi && window.MyAi.applyConsent) {
window.MyAi.applyConsent(consent);
}
}
/**
* Show cookie consent banner with fade-in animation.
*/
function showBanner() {
$('#cookieBanner').fadeIn(200);
}
/**
* Hide cookie consent banner with fade-out animation.
*/
function hideBanner() {
$('#cookieBanner').fadeOut(200);
}
/**
* Show "manage cookies" button.
* Appears after user has made a consent choice.
*/
function showManage() {
$('#cookieManage').show();
}
/**
* Initialize cookie consent flow on page load.
* If user has already made a choice, apply preferences and show manage button.
* If no choice yet, show consent banner.
*/
function initConsent() {
var consent = getConsent();
if (!consent) {
showBanner();
} else {
applyConsent(consent);
showManage();
}
}
/**
* Bind cookie consent button handlers.
* Reject or Necessary-only button → analytics: false
* Accept button → analytics: true (and load GTM)
* Manage button → show banner again
*/
function setupConsentHandlers() {
$('#cookieReject, #cookieNecessary').on('click', function () {
setConsent({
necessary: true,
analytics: false,
ts: new Date().toISOString()
});
hideBanner();
showManage();
});
$('#cookieAccept').on('click', function () {
var consent = {
necessary: true,
analytics: true,
ts: new Date().toISOString()
};
setConsent(consent);
applyConsent(consent);
hideBanner();
showManage();
});
$('#cookieManage').on('click', function (e) {
e.preventDefault();
showBanner();
});
}
// Expose consent utilities on window.MyAi
window.MyAi = window.MyAi || {};
window.MyAi.getConsent = getConsent;
window.MyAi.setConsent = setConsent;
window.MyAi.initConsent = initConsent;
window.MyAi.showBanner = showBanner;
window.MyAi.hideBanner = hideBanner;
// Initialize on DOM ready
$(function() {
setupConsentHandlers();
initConsent();
});
+121
View File
@@ -0,0 +1,121 @@
/**
* API & Configuration Loading Utilities
*
* Shared helpers for API health checks and configuration retrieval.
* Handles reCaptcha key loading, Google Tag Manager setup, and API health checks.
*/
var reCaptchaSiteKey = null;
var gTagManagerId = null;
/**
* Check API /health/live endpoint and update status indicator if present.
* Updates #api-status element with "API: {status}" (green if OK, red if down).
* Logs result to console if element not found.
*
* @returns {object} - jQuery AJAX promise
*/
function checkApiLive() {
var $statusEl = $('#api-status');
return $.ajax({
url: '/api/health/live',
method: 'GET',
dataType: 'json',
timeout: 5000
}).done(function (data) {
var status = (data && data.status) ? data.status : 'unknown';
if ($statusEl.length) {
$statusEl.text('API: ' + status).removeClass('text-danger').addClass('text-success');
} else {
console.log('API live status:', status);
}
}).fail(function (jqXHR, textStatus, errorThrown) {
if ($statusEl.length) {
$statusEl.text('API: offline').removeClass('text-success').addClass('text-danger');
}
console.error('API health check failed:', textStatus, errorThrown);
});
}
/**
* Load reCaptcha public site key from /api/captcha endpoint.
* Dynamically injects reCaptcha script if not already loaded.
* Stores key on window for use by grecaptcha.execute().
*
* @returns {object} - jQuery AJAX promise
*/
function getRecaptchaWebKey() {
return $.get('/api/captcha').done(function (res) {
reCaptchaSiteKey = res;
if (reCaptchaSiteKey && !window.__recaptcha_loaded) {
window.__recaptcha_loaded = true;
var script = document.createElement('script');
script.setAttribute('src', 'https://www.google.com/recaptcha/api.js?render=' + reCaptchaSiteKey);
document.head.appendChild(script);
}
}).fail(function () {
console.warn('Could not load reCaptcha site key from /api/captcha');
});
}
/**
* Load Google Tag Manager ID from /api/google/tagmanager endpoint.
* Does not load GTM script—that happens in loadGoogleTagManager() once consent is given.
*
* @returns {object} - jQuery AJAX promise
*/
function getGoogleTagManagerId() {
return $.get('/api/google/tagmanager').done(function (res) {
gTagManagerId = res;
}).fail(function () {
console.warn('Could not load Google Tag Manager id from /api/google/tagmanager');
});
}
/**
* Load and inject Google Tag Manager script if consent is given and not already loaded.
* Sets up dataLayer and injects GTM script from googleapis.com.
* Called only after user accepts analytics consent.
*
* Requires gTagManagerId to be loaded first via getGoogleTagManagerId().
*/
function loadGoogleTagManager() {
if (window.__gtm_loaded || !gTagManagerId) return;
window.__gtm_loaded = true;
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'gtm.start': new Date().getTime(),
event: 'gtm.js'
});
var script = document.createElement('script');
script.async = true;
script.src = 'https://www.googletagmanager.com/gtm/js?id=' + gTagManagerId;
document.head.appendChild(script);
}
/**
* Get the currently loaded reCaptcha site key.
* @returns {string|null} - reCaptcha site key or null if not yet loaded
*/
function getReCaptchaSiteKey() {
return reCaptchaSiteKey;
}
/**
* Get the currently loaded Google Tag Manager ID.
* @returns {string|null} - GTM ID or null if not yet loaded
*/
function getGoogleTagManagerId() {
return gTagManagerId;
}
// Expose API utilities on window.MyAi for use by other scripts
window.MyAi = window.MyAi || {};
window.MyAi.checkApiLive = checkApiLive;
window.MyAi.getRecaptchaWebKey = getRecaptchaWebKey;
window.MyAi.getGoogleTagManagerId = getGoogleTagManagerId;
window.MyAi.loadGoogleTagManager = loadGoogleTagManager;
window.MyAi.getReCaptchaSiteKey = getReCaptchaSiteKey;
window.MyAi.applyConsent = function(consent) {
if (consent && consent.analytics === true) loadGoogleTagManager();
};
+77
View File
@@ -0,0 +1,77 @@
/**
* Form Validation & Error Handling Utilities
*
* Shared helpers for form field validation and error display across all pages.
* Provides reusable patterns for: error messages, field validation, API error extraction.
*/
/**
* Display a field error message and mark its container with is-invalid class.
* Finds the appropriate parent container (label, form group, consent row, etc.)
* and toggles the is-invalid class based on whether msg is provided.
*
* @param {string} errorId - HTML ID of the error message element
* @param {string} [msg] - Error message to display; empty/null to clear
*/
function showFieldError(errorId, msg) {
var $el = $('#' + errorId);
$el.text(msg || '');
var $parent = $el.parent();
var $container = $parent.is('label, .consent-inline') ? $parent : $el.prev();
if (!$container.length || !$container.is('label, .consent-inline, .file-drop, .subscribe-row')) {
$container = $el.closest('form');
}
$container.toggleClass('is-invalid', !!msg);
}
/**
* Clear multiple field errors at once.
* Calls showFieldError(id, '') for each error element ID.
*
* @param {string[]} errorIds - Array of HTML IDs to clear
*/
function clearFieldErrors(errorIds) {
for (var i = 0; i < errorIds.length; i++) {
showFieldError(errorIds[i], '');
}
}
/**
* Validate email format using a simple regex pattern.
* Checks for: non-whitespace + @ + non-whitespace + . + non-whitespace
*
* @param {string} value - Email address to validate
* @returns {boolean} - True if email format is valid
*/
function isValidEmail(value) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(value || '').trim());
}
/**
* Extract user-facing error message from API response.
*
* Rules:
* - 429 (rate limit) → return rateLimitKey translation
* - 4xx with error body → return server's error message (intentional feedback)
* - 5xx or no body → return fallbackKey translation
*
* @param {object|null} body - Parsed JSON response body
* @param {number} status - HTTP status code
* @param {string} fallbackKey - i18n key for 5xx/unknown errors (e.g., 'form.failed')
* @param {string} [rateLimitKey] - Optional i18n key for 429 (defaults to 'form.rateLimited')
* @returns {string} - User-facing error message
*/
function extractApiError(body, status, fallbackKey, rateLimitKey) {
if (status === 429) {
return window.MyAi.t(rateLimitKey || 'form.rateLimited');
}
var msg = body && (body.error || body.Error || body.title);
return (status >= 400 && status < 500 && msg) ? msg : window.MyAi.t(fallbackKey);
}
// Expose helpers on window.MyAi for use by other scripts
window.MyAi = window.MyAi || {};
window.MyAi.showFieldError = showFieldError;
window.MyAi.clearFieldErrors = clearFieldErrors;
window.MyAi.isValidEmail = isValidEmail;
window.MyAi.extractApiError = extractApiError;
+91
View File
@@ -0,0 +1,91 @@
/**
* Internationalization (i18n) Utilities
*
* Shared helpers for language detection, translation lookup, and language switching.
* Expects window.MyAi.i18n dictionary to be populated by i18n.js.
*/
var LANG_KEY = "myai_lang";
/**
* Detect browser language preference from navigator.
* Returns 'ro' if browser language starts with 'ro', otherwise 'en'.
*
* @returns {string} - 'ro' or 'en'
*/
function browserLang() {
return ((navigator.language || navigator.userLanguage || 'en').toLowerCase().indexOf('ro') === 0) ? 'ro' : 'en';
}
/**
* Get the currently active language preference.
* Uses localStorage if set, otherwise detects from browser.
*
* @returns {string} - 'ro' or 'en'
*/
function currentLang() {
return localStorage.getItem(LANG_KEY) || browserLang();
}
/**
* Translate a key into the current language.
* Falls back to English if key not found in the current language.
* Requires window.MyAi.i18n to be populated with en/ro dictionaries.
*
* Usage: MyAi.t('form.name') → "Name" (or "Nume" if lang is 'ro')
*
* @param {string} key - Translation key (e.g., 'form.name')
* @returns {string} - Translated text or fallback key if not found
*/
function t(key) {
var lang = currentLang();
return (window.MyAi.i18n[lang] && window.MyAi.i18n[lang][key]) ||
window.MyAi.i18n.en[key] || key;
}
/**
* Apply a language across the entire page.
* Updates:
* - localStorage with new language preference
* - <html lang> attribute
* - All [data-i18n] elements with translated text
* - All [data-i18n-placeholder] elements with translated placeholders
* - Legal page links to point to correct language version
* - Language button states (aria-pressed)
*
* @param {string} lang - Language code ('en' or 'ro')
*/
function applyLanguage(lang) {
localStorage.setItem(LANG_KEY, lang);
document.documentElement.lang = lang;
updateLegalLinks(lang);
$('[data-i18n]').each(function () {
$(this).text(t($(this).data('i18n')));
});
$('[data-i18n-placeholder]').each(function () {
$(this).attr('placeholder', t($(this).data('i18n-placeholder')));
});
$('.lang-flag').attr('aria-pressed', 'false');
$('.lang-flag[data-lang="' + lang + '"]').attr('aria-pressed', 'true');
}
/**
* Update all legal page links to point to the active language version.
* Looks for [data-legal] attribute (e.g., data-legal="terms") and
* updates href to /legal/{page}-{lang}.html
*
* @param {string} lang - Language code ('en' or 'ro')
*/
function updateLegalLinks(lang) {
$('[data-legal]').each(function () {
var page = $(this).data('legal');
$(this).attr('href', '/legal/' + page + '-' + lang + '.html');
});
}
// Expose i18n utilities on window.MyAi for use by other scripts
window.MyAi = window.MyAi || {};
window.MyAi.currentLang = currentLang;
window.MyAi.t = t;
window.MyAi.applyLanguage = applyLanguage;
window.MyAi.browserLang = browserLang;
+14 -24
View File
@@ -4,29 +4,15 @@
* Dynamically injects a common header (topbar) and language-aware footer
* into all 6 legal pages to eliminate HTML duplication.
*
* Footer content depends on page language (EN vs RO).
* Language links use event delegation so they work on injected elements.
* Reuses language detection and switching utilities from shared modules.
* Uses event delegation for language links so they work on injected elements.
*/
(function(){
"use strict";
// Local constant for storing page language preference in localStorage
var LANG_KEY = "legalLang";
/**
* Detect browser language preference (EN or RO).
*/
function browserLang(){
var lang = (navigator.language || navigator.userLanguage || 'en').toLowerCase();
return lang.indexOf('ro') === 0 ? 'ro' : 'en';
}
/**
* Get stored language preference, fall back to browser detection.
*/
function getLang(){
return localStorage.getItem(LANG_KEY) || browserLang();
}
/**
* Build URL to alternate language page.
* Supports both -en.html and -ro.html naming patterns.
@@ -57,6 +43,7 @@
/**
* Inject topbar with logo and language switcher.
* Uses pageLang() to determine current page language and set active state.
*/
function injectTopbar(){
var base = basePage();
@@ -79,13 +66,11 @@
}
/**
* Inject language-aware footer.
* EN: "©2026 myAi. All rights reserved."
* RO: "©2026 myAi. Toate drepturile sunt rezervate."
* Inject language-aware footer with copyright and legal links.
* Footer text and links vary by current page language (EN vs RO).
*/
function injectFooter(){
var lang = pageLang();
var base = basePage();
var copyrightText = lang === 'ro' ? '©2026 myAi. Toate drepturile sunt rezervate.' : '©2026 myAi. All rights reserved.';
var linksHtml = '';
if(lang === 'ro'){
@@ -105,7 +90,7 @@
}
/**
* Initialize language persistence and topbar injection.
* Initialize language persistence and inject topbar/footer.
*/
function init(){
localStorage.setItem(LANG_KEY, pageLang());
@@ -115,7 +100,8 @@
/**
* Handle language link clicks with event delegation.
* Works on both static and injected links.
* Works on both static and dynamically injected language links.
* Updates localStorage and navigates to the target language page.
*/
document.addEventListener('click', function(e){
var link = e.target.closest('.lang-link');
@@ -125,7 +111,11 @@
window.location.href = targetPage(window.location.pathname, link.getAttribute('data-lang'));
});
// Run on page load
/* ============================================================
PAGE INITIALIZATION
============================================================ */
// Initialize topbar and footer injection on DOM ready
if(document.readyState === 'loading'){
document.addEventListener('DOMContentLoaded', init);
} else {