var _NAVIPLUS_VERSION = /*replace*/'DEV'/*endreplace*/; //==> with be replaced to $_GET['version']
// NAVI01347. Start
/* Mốc 0 của RUM (rum/navi-rum.js, include ở cuối file): lúc start.js bắt đầu chạy. Giữ mốc lần chạy ĐẦU. */
try { if (typeof window._naviRumT0 !== 'number') window._naviRumT0 = performance.now(); } catch (e) {}
/* Nâng bộ đệm Resource Timing (250 → 600) cho RUM: CHỈ trang Shopify (X7, Khôi chốt Global/Wix không đổi) — đã dời vào
processNaviSetting ngay khi biết env (cùng lượt chạy đồng bộ, lệch vài µs). */
(function (global) {
var receiverUrl = 'https://dev-shopify.naviplus.app/naviplus/microservices/debug-receiver.php';
/**
* Tạo hàm _navidebug theo môi trường chạy.
* DEV: log console + gửi batch về debug receiver.
* Production: no-op để không ảnh hưởng runtime.
*/
function create(version) {
if (version !== 'DEV') {
return function () {};
}
var buffer = [];
var timer = null;
/**
* Gửi batch log hiện tại lên debug receiver.
*/
function flush() {
if (!buffer.length) return;
var payload = { logs: buffer.slice() };
buffer = [];
fetch(receiverUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
keepalive: true
}).catch(function () {});
}
/**
* Hàm debug dùng chung cho start.js.php khi cần chẩn đoán nhanh.
*/
return function (label, data) {
var msg = '[' + label + '] ' + (typeof data === 'object' ? JSON.stringify(data) : String(data === undefined ? '' : data));
console.log(msg);
buffer.push({ level: 'log', msg: msg });
clearTimeout(timer);
timer = setTimeout(flush, 300);
};
}
global.NaviDebug = { create: create };
})(window);
window._navidebug = NaviDebug.create(_NAVIPLUS_VERSION);
//******** Khai báo các biến cần thiết ****************************/
var cdnCloudflare = 'https://live-r2.naviplus.app/live';
// Fallback CDN
if (typeof _isUseNaviCDNFallback !== 'undefined' && _isUseNaviCDNFallback === true) cdnCloudflare = 'https://flov.b-cdn.net/live';
var cdnUigenCSS = 'https://dev-shopify.naviplus.app/naviplus/frontend';
if (_NAVIPLUS_VERSION != 'DEV') cdnUigenCSS = cdnCloudflare + "/" + _NAVIPLUS_VERSION;
var cdnUigenJS = 'https://dev-shopify.naviplus.app/naviplus/frontend';
if (_NAVIPLUS_VERSION != 'DEV') cdnUigenJS = cdnCloudflare + "/" + _NAVIPLUS_VERSION;
var cdnJson = 'https://cdn.naviplus.app/naviplus/data/json';
var startJs = 'start.js.php';
if (_NAVIPLUS_VERSION != 'DEV') startJs = "start.js";
var doc = document;
var uigenCss = "/uigen/uigen.css.php";
if (_NAVIPLUS_VERSION != 'DEV') uigenCss = "/uigen.min.css";
var uigenJs = "/uigen.js.php";
if (_NAVIPLUS_VERSION != 'DEV') uigenJs = "/uigen.min.js";
// File font thật của RemixIcon (được @font-face bên trong remixicon.css trỏ tới) — tách biến
// riêng để preload dùng chung version với remixicon.css bên dưới, khỏi hardcode 2 nơi lệch version.
/* ⚠ Chuỗi '?t=1766743011500' BẮT BUỘC phải có và phải khớp TUYỆT ĐỐI với chuỗi RemixIcon tự nhét
vào @font-face trong chính remixicon.css của bản 4.8.0 (họ dùng nó để cache-bust). Trình duyệt
so khớp với request thật theo URL NGUYÊN VẸN kể cả query string: thiếu '?t='
thì preload không bao giờ được dùng lại → font tải 2 lần + Chrome cảnh báo "preloaded using link
preload but not used within a few seconds" trên console của khách (KH mein-kleines-hochzeitsbuero
báo 2026-09-06, chat Inbox+ NS-9BL2HEPGXQ).
⛔ Nâng version RemixIcon (4.8.0 → khác) thì PHẢI mở file .css của version mới lấy lại đúng chuỗi
'?t=...' đó dán vào đây, nếu không warning quay lại y hệt mà không có gì báo. */
var remixiconWoff2 = 'https://cdn.jsdelivr.net/npm/remixicon@4.8.0/fonts/remixicon.woff2?t=1766743011500';
//******** Khai báo các biến cần thiết ****************************/
var _NAVIPLUS = {
VER: _NAVIPLUS_VERSION,
SHOP: '',
VARS: [
cdnUigenCSS + uigenCss, //==> with be replaced to uigen.min.css
'https://cdn.jsdelivr.net/npm/animate.css@4.1.1/animate.min.css',
'https://cdn.jsdelivr.net/npm/remixicon@4.8.0/fonts/remixicon.css',
// Material Symbols: KHÔNG preload — lazy inject bởi NaviFontLoader.ensureMaterial() chỉ khi menu có ms: icon
// Cần phải đánh giá vì hiệu qủa có khi ko lớn mà ko update ngay.
// cdnJson + '/{shop}.all.json',
// cdnJson + '/{shop}.info.json',
cdnUigenJS + uigenJs //==> with be replaced to uigen.min.js
],
GO: (function () {
const _loaded = { css: [], js: [], json: [] };
//============================== MAIN FUNCTIONS ==============================
function loadUIGenJS(url, ver, naviSetting) {
if (!navistart.validateUIgenUrl(url)) return;
// ---- BƯỚC 1: Tạo script ----
const script = doc.createElement("script");
script.src = navistart.addVersionToUrl(url, ver);
_loaded.js.push(script.src);
// ---- Bước 2: Copy các biến trong _navi_setting thành attributes cho uigen.js ----
navistart.copyAttribute(script, naviSetting);
navistart.setAttributeDefer(script);
/* Script chèn động bị Chrome xếp ưu tiên tải Low — ngang hàng ảnh theme (đo eacygrow.com:
121 ảnh tải hết rồi mới tới uigen.min.js, skeleton Replace xoay thêm vài giây dù file đã
cache). fetchpriority=high đưa nó lên đầu hàng chờ mạng; KHÔNG đổi thứ tự thực thi
(setAttributeDefer ở trên vẫn giữ), không chặn trang. Trình duyệt không hỗ trợ → gán
property/attribute vô nghĩa, hành vi y như cũ. Đi cùng preload + fetchpriority của thẻ
start.js trong app-embed.liquid / app-block.liquid. */
script.fetchPriority = "high";
script.setAttribute("fetchpriority", "high");
// ---- Bước 3: Fallback nếu CDN chậm ----
script.onerror = () => {
navistart.failOver(script.src, script, _NAVIPLUS.VER);
};
// ---- Bước 4: Append vào head ----
// console.log("Loading... uigen.js", script);
doc.head.appendChild(script);
}
//============================== MAIN FUNCTIONS ==============================
function start(vars, naviSetting) {
navistart.initDOM();
navistart.initResources(vars, naviSetting, loadUIGenJS);
}
return { start, loadUIGenJS };
})()
};
/**
* ============================================
* NAVISTART - Naviplus Start Utilities Module
* ============================================
*
* Module tiện ích chính cho việc khởi tạo và quản lý tài nguyên của Naviplus.
* Cung cấp các hàm utility cho:
*
* - Resource loading (CSS, JSON, JS)
* - DOM manipulation và initialization
* - Shop/domain normalization
* - Performance monitoring và timing
* - Configuration management
*
* Tất cả functions đều static và có thể truy cập qua navistart.*
*/
if (typeof navistart === 'undefined') navistart = {};
/* Fallback _navidebug: start.js.php định nghĩa window._navidebug (NaviDebug.create theo version).
Container khác include module này (vd simulator.php) không có → đặt no-op để tránh
ReferenceError ở consoleOnce/logTiming. Không override bản thật vì dùng || */
window._navidebug = window._navidebug || function () {};
if (!window._NAVIPLUS_START_MODULE) {
window._NAVIPLUS_START_MODULE = true;
/**
* In ra biến lên console chỉ một lần trong suốt phiên làm việc của trang.
* Sử dụng cơ chế lưu trữ trên window để đảm bảo mỗi key chỉ được log một lần.
*
* @param {*} variable - Biến cần in ra console (có thể là bất kỳ kiểu dữ liệu nào)
* @param {string} [key='_CONSOLE_NAVIPLUS_START'] - Khóa duy nhất để kiểm tra đã log chưa.
* Mặc định là '_CONSOLE_NAVIPLUS_START'
*
* @example
* navistart.consoleOnce({user: 'john', version: '1.0'}); // Log object
* navistart.consoleOnce('Debug message', 'custom_key'); // Log với key tùy chỉnh
*/
navistart.consoleOnce = function(variable, key = '_CONSOLE_NAVIPLUS_START') {
if (!window[key]) {
window[key] = true;
// Gate dump qua _navidebug (no-op ở production, chỉ in khi version DEV)
_navidebug('NAVIPLUS_START', variable);
}
};
/**
* Chuẩn hóa tên shop dựa trên môi trường sử dụng.
*
* Quy tắc chuẩn hóa:
* - Nếu env là "shopify": loại bỏ phần '.myshopify.com' khỏi tên shop
* (VD: 'mystore.myshopify.com' -> 'mystore')
* - Nếu env không phải "shopify": trả về domain đã chuẩn hóa bằng normalizeDomainSync
* - Nếu không có env hoặc shop rỗng: trả lại shop gốc
*
* @param {string} shop - Tên shop hoặc domain cần chuẩn hóa
* @param {string} env - Môi trường sử dụng ('shopify', 'woocommerce', etc.)
* @returns {string} Tên shop đã được chuẩn hóa theo quy tắc của môi trường
*
* @example
* navistart.normalizeShop('mystore.myshopify.com', 'shopify'); // 'mystore'
* navistart.normalizeShop('example.com', 'woocommerce'); // 'example.com' (đã chuẩn hóa)
* navistart.normalizeShop('', 'shopify'); // '' (rỗng thì trả về rỗng)
*/
navistart.normalizeShop = function(shop, env) {
if (!shop) return shop;
if (env && env !== "shopify") {
return navistart.normalizeDomainSync(shop);
}
if (env === "shopify") {
return shop.replace('.myshopify.com', '');
}
return shop;
}
/**
* Chuẩn hóa domain một cách đồng bộ, trả về root domain.
*
* Ưu tiên sử dụng thư viện tldts (nếu có sẵn) để parse domain chính xác.
* Nếu không có tldts, fallback về logic tự implement với các quy tắc:
*
* - Shopify domains (*.myshopify.com) được trả nguyên vẹn
* - Loại bỏ protocol (http://, https://)
* - Loại bỏ path, query string, hash, port
* - Loại bỏ www prefix
* - Xử lý TLD phức tạp (co.uk, com.vn, etc.)
*
* @param {string} host - Domain hoặc URL cần chuẩn hóa
* @returns {string} Root domain đã được chuẩn hóa
*
* @example
* navistart.normalizeDomainSync('https://sub.example.co.uk/path'); // 'example.co.uk'
* navistart.normalizeDomainSync('mystore.myshopify.com'); // 'mystore.myshopify.com'
* navistart.normalizeDomainSync('www.example.com:8080'); // 'example.com'
*/
navistart.normalizeDomainSync = function (host) {
host = String(host || "").trim().toLowerCase();
host = host.replace(/^[a-z]+:\/\//, "")
.split(/[/?#]/)[0]
.replace(/:\d+$/, "")
.replace(/^www\d*\./, "");
if (host.endsWith(".myshopify.com")) {
return host;
}
if (window.tldts) {
const rootDomain = window.tldts.getDomain(host);
// Kiểm tra kết quả từ tldts có hợp lý không
if (rootDomain && rootDomain !== host) {
// Kiểm tra thêm: nếu rootDomain quá ngắn (chỉ là TLD) thì có thể sai
// Ví dụ: khoipn.com.jp -> com.jp (sai, phải là khoipn.com.jp)
const hostParts = host.split('.');
const rootParts = rootDomain.split('.');
// Nếu rootDomain không chứa phần domain chính (phần đầu tiên), có thể sai
if (rootParts.length >= 2 && hostParts.length > rootParts.length) {
// Kiểm tra xem rootDomain có phải chỉ là TLD không
const firstHostPart = hostParts[0];
if (!rootDomain.includes(firstHostPart)) {
// Có thể tldts trả về sai, dùng fallback
} else {
return rootDomain;
}
} else {
return rootDomain;
}
}
// Nếu tldts trả về null hoặc chính host gốc (không nhận diện được TLD phức tạp)
// thì dùng fallback logic bên dưới
}
const parts = host.split(".");
const len = parts.length;
if (len <= 2) return host;
const cc = parts[len - 1]; // country code dự đoán
const common2 = parts[len - 2]; // phần đứng trước cc
const remaining = parts.slice(0, -1);
const countryCodes = new Set([
'vn', 'uk', 'au', 'jp', 'kr', 'cn', 'id', 'my', 'sg', 'th', 'ph', 'nz', 'br', 'mx',
'za', 'in', 'ru', 'tr', 'pl', 'pt', 'es', 'it', 'fr', 'de'
]);
const commonLevel2 = new Set(['com', 'net', 'org', 'gov', 'edu', 'co', 'ac', 'ne', 'or']);
// rule: multi-level TLD dạng com.vn, net.vn, co.uk, com.au ...
if (cc.length === 2 && countryCodes.has(cc) && commonLevel2.has(common2)) {
// Lấy 1 phần trước TLD phức tạp (nếu có)
// khoipn.com.jp -> khoipn.com.jp (đúng vì chỉ có 3 phần)
// sub.khoipn.com.jp -> khoipn.com.jp
if (remaining.length > 2) {
return remaining.slice(-2).join('.') + '.' + cc;
} else {
// Nếu remaining chỉ có 2 phần, lấy cả 2 phần
return remaining.join('.') + '.' + cc;
}
}
// fallback mặc định: TLD 1 lớp
return parts.slice(-2).join('.');
};
/**
* Lấy thuộc tính từ object naviSetting một cách an toàn.
*
* Hàm này kiểm tra:
* - naviSetting có tồn tại và là object không
* - Thuộc tính có tồn tại trong naviSetting không (không phải undefined)
* - Nếu không thỏa mãn, trả về giá trị mặc định
*
* @param {Object} naviSetting - Object chứa các setting của Naviplus
* @param {string} attr - Tên thuộc tính cần lấy
* @param {*} [defaultValue=null] - Giá trị mặc định nếu thuộc tính không tồn tại
* @returns {*} Giá trị của thuộc tính hoặc giá trị mặc định
*
* @example
* const setting = { shop: 'example.com', embed_id: '123' };
* navistart.getNaviSetting(setting, 'shop'); // 'example.com'
* navistart.getNaviSetting(setting, 'token'); // '123'
* navistart.getNaviSetting(setting, 'version', '1.0'); // '1.0' (mặc định)
* navistart.getNaviSetting(null, 'shop'); // null (mặc định)
*/
navistart.getNaviSetting = function(naviSetting, attr, defaultValue = null) {
if (!naviSetting || typeof naviSetting !== 'object') return defaultValue;
return naviSetting[attr] !== undefined ? naviSetting[attr] : defaultValue;
}
/**
* Module tối ưu hóa hiệu năng Naviplus.
*
* Module này tự động đo thời gian tải các tài nguyên quan trọng:
* - uigen.css: File CSS chính của UI generator
* - uigen.js: File JavaScript chính của UI generator
*
* Sử dụng IIFE pattern để encapsulate các biến private và chỉ expose
* những gì cần thiết qua return object.
*
* @returns {Object} Object chứa các hàm public của module
*/
navistart.Optimize = (function () {
const timing = {
start: performance.now(),
uigenCss: null,
uigenJs: null
};
let hasLogged = false;
/**
* Ghi log thời gian tải các tài nguyên chính và lưu vào window._NAVIPLUS_TIMING.
*
* Chỉ thực hiện một lần khi cả uigenCss và uigenJs đều đã được đo.
* Kết quả được lưu vào window._NAVIPLUS_TIMING để debug và monitoring.
*
* @private
*/
function logTiming() {
if (hasLogged) return;
if (timing.uigenCss !== null && timing.uigenJs !== null) {
hasLogged = true;
window._NAVIPLUS_TIMING = {
start: timing.start,
uigenCss: timing.uigenCss,
uigenJs: timing.uigenJs
};
// Giữ window._NAVIPLUS_TIMING (monitoring), gate dòng log qua _navidebug
_navidebug('NAVIPLUS_TIMING', window._NAVIPLUS_TIMING);
}
}
/**
* Đợi đến khi file CSS được tải hoàn toàn và gọi callback với thời gian đã chờ.
*
* Cách hoạt động:
* 1. Kiểm tra mỗi 10ms để tìm link element chứa urlContains trong href
* 2. Nếu link.sheet đã tồn tại → callback ngay lập tức
* 3. Nếu link chưa có sheet → gán onload event để callback khi tải xong
* 4. Dừng interval sau khi callback được gọi
*
* @param {string} urlContains - Chuỗi con trong URL để identify file CSS cần theo dõi
* @param {function} callback - Hàm callback nhận thời gian chờ tính bằng ms
*
* @example
* waitForCSSLoaded('uigen', function(elapsed) {
* console.log('CSS loaded in', elapsed, 'ms');
* });
*/
function waitForCSSLoaded(urlContains, callback) {
const startTime = performance.now();
const timer = setInterval(() => {
const links = document.querySelectorAll('link[rel="stylesheet"]');
for (const link of links) {
if (link.href.includes(urlContains)) {
if (link.sheet) {
clearInterval(timer);
const elapsed = performance.now() - startTime;
callback(elapsed);
return;
} else {
link.onload = () => {
clearInterval(timer);
const elapsed = performance.now() - startTime;
callback(elapsed);
};
return;
}
}
}
}, 10);
}
/**
* Đợi đến khi biến toàn cục xuất hiện trên window (đánh dấu script đã load xong).
*
* Thường dùng để detect khi script bên thứ 3 đã load xong bằng cách
* kiểm tra biến global mà script đó tạo ra.
*
* @param {string} varName - Tên biến toàn cục cần kiểm tra (VD: 'naviman_version', 'jQuery')
* @param {function} callback - Hàm callback nhận thời gian chờ tính bằng ms
*
* @example
* waitForJSLoaded('naviman_version', function(elapsed) {
* console.log('Naviman loaded in', elapsed, 'ms');
* });
*/
function waitForJSLoaded(varName, callback) {
const startTime = performance.now();
const timer = setInterval(() => {
if (window[varName] !== undefined) {
clearInterval(timer);
const elapsed = performance.now() - startTime;
callback(elapsed);
}
}, 10);
}
// Đợi file CSS có chứa "uigen" được load xong rồi thực hiện callback
waitForCSSLoaded("uigen", function (elapsed) {
timing.uigenCss = elapsed;
logTiming();
});
// Đợi đến khi biến toàn cục "naviman_version" xuất hiện (file JS đã load xong), sau đó thực hiện callback
waitForJSLoaded("naviman_version", function (elapsed) {
timing.uigenJs = elapsed;
logTiming();
});
return {
/**
* Lấy thông tin timing hiện tại.
* @returns {Object} Object chứa start, uigenCss, uigenJs timing
*/
getTiming: function () {
return timing;
}
};
})();
// ========== RESOURCE LOADING FUNCTIONS ==========
/**
* @private Biến tracking các tài nguyên đã được load để tránh duplicate.
* Đặt tên có tiền tố "_navi" (không phải "_loaded" trần) — script này chạy ở top-level,
* không bọc IIFE, nên tên biến chung chung dễ đụng độ global scope với theme/app khác
* (từng xung đột thật với 1 theme khách có script khai `const _loaded` riêng, gây
* SyntaxError redeclare chặn đứng toàn bộ start.js).
*/
var _naviLoaded = { css: [], js: [], json: [] };
/**
* @private Set tracking các JSON URLs đã được fetch để tránh duplicate requests
*/
var _naviJsonSet = new Set();
/**
* Load file CSS vào trang web.
*
* Tính năng:
* - Tự động thêm version parameter nếu được cung cấp
* - Kiểm tra duplicate để tránh load cùng file CSS nhiều lần
* - Tracking các file đã load trong _naviLoaded.css
*
* @param {string} u - URL của file CSS
* @param {string|null} v - Version parameter (sẽ được thêm vào URL nếu có)
*
* @example
* navistart.loadCSS('https://cdn.example.com/style.css', '1.0');
* // Tạo:
*/
navistart.loadCSS = function(u, v) {
const f = navistart.addVersionToUrl(u, v);
if (document.querySelector(`link[href="${f}"]`)) return;
_naviLoaded.css.push(f);
document.head.appendChild(Object.assign(document.createElement("link"), { rel: "stylesheet", href: f }));
};
/**
* Load và cache file JSON từ URL.
*
* Tính năng:
* - Sử dụng fetch với cache "force-cache" để tối ưu hiệu năng
* - Kiểm tra duplicate requests để tránh fetch cùng URL nhiều lần
* - Silent fail (catch empty) vì JSON thường không critical
*
* @param {string} u - URL của file JSON cần fetch
*
* @example
* navistart.loadJSON('https://api.example.com/config.json');
*/
navistart.loadJSON = function(u) {
if (!u || _naviJsonSet.has(u)) return;
_naviLoaded.json.push(u);
_naviJsonSet.add(u);
fetch(u, { cache: "force-cache" }).catch(() => { });
};
/**
* Thêm version parameter vào URL để cache busting.
*
* Quy tắc:
* - Nếu URL đã có query string (?): thêm &v=version
* - Nếu URL chưa có query string: thêm ?v=version
* - Nếu version null/undefined: trả về URL gốc
*
* @param {string} url - URL gốc
* @param {string|null} v - Version string
* @returns {string} URL với version parameter hoặc URL gốc
*
* @example
* navistart.addVersionToUrl('style.css', '1.0'); // 'style.css?v=1.0'
* navistart.addVersionToUrl('style.css?a=1', '1.0'); // 'style.css?a=1&v=1.0'
* navistart.addVersionToUrl('style.css', null); // 'style.css'
*/
navistart.addVersionToUrl = function(url, v) {
return v ? url + (url.includes('?') ? '&' : '?') + 'v=' + v : url;
};
// ========== DOM AND SCRIPT UTILITIES ==========
/**
* @private Tên file start script dựa trên environment
*/
var startJs = 'start.js.php';
if (typeof _NAVIPLUS_VERSION !== 'undefined' && _NAVIPLUS_VERSION != 'DEV') startJs = "start.js";
/**
* @private Registry để track embed_ids đã được xử lý, tránh duplicate loading
* Sử dụng window scope để persist across multiple script loads
*/
window._processedEmbedIds = window._processedEmbedIds || {};
/**
* Thêm container element naviman_app vào đầu body nếu chưa tồn tại.
*
* Container này dùng để chứa toàn bộ UI của Naviplus.
* Chỉ thêm một lần, không tạo duplicate elements.
*/
navistart.addNavimanApp = function() {
// Đã thử đặt style="display: none;" - Không chạy tốt vì lý do nào đó, tìm cách khác
if (!document.getElementById("naviman_app")) document.body.insertAdjacentHTML("afterbegin", '
');
/* Theme có body là CSS Grid (họ Dawn: `grid-template-rows: auto auto 1fr auto`) coi div này
là 1 grid item đứng ĐẦU → mọi section theme dịch xuống 1 track, `1fr` của rơi vào
header → trang ngắn hiện khoảng trống lớn dưới header. Đẩy nó ra hàng ngầm SAU hàng khai
báo cuối: không chiếm track của theme nữa. Chỉ đổi grid-row (không đụng display — cơ chế
chống CLS `.naviman_app{display:none}` và FixGoogleApp vẫn y cũ); body không phải grid
thì trình duyệt bỏ qua thuộc tính này → 0 pixel thay đổi. */
var app = document.getElementById("naviman_app");
if (app && !app.style.gridRow) app.style.gridRow = "-1 / span 1";
};
/**
* Tìm script element hiện tại đang được thực thi.
*
* Ưu tiên sử dụng document.currentScript (standard API).
* Fallback: tìm script cuối cùng có src chứa startJs nếu currentScript không khả dụng.
*
* @returns {HTMLScriptElement|null} Script element hiện tại hoặc null nếu không tìm thấy
*/
navistart.findCurrentScript = function() {
let s = document.currentScript;
// document.currentScript chỉ đáng tin trong lượt chạy đồng bộ ban đầu của start.js.
// Khi liveQueue (armLiveQueue) hijack _navi_setting.push và script KHÁC trên trang
// (vd inline embed snippet) gọi push sau đó, currentScript lúc này là script khác
// đó (thường không có 'src') — phải fallback tìm đúng thẻ script start.js thật.
if (!s || !s.getAttribute('src') || s.getAttribute('src').indexOf(startJs) === -1) {
const sc = document.querySelectorAll('script[src*="' + startJs + '"]');
if (sc.length) s = sc[sc.length - 1];
}
return s;
};
/**
* Lấy giá trị version từ attribute của script element.
*
* Xử lý đặc biệt cho attribute 'src':
* - Parse version từ query parameter v=...
* - VD: 'start.js.php?v=1.0&other=1' -> '1.0'
*
* Với các attribute khác: trả về giá trị trực tiếp.
*
* @param {HTMLScriptElement} s - Script element
* @param {string} attr - Tên attribute cần lấy ('src', 'embed_id', etc.)
* @returns {string|null} Giá trị version hoặc null nếu không tìm thấy
*/
navistart.getVersionFromScript = function(s, attr) {
if (!s) return null;
const val = s.getAttribute(attr);
if (val === null) return null;
return attr === 'src' ? (val.match(/[?&]v=([^&]+)/) || [])[1] || null : val;
};
/**
* Khởi tạo DOM environment cho Naviplus.
*
* Chỉ thực hiện một lần trong toàn bộ session.
* Thêm naviman_app container vào body.
*
* Nếu document.body đã sẵn sàng: thêm ngay lập tức
* Nếu chưa: sử dụng MutationObserver để đợi body được tạo
*/
navistart.initDOM = function() {
if (window._NAVIPLUS_APP_LOADED) return;
window._NAVIPLUS_APP_LOADED = true;
if (document.body) {
navistart.addNavimanApp();
} else {
new MutationObserver((m, o) => {
if (document.body) {
navistart.addNavimanApp();
o.disconnect();
}
}).observe(document.documentElement, { childList: true });
}
};
/**
* Copy các attributes từ naviSetting vào script element.
*
* Luôn set các attributes cơ bản: embed_id, shop, env
* Chỉ set các attributes nâng cao (not_sticky, embed_title, etc.)
* khi embed_id không rỗng (có nghĩa là có embed thực sự).
*
* @param {HTMLScriptElement} script - Script element cần set attributes
* @param {Object} naviSetting - Object chứa các setting
*/
navistart.copyAttribute = function(script, naviSetting) {
script.setAttribute('embed_id', navistart.getNaviSetting(naviSetting, 'embed_id', ''));
script.setAttribute('shop', navistart.getNaviSetting(naviSetting, 'shop', ''));
script.setAttribute('token', navistart.getNaviSetting(naviSetting, 'token', ''));
script.setAttribute('env', navistart.getNaviSetting(naviSetting, 'env', ''));
script.setAttribute('multisite', navistart.getNaviSetting(naviSetting, 'multisite', ''));
if(navistart.getNaviSetting(naviSetting, 'embed_id', '') != '') {
script.setAttribute('not_sticky', navistart.getNaviSetting(naviSetting, 'not_sticky', true));
script.setAttribute('embed_title', navistart.getNaviSetting(naviSetting, 'embed_title', ''));
script.setAttribute('embed_is_full', navistart.getNaviSetting(naviSetting, 'embed_is_full', false));
script.setAttribute('embed_margin', navistart.getNaviSetting(naviSetting, 'embed_margin', '0 0 0 0'));
}
};
/**
* Set defer attributes cho script element.
*
* Loại bỏ async attribute (nếu có) và set defer = true.
* Điều này đảm bảo script sẽ load và execute theo thứ tự,
* sau khi DOM đã được parse xong.
*
* @param {HTMLScriptElement} script - Script element cần set defer
*/
/**
* Validate URL dành riêng cho UI Generator scripts.
*
* Kiểm tra các điều kiện cơ bản của URL và log với context cụ thể
* cho UI generator loading.
*
* @param {*} url - URL của UI generator script cần validate
* @returns {boolean} true nếu URL valid, throw error nếu invalid
* @throws {Error} Nếu URL không valid
*
* @example
* navistart.validateUIgenUrl('https://cdn.example.com/uigen.js');
* // Returns: true (nếu valid)
* // Throws: Error (nếu invalid)
*/
navistart.validateUIgenUrl = function(url) {
if (!url || typeof url !== 'string' || url.trim() === '') {
console.error("loadUIGenJS: Invalid URL", url);
return false;
}
return true;
};
/**
* Fallback mechanism khi script load thất bại.
*
* Tạo script backup từ CDN khác và append vào head.
* Kiểm tra duplicate để tránh tạo multiple scripts giống nhau.
*
* @param {string} scriptSrc - URL của script thất bại
* @param {HTMLScriptElement} currentScript - Script element hiện tại
* @param {string} version - Version của app (VD: 'DEV', '1.0', etc.)
*/
navistart.failOver = function (scriptSrc, failedScript, version) {
console.warn("[Navi+] Load failed, fallback:", scriptSrc);
// ---- Build fallback URL ----
var backupVersion = version || "live-999";
var backupSrc = "https://flov.b-cdn.net/live/" + backupVersion + "/uigen.min.js";
if (_NAVIPLUS_VERSION == 'DEV')
backupSrc = "https://dev-shopify.naviplus.app/naviplus/frontend/uigen_flov.js.php";
if (!failedScript) {
console.error("[Navi+] Failover aborted: failedScript is null");
return;
}
// ---- Identity by embed_id ----
var currentEmbedId = failedScript.hasAttribute('embed_id')
? String(failedScript.getAttribute('embed_id'))
: null;
// ---- Check existing fallback scripts ----
// Only skip if we have a WORKING fallback script with same embed_id
var scripts = document.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
var s = scripts[i];
if (!s.src) continue;
if (!s.src.includes("/uigen.min.js")) continue;
var existingEmbedId = s.getAttribute("embed_id");
// Check if this is the same embed_id AND the script is actually working
if (currentEmbedId !== null && existingEmbedId === currentEmbedId) {
// Check if script is loaded and working (has navistart object)
if (typeof window.navistart !== 'undefined' && window.navistart.initialized) {
console.warn("[Navi+] Working fallback already exists for embed_id:", currentEmbedId, "skip:", backupSrc);
return;
} else {
console.warn("[Navi+] Found existing fallback script but it's not working, will create new one");
// Continue to create new fallback since existing one is broken
}
}
}
// ---- Create fallback script ----
var backupScript = document.createElement("script");
// ---- Copy attributes safely (NamedNodeMap) ----
var attrs = failedScript.attributes;
for (var j = 0; j < attrs.length; j++) {
var attr = attrs[j];
if (!attr || !attr.name) continue;
if (attr.name === "src" || attr.name === "onerror") continue;
backupScript.setAttribute(attr.name, attr.value);
}
// ---- Apply src & defer ----
backupScript.src = backupSrc;
navistart.setAttributeDefer(backupScript);
// ---- Mark this script as a fallback attempt ----
backupScript.setAttribute('data-naviplus-fallback', 'true');
// ---- Fallback failure logging ----
backupScript.onerror = function () {
console.error("[Navi+] Fallback uigen failed:", {
embed_id: currentEmbedId,
src: backupSrc
});
// Mark this script as failed so future checks know it's not working
backupScript.setAttribute('data-naviplus-failed', 'true');
};
// ---- Success callback ----
backupScript.onload = function () {
console.log("[Navi+] Fallback uigen loaded successfully:", backupSrc);
};
// ---- Append ----
document.head.appendChild(backupScript);
};
/**
* Load thư viện TLDTS (Top Level Domain TypeScript) nếu cần thiết.
*
* TLDTS được sử dụng để parse domain một cách chính xác.
* Chỉ load khi:
* - Environment không phải "shopify"
* - Thư viện tldts chưa có sẵn
*
* @param {string} env - Environment hiện tại ('shopify', 'woocommerce', etc.)
*/
navistart.loadTLDTS = function(env) {
if (env !== "shopify" && !window.tldts) {
const script = document.createElement("script");
script.src = "https://cdn.jsdelivr.net/npm/tldts/dist/tldts.min.js";
script.async = true;
document.head.appendChild(script);
}
};
// NAVI01347. Start
/* NAVI01347-flag — market có prefetch info.json sớm trong start.js không (Shopify + Global thường).
wp/demo (shop không phải domain chuẩn) và wix KHÔNG prefetch → giữ nguyên hành vi cũ ở các chỗ gọi.
Một nguồn duy nhất cho điều kiện này: khối prefetch info + quyết định thời điểm preload font. */
navistart.prefetchesShopInfo = function(env) {
return env === 'shopify' || (env !== 'wp' && env !== 'demo' && env !== 'wix');
};
/* Công tắc "preload font ĐỢI info.json để đọc cờ `font_preload: 0` theo shop" (job flag).
ĐỢT GOLIVE 1 = TẮT (false): mọi market preload remixicon.woff2 NGAY trong khối preconnect y như prod trước
NAVI01347 → nhóm chứng của A/B gói icon đúng là "hành vi hôm nay" (review V1 C2: đợi info làm icon trễ
+~160 ms ở 4G cho 92% shop). Phía server vẫn sinh key `font_preload` (vô hại) để đợt sau chỉ cần đổi hằng này
thành true rồi golive start.js. `window.NAVI_FONT_PRELOAD_AFTER_INFO = true` (trang tự đặt trước start.js) bật
thử cho riêng 1 trang — dùng cho test tự động (flag/jstest) và kiểm tay trên store. */
navistart.FONT_PRELOAD_AFTER_INFO = false;
/* TRUE = trang này preload font SAU info.json (chỉ market có prefetch info + công tắc trên bật). */
navistart.fontPreloadAfterInfo = function(env) {
var on = navistart.FONT_PRELOAD_AFTER_INFO === true || window.NAVI_FONT_PRELOAD_AFTER_INFO === true;
return on && navistart.prefetchesShopInfo(env);
};
/* NAVI01347-flag — chèn font RemixIcon, TỐI ĐA 1 lần/trang (nhiều entry _navi_setting,
hẹn giờ dự phòng, then info.json… gọi trùng đều vô hại). `window.NAVI_FONT_PRELOAD === false` (trang tự đặt
trước start.js) vẫn tắt được tay như trước. href phải khớp TUYỆT ĐỐI URL @font-face trong remixicon.css
(kể cả ?t=…) — xem chú thích biến remixiconWoff2 trong start.js.php. */
navistart.preloadRemixFont = function(href) {
if (window._naviFontPreloaded || window.NAVI_FONT_PRELOAD === false) return;
/* NAVI01347-D2: trang đang dùng gói icon theo shop (start/IconPack.js) → font đầy đủ KHÔNG cần. Gói lỗi thì
NaviIconPack chuyển state 'full' TRƯỚC rồi mới gọi lại hàm này → lúc đó preload chạy bình thường. */
if (window._naviIconPack && window._naviIconPack.usingPack()) return;
window._naviFontPreloaded = true;
var l = document.createElement('link');
l.rel = 'preload'; l.as = 'font'; l.type = 'font/woff2';
l.href = href; l.crossOrigin = 'anonymous';
document.head.appendChild(l);
};
/* NAVI01347-flag — shop TẮT preload (icon `ri-` chỉ nằm ở chỗ mở sau: ngăn kéo Slide, popup cấp 2/3) vẫn cần font
sẵn khi khách MỞ menu lần đầu. Nạp nhẹ SAU sự kiện load + lúc rảnh: không tranh băng thông first paint.
Dùng document.fonts.load (đi qua @font-face của remixicon.css, cùng URL/cache) thay vì để
không sinh cảnh báo "preloaded but not used" trên console khách. CSS chưa có / API thiếu → bỏ qua, font
vẫn tự tải lười như bình thường khi icon hiện ra. */
navistart.warmRemixFontLater = function() {
if (window._naviFontWarmArmed || !document.fonts || !document.fonts.load) return;
if (window._naviIconPack && window._naviIconPack.usingPack()) return; /* NAVI01347-D2: gói icon đã có font */
window._naviFontWarmArmed = true;
var go = function () {
var run = function () { try { document.fonts.load('16px remixicon').catch(function () {}); } catch (e) {} };
if (window.requestIdleCallback) window.requestIdleCallback(run, { timeout: 3000 }); else setTimeout(run, 1000);
};
if (document.readyState === 'complete') go(); else window.addEventListener('load', go, { once: true });
};
/**
* Lấy naviSetting từ queue _navi_setting.
*
* Xử lý queue các config đã được push vào window._navi_setting
* và trả về config đầu tiên (nếu có).
*
* @returns {Object|null} Config object từ queue hoặc null nếu queue rỗng
*/
navistart.getNaviSettingFromQueue = function() {
const queue = window._navi_setting || [];
if (queue.length > 0) {
return queue.shift();
}
return null;
};
/**
* Cập nhật shop và thay thế placeholder {shop} trong URLs tài nguyên.
*
* Nếu shop có giá trị:
* - Cập nhật _NAVIPLUS.SHOP
* - Thay thế {shop} trong tất cả URLs trong _NAVIPLUS.VARS
*
* @param {string} shop - Tên shop đã được chuẩn hóa
* @param {Object} naviplus - Object _NAVIPLUS chứa SHOP và VARS
*/
navistart.updateShopAndResources = function(shop, naviplus) {
if (shop) {
naviplus.SHOP = shop;
naviplus.VARS = naviplus.VARS.map(url =>
typeof url === 'string' && url.includes('{shop}')
? url.replace('{shop}', shop)
: url
);
}
};
/**
* Kiểm tra queue _navi_setting có còn phần tử nào sau 3 giây không.
* Chỉ setup validation 1 lần duy nhất trong toàn bộ session.
* Dùng để detect naviSettings bị bỏ sót không được xử lý.
*/
navistart.checkQueueEmpty = function() {
if (!window._NAVIPLUS_QUEUE_VALIDATION_SETUP) {
window._NAVIPLUS_QUEUE_VALIDATION_SETUP = true;
setTimeout(function() {
var remainingQueue = window._navi_setting || [];
if (remainingQueue.length > 0) {
console.error("ERROR: Unprocessed naviSettings found in queue after 5 seconds:", {
remainingCount: remainingQueue.length,
remainingItems: remainingQueue,
processedEmbedIds: window._processedEmbedIds || {}
});
}
}, 5000);
}
};
/**
* Đặt attribute defer cho thẻ script và đảm bảo không dùng async.
* Dùng để script tải tuần tự, after DOM hoàn tất.
* IMPORTANT: Theo như ChatGPT nói thì cái defer này ko có tác dụng gì cả.
*/
navistart.setAttributeDefer = function(script) {
script.removeAttribute('async');
script.async = false;
script.defer = true;
};
/**
* Khởi tạo và load tất cả tài nguyên cần thiết cho Naviplus.
*
* Phân loại và load các loại tài nguyên:
* - JSON files: sử dụng loadJSON
* - CSS files: sử dụng loadCSS (có version nếu là uigen)
* - JS files: sử dụng loadJSFunc callback (có version nếu là uigen)
*
* @param {string|string[]} vars - URL hoặc array các URLs cần load
* @param {Object} naviSetting - Setting object để truyền vào JS loader
* @param {function} loadJSFunc - Function để load JavaScript files
*
* @example
* navistart.initResources([
* 'style.css',
* 'uigen.js',
* 'config.json'
* ], setting, customJSLoader);
*/
navistart.initResources = function(vars, naviSetting, loadJSFunc) {
const cs = navistart.findCurrentScript();
if (!cs) return;
const ver = navistart.getVersionFromScript(cs, 'src');
const resources = Array.isArray(vars) ? vars : [vars];
resources.forEach(url => {
if (!url || typeof url !== 'string') return;
const isUigen = url.includes('/uigen.js') || url.includes('/uigen.css');
if (url.includes('.json')) {
navistart.loadJSON(url);
} else if (url.includes('.css')) {
navistart.loadCSS(url, isUigen ? ver : null);
} else if (url.includes('.js') || url.includes('javascript')) {
if (loadJSFunc && typeof loadJSFunc === 'function') {
loadJSFunc(url, isUigen ? ver : null, naviSetting);
}
}
});
};
/**
* Kiểm tra shop có hợp lệ để sử dụng Naviplus không.
* - Nếu env là "shopify": bỏ qua kiểm tra (trả true).
* - Nếu env khác "shopify": shop phải trùng với root domain của trang hiện tại.
* (chuẩn hóa cả 2 theo quy tắc normalizeDomainSync)
* In log trạng thái các bước kiểm tra cho gỡ lỗi.
*
* @param {string} shop - Tên shop hoặc domain.
* @param {string} env - Môi trường platform (shopify, woocommerce, v.v.).
* @returns {boolean} - true nếu hợp lệ, false nếu không hợp lệ.
*/
navistart.isValidatedShop = function(shop, env) {
// Wix: shop=siteId (GUID) không phải domain thật → skip domain check như WP
if (env === 'wix') {
return true;
}
// WordPress SSO: bỏ qua domain check vì shop là wp_TOKEN, không phải domain thật
if (WpMarket.isActive(env)) {
console.log('[Navi+ WP] Skip domain validation. shop:', shop, '| env:', env);
return true;
}
// Demo mode: bỏ qua domain check, cho phép preview trên mọi domain
if (typeof DemoMarket !== 'undefined' && DemoMarket.isActive(env)) {
console.log('[Navi+ Demo] Skip domain validation. shop:', shop, '| env:', env);
return true;
}
if (env !== "shopify") {
var shopRoot = navistart.normalizeDomainSync(shop);
var currentDomain = navistart.normalizeDomainSync(window.location.hostname);
if (shopRoot !== currentDomain) {
console.error("Shop not valid: ", {
shop,
env,
currentDomain
});
return false;
}
}
return true;
};
/**
* Lấy naviSetting một cách tiện dụng, đảm bảo tương thích cả cách cũ (gắn attribute trực tiếp trên thẻ script)
* lẫn cách mới (push vào queue _navi_setting hoặc naviplusSetting).
* - Ưu tiên lấy qua attribute trên script nếu có (giữ cho các shop cũ không bị lỗi).
* - Nếu không, fallback sang lấy từ hàng đợi (queue) hiện đại.
* - Có cơ chế chống trùng lặp embed_id để tránh load lại nhiều lần.
*
* @returns {Object|null} setting object chứa thông tin shop, env, embed_id, lang, ver, mode (nếu có)
*/
navistart.getNaviSettingCompat = function() {
var curScript = document.currentScript;
if (!curScript) {
var scripts = document.getElementsByTagName('script');
curScript = scripts[scripts.length - 1];
}
// Kiểm tra cách cũ: attribute trên script
if (curScript && curScript.hasAttribute('shop')) {
var setting = {};
['shop', 'token', 'env', 'market', 'embed_id', 'embed_title', 'embed_is_full', 'embed_margin', 'not_sticky'].forEach(function(attr) {
var val = curScript.getAttribute(attr);
if (val !== null) setting[attr] = val;
});
// Kiểm tra duplicate embed_id — chỉ dedupe khi embed_id không rỗng.
// Khi embed_id rỗng (vd: Wix global push không có embed_id cụ thể),
// bỏ qua dedupe để SPA navigation không bị block lần 2.
var embedId = setting.embed_id || '';
if (embedId && window._processedEmbedIds[embedId]) {
// Gate warn nội bộ qua _navidebug (silent ở production)
_navidebug('NAVIPLUS_START', 'Skip duplicate embed_id: ' + embedId + ' - already processed');
return null; // Trả về null để skip processing
}
if (embedId) window._processedEmbedIds[embedId] = true;
// Gate warn nội bộ qua _navidebug (silent ở production)
_navidebug('NAVIPLUS_START', 'Get setting by old way (not queue) by attribute on script');
return setting;
}
// Fallback sang queue (cách mới)
var setting = navistart.getNaviSettingFromQueue();
if (setting) {
/* QUAN TRỌNG! */
/* Nếu ko chịu khai báo shop thì lấy domain hiện tại để khởi tạo shop ****/
if(!setting["shop"] || setting["shop"] == "" )
setting["shop"] = navistart.normalizeDomainSync(window.location.hostname);
/* End of if *************************************************************/
// Kiểm tra duplicate embed_id cho queue — chỉ dedupe khi embed_id không rỗng.
var embedId = setting.embed_id || '';
if (embedId && window._processedEmbedIds[embedId]) {
// Gate warn nội bộ qua _navidebug (silent ở production)
_navidebug('NAVIPLUS_START', 'Skip duplicate embed_id from queue: ' + embedId + ' - already processed');
return null; // Trả về null để skip processing
}
if (embedId) window._processedEmbedIds[embedId] = true;
}
return setting;
};
/**
* liveQueue — xử lý entry push vào _navi_setting SAU khi start.js đã chạy.
*
* Bối cảnh (đo thật trên studytosell.com): Wix Thunderbolt chèn cả snippet push lẫn
*
* 2. Truyền embed_id qua URL param ?embed=SF-12345678
*
* Ví dụ:
* http://test.dragform.com/?embed=SF-12345678
* → Hiển thị ngay menu SF-12345678 bất kể điều kiện ẩn/hiện nào.
*
* Toàn bộ logic demo mode được gom tại đây để tránh loãng với các file khác.
* Được include sớm trong start.js, là biến global dùng được trong cả navistart lẫn uigen.js.
*/
if (typeof DemoMarket === 'undefined') var DemoMarket = {};
/**
* Danh sách domain được phép kích hoạt demo mode.
* So sánh theo hostname (không phân biệt hoa thường, bỏ qua www).
* Thêm domain mới vào đây khi cần.
*/
DemoMarket.ALLOWED_HOSTS = [
'test.dragform.com',
'test.naviplus.io',
'test.naviplus.app',
'100.105.92.91',
// TASK00222. Begin
'preview.naviplus.io',
// TASK00222. End
];
/**
* Kiểm tra hostname hiện tại có nằm trong whitelist không.
*
* @returns {boolean}
*/
DemoMarket.isAllowedHost = function() {
var host = window.location.hostname.toLowerCase().replace(/^www\./, '');
return DemoMarket.ALLOWED_HOSTS.some(function(allowed) {
return host === allowed.toLowerCase();
});
};
/**
* Kiểm tra URL có yêu cầu test trực tiếp menu không: ?test=1&embed=SF-xxx
*
* Khác demo mode: KHÔNG cần env='demo', KHÔNG cần host whitelist.
* Mục đích: khách đã embed Navi+ vào website thật của họ → mở
* https:///?test=1&embed=SF-xxx sẽ hiện menu y xì như trên
* showcase (force hiện, bỏ qua điều kiện ẩn/hiện & check plan).
* shop/token vẫn lấy từ embed thật trên trang (không truyền ?domain/?token).
*
* @returns {boolean}
*/
DemoMarket.isTestParam = function() {
// Hàm này chạy ở ĐƯỜNG NÓNG của MỌI visitor (isActive gọi đầu tiên).
// Tính năng test chỉ là phụ → bọc try/catch: bất kỳ lỗi nào (vd trình duyệt cũ
// không có URLSearchParams) cũng trả false để KHÔNG ảnh hưởng render menu của khách.
try {
if (!window.location.search || window.location.search.indexOf('test=1') === -1) return false;
if (typeof URLSearchParams === 'undefined') return false;
var params = new URLSearchParams(window.location.search);
if (params.get('test') !== '1') return false;
var embed = (params.get('embed') || '').trim();
return /^SF-\d+/.test(embed);
} catch (e) {
return false;
}
};
/**
* Phân biệt "test trên website khách" với "demo trên showcase".
* - Showcase: env === 'demo' (đã có sẵn .canvas__open, header chuẩn của showcase).
* - Site khách: có ?test=1&embed= nhưng env là shopify/global/wix → cần inject
* floating button cho slide, và mở rộng selector header cho mega/grid.
*
* @param {string} env
* @returns {boolean}
*/
DemoMarket.isOwnSiteTest = function(env) {
return DemoMarket.isTestParam() && env !== 'demo';
};
/**
* Kiểm tra xem demo mode có được kích hoạt hợp lệ không.
* Kích hoạt khi một trong hai điều kiện đúng:
* 1. ?test=1&embed=SF-xxx trên URL (test trực tiếp trên site khách — mọi domain)
* 2. env === 'demo' VÀ domain nằm trong whitelist (showcase / trang demo)
*
* @param {string} env - Giá trị env từ naviSetting
* @returns {boolean}
*/
DemoMarket.isActive = function(env) {
if (DemoMarket.isTestParam()) return true;
if (env !== 'demo') return false;
if (!DemoMarket.isAllowedHost()) {
console.warn('[Navi+ Demo] Domain không được phép dùng demo mode:', window.location.hostname);
return false;
}
return true;
};
var _DEMO_SESSION_KEY = 'navi_demo_params';
/**
* Đồng bộ params giữa URL và sessionStorage.
*
* Logic:
* - Nếu URL có bất kỳ param nào (embed, domain, token) → xoá session cũ, lưu lại từ URL
* - Nếu URL không có param nào → đọc từ session (nếu có)
*
* Gọi hàm này 1 lần sớm nhất có thể, trước khi getUrlParams().
*/
DemoMarket.syncSessionParams = function() {
var params = new URLSearchParams(window.location.search);
var hasAny = params.has('embed') || params.has('domain') || params.has('token');
if (hasAny) {
// Có param trên URL → reset session, lưu lại
var toSave = {};
if (params.get('embed')) toSave.embed = params.get('embed').trim();
if (params.get('domain')) toSave.domain = params.get('domain').trim();
if (params.get('token')) toSave.token = params.get('token').trim();
sessionStorage.setItem(_DEMO_SESSION_KEY, JSON.stringify(toSave));
}
};
/**
* Parse tất cả các URL params cần thiết cho demo mode.
* Ưu tiên URL trước, fallback sang sessionStorage nếu URL không có.
*
* - embed=SF-xxx,SF-yyy → danh sách embed_id (format SF-\d+, phân cách bằng dấu phẩy)
* - domain=naviplus.work → shop override (tùy chọn)
* - token=NAVI733440 → token (tùy chọn)
*
* @returns {{ embedIds: string[], embedId: string, domain: string, token: string }}
*/
DemoMarket.getUrlParams = function() {
var params = new URLSearchParams(window.location.search);
// Đọc session fallback
var session = {};
try { session = JSON.parse(sessionStorage.getItem(_DEMO_SESSION_KEY) || '{}'); } catch(e) {}
var embedRaw = (params.get('embed') || session.embed || '').trim();
// Parse danh sách, lọc chỉ giữ format SF-\d+ hợp lệ
var embedIds = embedRaw.split(',').map(function(s) { return s.trim(); }).filter(function(s) { return /^SF-\d+$/.test(s); });
return {
embedIds: embedIds,
embedId: embedIds[0] || '', // backward compat: dùng cái đầu tiên cho all.json
domain: (params.get('domain') || session.domain || '').trim(),
token: (params.get('token') || session.token || '').trim(),
};
};
/**
* Kiểm tra embed_id có nằm trong danh sách được phép hiển thị không.
* Nếu embedIds rỗng → hiện tất cả (không filter).
*
* @param {string} embedId
* @returns {boolean}
*/
DemoMarket.isEmbedAllowed = function(embedId) {
var p = DemoMarket.getUrlParams();
if (p.embedIds.length === 0) return true;
return p.embedIds.indexOf(embedId) !== -1;
};
/**
* Inject các params từ URL vào naviSetting.
* - embed_id : lấy từ ?embed=
* - shop : lấy từ ?domain= nếu có, không thì giữ nguyên (domain hiện tại)
* - token : lấy từ ?token= nếu có
* - not_sticky: false để không bị ẩn
*
* @param {Object} naviSetting - Setting object hiện tại (sẽ bị mutate)
* @returns {Object} naviSetting đã được bổ sung
*/
DemoMarket.applyToNaviSetting = function(naviSetting) {
DemoMarket.syncSessionParams();
var p = DemoMarket.getUrlParams();
if (!p.embedId) {
console.warn('[Navi+ Demo] Demo mode active nhưng không có ?embed=SF-xxx trên URL');
return naviSetting;
}
// Nhiều embed_id → fetch all.json rồi filter, không truyền embed_id cụ thể
naviSetting['embed_id'] = p.embedIds.length === 1 ? p.embedId : '';
naviSetting['not_sticky'] = false;
if (p.domain) naviSetting['shop'] = p.domain;
if (p.token) naviSetting['token'] = p.token;
console.log('[Navi+ Demo] active | embeds:', p.embedIds, '| shop:', naviSetting['shop']);
return naviSetting;
};
/**
* Trả về shopinfo giả để bypass getShopInfo() trong demo mode.
* update_version = số random mỗi lần gọi (TASK00713, 2026-08-26 — trước đó cố định "0") → URL JSON
* `domain.SF-xxx.json?v=` LUÔN ĐỔI giữa các lần load, tự bust cache EDGE của CDN
* (`cdn.naviplus.app`). Trước đây hardcode "0" khiến URL đứng yên vĩnh viễn — code đã né được 2 tầng
* cache PHÍA CLIENT (IndexedDB + browser HTTP cache, qua `cache:"no-store"` ở uigen.js.php) nhưng
* "no-store" chỉ chặn trình duyệt tự dùng lại cache của CHÍNH NÓ, không gửi header buộc CDN EDGE bỏ
* qua cache của edge đó — với URL cố định, edge cache lần đầu gặp URL này trả mãi bản đó cho MỌI
* client, bất kể no-store/incognito phía trình duyệt (Khôi báo qua `?test=1&embed=` không thấy tab
* mới thêm dù đã Save, xác nhận bằng cách đọc thẳng `window.navimanData` — data ĐẦU VÀO app nhận đã
* thiếu sẵn trước khi tới bất kỳ thuật toán render nào).
*
* @returns {Object} shopinfo mặc định
*/
DemoMarket.getFakeShopInfo = function() {
return {
update_version: String(Math.floor(Math.random() * 1000000000)),
plan: "",
debug_mode_enabled: true, // TASK00533 — demo naviplus.io luôn cho phép "Try Navi+ menus"/Navi+ Live, không phải shop thật nên không áp toggle của khách
analytics_enabled: false // TASK00819 — demo naviplus.io không phải shop thật, không tính vào số liệu Analytics (thay cho entry "naviplus.io" trong blackListDomains cũ)
};
};
/**
* Load từng embed_id riêng lẻ rồi gọi callback cho mỗi cái.
* Dùng trong uigen.js để tách logic fetch ra khỏi initNaviplusApp.
*
* @param {Object} opts
* @param {string} opts.cdnJsonBase - Base URL của CDN JSON (naviplusCDNJson)
* @param {string} opts.shop - Shop đã được normalize
* @param {string} opts.token - Token
* @param {Function} opts.standardize - navihelper.standardizeDomain
* @param {Function} opts.onLoaded - callback(json, fakeShopInfo) cho mỗi embed
* @param {Object} opts.fakeShopInfo - shopinfo giả
*/
DemoMarket.loadEmbeds = function(opts) {
var p = DemoMarket.getUrlParams();
// Phase 2.5: EDIT popup "Try Navi+ menus" (debugmode.js) cho phép đổi 1 menu
// demo sang mẫu thuộc STORE KHÁC domain đang demo (29/29 mẫu visible thuộc 4 store riêng theo
// loại — navi-tabbar/navi-slidemenu/navi-megamenu/navi-fab.myshopify.com — KHÔNG thuộc naviplus.io,
// xem TASKS/TASK00519.md History 2026-07-23 "Fable review Phase 0-2..."). debugmode.js ghi map
// phẳng embed_id → {d:domain, t:token} vào sessionStorage NGAY TRƯỚC KHI navigate (chỉ khi own-site
// test đã chọn mẫu khác qua EDIT popup) — đọc lại ở đây để build đúng URL JSON riêng cho TỪNG embed.
// Không có entry cho 1 eid (mọi trường hợp khác — khách thật dùng ?test=1&embed= tự test menu của
// họ, hoặc demo chưa đổi mẫu nào) → giữ NGUYÊN opts.standardize(opts.shop, opts.token) như cũ, không
// đổi 1 byte hành vi hiện có.
var embedDomainMap = {};
try {
var _rawEmbedDomains = sessionStorage.getItem('_naviplus_try_menus_embed_domains');
if (_rawEmbedDomains) embedDomainMap = JSON.parse(_rawEmbedDomains) || {};
} catch (e) { embedDomainMap = {}; }
p.embedIds.forEach(function(eid) {
// TASK00519: prefix riêng cho embed đã đổi mẫu sang store khác — xem khối đọc map phía trên.
var _domainEntry = embedDomainMap[eid];
var prefix = _domainEntry ? opts.standardize(_domainEntry.d, _domainEntry.t || '') : opts.standardize(opts.shop, opts.token);
var url = opts.cdnJsonBase + '/' + prefix + '.' + eid + '.json?v=0';
// TASK00617/TASK00721: URL luôn ?v=0 (cố định) → không có Cache-Control trên response JSON này
// khiến trình duyệt tự áp heuristic caching, kẹt bản cũ tới khi khách publish xong vẫn không thấy
// đổi. no-store ép luôn lấy bản mới nhất từ CDN, đúng mục đích "test" — không cache dài.
fetch(url, { cache: 'no-store' }).then(function(r) {
if (!r.ok) throw new Error("HTTP error " + r.status);
return r.json();
}).then(function(json) {
// TASK01139: Navi+ Live đổ menu thật của khách vào mẫu (DemoContent chỉ có trong bundle uigen, không có ở start.js)
if (typeof DemoContent !== 'undefined') json = DemoContent.apply(json);
opts.onLoaded(json, opts.fakeShopInfo);
}).catch(function(err) {
console.error('[Navi+ Demo] Failed to load', eid, err);
});
});
};
/**
* Override vị trí chèn (publishToPlace) cho "own site test" (isOwnSiteTest) — dùng bởi feature
* "Try Navi+ menus" (debugmode.js) để chèn Mega ĐÚNG theo theme khách đang xem thay vì fallback
* selector chung chung. Ghi bởi debugmode.js (sessionStorage, key TRY_MENUS_PLACEMENT_SESSION_KEY —
* PHẢI trùng _DEMO_PLACEMENT_KEY bên dưới), đọc bởi uigen_func.js.php ngay tại nhánh
* DemoMarket.isOwnSiteTest(). KHÔNG có override → giữ nguyên hành vi fallback cũ (an toàn cho mọi
* khách hàng đang dùng ?test=1&embed= để tự test menu thật của họ, không đổi gì).
*
* Shape lưu trong sessionStorage: { "": { selector: "...", kind: "1"|"2"|"3" } }
*/
var _DEMO_PLACEMENT_KEY = 'navi_demo_placement_override';
/**
* @param {string} menuKindClass - vd "SECTION_DESKTOP_MEGAMENU"
* @returns {{selector:string, kind:string}|null}
*/
/* @param {string} [embedId] — ưu tiên entry theo CHÍNH embed (map["SF-xxx"]) trước entry theo kind:
Navi+ Live "Kiểm tra Selector" chạy 2 Mega Desktop cùng lúc ở 2 chỗ (full dưới header + menu ngắn
thay nav) → placement không thể chỉ keyed theo kind. Không truyền/không có entry embed → y như cũ. */
DemoMarket.getPlacementOverride = function(menuKindClass, embedId) {
try {
var raw = sessionStorage.getItem(_DEMO_PLACEMENT_KEY);
if (!raw) return null;
var map = JSON.parse(raw);
if (!map) return null;
if (embedId && map[embedId]) return map[embedId];
return map[menuKindClass] ? map[menuKindClass] : null;
} catch (e) {
return null;
}
};
/**
* Proposal Live (TASK01142) — khách bấm nút trong email proposal là thấy menu ĐỀ XUẤT chạy thật trên chính website của họ.
* Link: https:///?test=1&embed=SF-a,SF-b,SF-c&nvp=
*
* An toàn:
* - Chỉ có hiệu lực khi isTestParam() (URL đã có ?test=1&embed=) → visitor thường không bao giờ vào nhánh này.
* - nvp chỉ là MÃ (hex 16-40 ký tự), KHÔNG nhận URL: file luôn đọc từ thư mục cố định của Navi+ trên CDN
* (PROPOSAL_BASE, chỉ Navi+ ghi được) → không ai nhét được JSON/HTML lạ vào storefront khách qua link.
* - Mã proposal là file BẤT BIẾN (đổi nội dung = mã mới) → không dính bẫy cache ?v=0 của loadEmbeds.
*
* File proposal (sinh bởi microservices/menuProposal/live_publish.php):
* { v:1, shop, created, menus:[{id, embed_id, name, shop, data:{setting, dragdrop}, menuKind}],
* placement:{ "": {selector, kind, level1BackgroundHide?} | [ứng viên theo thứ tự ưu tiên],
* "CONTEXT_SLIDE": {trigger: ""} } }
*/
DemoMarket.PROPOSAL_BASE = 'https://cdn.naviplus.app/naviplus/data/proposal/';
/**
* Lấy mã proposal từ URL (?nvp=). Rỗng nếu không phải link test hoặc mã sai định dạng.
*
* @returns {string}
*/
DemoMarket.getProposalId = function() {
try {
if (!DemoMarket.isTestParam()) return '';
var id = (new URLSearchParams(window.location.search).get('nvp') || '').trim().toLowerCase();
return /^[a-f0-9]{16,40}$/.test(id) ? id : '';
} catch (e) {
return '';
}
};
/**
* Chọn vị trí chèn cho từng menu đề xuất rồi ghi vào đúng key sessionStorage mà getPlacementOverride() đọc.
* placement[embed_id] = 1 ứng viên {selector, kind, level1BackgroundHide?} HOẶC mảng ứng viên theo thứ tự ưu tiên
* (vd [thay main menu, chèn dưới header]) — lấy ứng viên ĐẦU TIÊN có selector khớp DOM trang hiện tại.
* Lý do thử trên DOM thật: registry theo theme có thể lệch với theme đã customize (holisticway: Reformation
* dùng thay vì theme-header), selector không khớp sẽ làm Mega chờ 10s rồi không hiện.
* Không ứng viên nào khớp → bỏ, runtime dùng fallback chung. Ứng viên thắng có level1BackgroundHide → ghi
* đúng field đó vào setting của menu tương ứng (chỉ field này; header trong suốt cần nền level-1 trong suốt
* khi Mega thay chỗ main menu — cùng quy ước Navi+ Live chế độ Replace).
* Ghi đè toàn bộ map (tab mở từ email là phiên proposal riêng, không trộn với lựa chọn Navi+ Live cũ).
*
* @param {Object} placement
* @param {Array} menus - mảng menu của proposal (được sửa tại chỗ field level1BackgroundHide)
*/
DemoMarket._proposalChosen = {}; // vị trí đã khớp DOM thật: {place:{s,k,h}, trigger} — mang sang app admin ở nút "Add these menus"
DemoMarket.applyProposalPlacement = function(placement, menus) {
DemoMarket._proposalChosen = {};
try {
var map = {};
Object.keys(placement || {}).forEach(function(key) {
var list = Array.isArray(placement[key]) ? placement[key] : [placement[key]];
for (var i = 0; i < list.length; i++) {
var p = list[i];
if (!p) continue;
/* Mobile Menu (key "CONTEXT_SLIDE"): entry {trigger} = selector nút ☰ THẬT của theme — uigen_func.js.php
nối nó vào publishTriggerIDClass (bấm ☰ của theme mở Mobile Menu đề xuất). Cùng quy tắc: chỉ nhận khi
khớp ĐÚNG 1 phần tử DOM thật. Không có {trigger} → như cũ (cần selector chèn). */
if (typeof p.trigger === 'string' && p.trigger) {
try {
// đúng 1 phần tử: renderer bind MỌI phần tử khớp (querySelectorAll) → selector rộng sẽ chiếm click của link khác
if (document.querySelectorAll(p.trigger).length !== 1) continue;
} catch (e) {
continue;
}
map[key] = { trigger: p.trigger };
DemoMarket._proposalChosen.trigger = p.trigger;
break;
}
if (typeof p.selector !== 'string' || !p.selector) continue;
try {
if (!document.querySelector(p.selector)) continue;
} catch (e) {
continue; // selector không hợp lệ
}
map[key] = { selector: p.selector, kind: String(p.kind || '2') };
DemoMarket._proposalChosen.place = { s: p.selector, k: String(p.kind || '2'), h: !!p.level1BackgroundHide };
if (typeof p.level1BackgroundHide !== 'undefined') {
(menus || []).forEach(function(m) {
if (m.embed_id === key) m.data.setting.level1BackgroundHide = p.level1BackgroundHide;
});
}
break;
}
});
if (Object.keys(map).length) sessionStorage.setItem(_DEMO_PLACEMENT_KEY, JSON.stringify(map));
else sessionStorage.removeItem(_DEMO_PLACEMENT_KEY);
} catch (e) {}
};
/**
* Tải file proposal rồi gọi onLoaded(menus) với mảng menu cùng dạng all.json.
* Không đi qua DemoContent.apply(): menu đề xuất đã là nội dung thật của khách, không được thay bằng dữ liệu quét.
*
* @param {string} pid
* @param {Function} onLoaded - callback(menus)
*/
DemoMarket.loadProposal = function(pid, onLoaded) {
fetch(DemoMarket.PROPOSAL_BASE + pid + '.json', { cache: 'no-store', credentials: 'omit' }).then(function(r) {
if (!r.ok) throw new Error("HTTP error " + r.status);
return r.json();
}).then(function(p) {
var menus = (p && Array.isArray(p.menus)) ? p.menus.filter(function(m) {
return m && m.data && m.data.setting && Array.isArray(m.data.dragdrop) && /^SF-\d+$/.test(m.embed_id || '');
}) : [];
if (!menus.length) throw new Error("Empty proposal");
DemoMarket.applyProposalPlacement(p.placement, menus);
return Promise.resolve(onLoaded(menus)).then(function() { DemoMarket.showProposalBar(p, pid); });
}).catch(function(err) {
console.error('[Navi+ Proposal] Failed to load', pid, err);
});
};
/**
* Thanh "đang xem thử" ở đầu trang + nút "Add these menus to my store" (TASK01151).
* Nút mở APP ADMIN Shopify của chính store (đã đăng nhập) với ?proposal= — app hiện màn xác nhận rồi mới tạo menu
* (KHÔNG cho link công khai tự ghi vào store). Kèm vị trí đã khớp thật (pl) + selector ☰ thật (tr) để menu thêm vào đúng chỗ vừa thấy.
* Chỉ vẽ trong chế độ xem thử ?nvp= → khách thường không bao giờ thấy.
*/
DemoMarket.PROPOSAL_APP_CLIENT_ID = { live: '9012f6c4203867f311edf8cc53758246', dev: '1a40137ca3fcf57dd8b32bddf82166a1' };
DemoMarket.showProposalBar = function(p, pid) {
try {
if (document.getElementById('navi-proposal-bar')) return;
var handle = String(p.shop_url || '').replace(/\.myshopify\.com$/i, '');
if (!/^[a-z0-9][a-z0-9\-]*$/i.test(handle)) return; // không biết store admin nào → không hiện nút (xem trước vẫn dùng được)
var isDev = (typeof _NAVIPLUS_VERSION !== 'undefined' && _NAVIPLUS_VERSION === 'DEV');
var cid = /^[a-f0-9]{32}$/.test(p.app_client_id || '') ? p.app_client_id : (isDev ? DemoMarket.PROPOSAL_APP_CLIENT_ID.dev : DemoMarket.PROPOSAL_APP_CLIENT_ID.live);
var qs = 'proposal=' + encodeURIComponent(pid);
var ch = DemoMarket._proposalChosen || {};
if (ch.place) qs += '&pl=' + btoa(unescape(encodeURIComponent(JSON.stringify(ch.place)))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
if (ch.trigger) qs += '&tr=' + encodeURIComponent(ch.trigger);
var addUrl = 'https://admin.shopify.com/store/' + handle + '/apps/' + cid + '?' + qs;
var st = document.createElement('style');
st.textContent = '#navi-proposal-bar{position:fixed;top:0;left:0;right:0;z-index:2147483647;display:flex;flex-wrap:wrap;align-items:center;justify-content:center;gap:8px 14px;padding:8px 12px;background:#111827;color:#fff;font:600 13.5px/1.3 system-ui,-apple-system,Segoe UI,Roboto,sans-serif;box-shadow:0 2px 14px rgba(0,0,0,.3)}'
+ '#navi-proposal-bar a,#navi-proposal-bar button{font:600 13.5px/1 system-ui,sans-serif;border-radius:7px;padding:8px 14px;text-decoration:none;cursor:pointer;border:0}'
+ '#navi-proposal-bar .npb-add{background:#fff;color:#111827}'
+ '#navi-proposal-bar .npb-x{background:transparent;color:#d1d5db;border:1px solid #4b5563}'
+ '#navi-proposal-bar span{opacity:.85;font-weight:500}'
/* màn hẹp: 1 hàng gọn (bỏ dòng chữ) để không che ☰/header của theme — chính chỗ Mobile Menu gắn vào */
+ '@media (max-width:560px){#navi-proposal-bar{flex-wrap:nowrap;gap:8px;padding:6px 10px}#navi-proposal-bar span{display:none}#navi-proposal-bar a,#navi-proposal-bar button{padding:8px 12px;font-size:13px;white-space:nowrap}#navi-proposal-bar .npb-add{flex:1;text-align:center}}';
var bar = document.createElement('div');
bar.id = 'navi-proposal-bar';
bar.innerHTML = 'Previewing suggested Navi+ menus';
var add = document.createElement('a'); add.className = 'npb-add'; add.href = addUrl; add.target = '_blank'; add.rel = 'noopener'; add.textContent = '+ Add these menus to this store';
var x = document.createElement('button'); x.type = 'button'; x.className = 'npb-x'; x.textContent = 'Exit preview';
x.addEventListener('click', function() {
try { sessionStorage.removeItem(_DEMO_PLACEMENT_KEY); sessionStorage.removeItem(_DEMO_SESSION_KEY); } catch (e) {}
window.location.href = window.location.origin + window.location.pathname;
});
bar.appendChild(add); bar.appendChild(x);
document.head.appendChild(st); document.body.appendChild(bar);
} catch (e) {}
};
/**
* NaviIconPack — NAVI01347-D2: gói icon RemixIcon THEO SHOP (Frontend, chạy trong start.js)
* ----------------------------------------------------------------------------------------
* Thay `remixicon.css` (155 KB) + `remixicon.woff2` (185 KB) đầy đủ bằng 1 file nhỏ do server sinh lúc lưu/publish
* menu: `/icons/.css` = font CẮT chỉ glyph shop dùng (data URI, có unicode-range) + đúng class
* shop dùng + mốc canh `--navi-icon-pack` ở cuối (server: app/includes/shop/iconPack.php). Đo F1: −0,86 s
* first-menu ở Fast3G, −0,34 s Slow4G.
*
* URL suy thẳng từ shop (như info.json) → chèn NGAY trong start.js, không chờ info.json.
* MỌI đường lỗi → nạp font đầy đủ như cũ (ensureFull), không bao giờ để menu mất icon:
* - gói 404 / lỗi mạng (onerror) · quá TIMEOUT chưa về · file cụt (thiếu mốc canh) · server trả gói "full"
* (công tắc NAVI_ICON_PACK_OFF / shop bị tắt / lỗi sinh) · font trong gói không giải được (status error)
* - THIẾU GLYPH: uigen gọi verify(data) với JSON menu → mỗi class `ri-` trong data phải có ::before trong gói
* (gói cũ trong cache trình duyệt sau khi khách thêm icon mới…) → thiếu 1 cái là nạp font đầy đủ.
* Font đầy đủ nạp SAU vẫn sống chung được: @font-face của gói có unicode-range, mặt đầy đủ (không range,
* khai báo sau) được trình duyệt ưu tiên → mọi icon vẽ bằng font đầy đủ, glyph y hệt.
*
* A/B đợt golive đầu: chỉ Shopify, PERCENT % shop theo hash(shop) dùng gói; còn lại = nhóm chứng (font đầy đủ,
* preload remixicon.woff2 NGAY trong khối preconnect — y hệt prod trước NAVI01347 vì công tắc
* navistart.FONT_PRELOAD_AFTER_INFO của job flag TẮT ở đợt 1). Ép tay để test: window.NAVI_ICON_PACK = true/false
* trước start.js, hoặc ?navi_icon_pack=1 / 0 trên URL. RUM (frontend/rum/navi-rum.js) gửi kèm group/state/reason.
*
* Trạng thái dùng chung cho mọi entry _navi_setting (và nếu start.js chạy 2 lần) ở window._naviIconPack:
* group 'pack' | 'control' · state 'off' | 'loading' | 'ready' | 'full' · reason (vì sao full) · std (tên shop chuẩn)
* · tReady (performance.now() lúc gói sẵn sàng, -1 nếu chưa) · usingPack() · verify(data)
*
* Tắt khẩn ≤5 phút KHÔNG cần golive: naviplus/microservices/golive/iconpack-kill.php ghi gói "full" cho mọi shop
* → client đọc mốc "full" → nạp font đầy đủ.
* ⛔ URL gói BẮT BUỘC kèm ?v=: cdn.naviplus.app cache MỌI file trong /naviplus/data/json/ 7 ngày
* (cache-control max-age=604800, cả 404; khoá cache gồm query — đo 01/11/2026, X1 cdn_probe) → không có ?v= thì gói
* 404 trước khi seed / gói cũ / gói tắt khẩn kẹt ở CDN + trình duyệt tới 7 ngày. Có ?v= → tối đa 5 phút.
*/
if (typeof NaviIconPack === 'undefined') var NaviIconPack = {};
/* % shop Shopify dùng gói (A/B theo hash shop để RUM so nhóm). 0 = tắt hẳn (công tắc khẩn bằng golive start.js),
100 = mọi shop. ⛔ Đổi số này = đổi nhóm của shop → báo người phân tích RUM. */
NaviIconPack.PERCENT = 50;
/* Hẹn giờ BẬT A/B (ms epoch UTC, đồng hồ máy khách). Trước mốc này: MỌI shop chạy như nhóm chứng (= prod hôm nay)
nhưng RUM vẫn ghi nhóm ĐƯỢC CHIA (`arm`) → có vài ngày số "TRƯỚC" của từng shop để so "từng shop trước/sau"
(review V1: chia hash lệch lượt xem 44/56, 10 shop lớn chiếm 56–65% → so gộp 2 nhóm bị shop lớn lái).
Cũng cho phép golive start.js TRƯỚC khi sinh xong gói (gói chỉ cần có trước mốc này). 0 = bật ngay khi golive.
Đổi: 1 dòng rồi golive start.js. Đồng hồ khách lệch → bật sớm/muộn vài người, gói chưa có thì 404 → font đầy đủ. */
NaviIconPack.START_AT = Date.UTC(2026, 10, 4); /* 04/11/2026 00:00 UTC (tháng tính từ 0) — mặc định theo V4, Khôi đổi được: 0 = bật ngay */
/* ⛔ Cùng phiên bản với iconPack/remixicon-4.8.0.* phía server và remixicon.css trong _NAVIPLUS.VARS */
NaviIconPack.FULL_CSS = 'https://cdn.jsdelivr.net/npm/remixicon@4.8.0/fonts/remixicon.css';
NaviIconPack.TIMEOUT = 3000;
/* Glyph ri-menu-line (U+EF3E) — glyph engine, server luôn đưa vào mọi gói → dùng để thử font giải được không.
Viết dạng escape để bundle không phụ thuộc mã hoá trang (review V1 M3). */
NaviIconPack.PROBE_CHAR = '\uef3e';
/* Mốc cache-bust ?v= của URL gói: đổi mỗi 5 phút → CDN (cache 7 ngày theo URL đầy đủ) và trình duyệt không giữ
gói cũ / 404 quá 5 phút (review V1 N6), script tắt khẩn iconpack-kill.php có tác dụng trong ≤5 phút.
Gói ~5 KB nén → tải lại mỗi 5 phút không đáng kể. Đánh đổi: mỗi shop×POP×5 phút có khách = 1 lần đọc R2
(Class B); muốn giảm đọc R2 thì tăng lên 900000 (15 phút) — tắt khẩn khi đó ≤15 phút. */
NaviIconPack.VERSION_MS = 300000;
/* FNV-1a 32-bit → 0..99. Cùng công thức phải dùng khi phân nhóm RUM phía server/báo cáo. */
NaviIconPack.bucket = function (s) {
var h = 0x811c9dc5, i;
s = String(s || '');
for (i = 0; i < s.length; i++) {
h ^= s.charCodeAt(i);
h = Math.imul(h, 0x01000193) >>> 0;
}
return h % 100;
};
/* Ép tay: window.NAVI_ICON_PACK (true/false) > ?navi_icon_pack=1/0 > null (theo A/B). */
NaviIconPack.override = function () {
if (window.NAVI_ICON_PACK === true || window.NAVI_ICON_PACK === false) return window.NAVI_ICON_PACK;
try {
var m = /[?&]navi_icon_pack=([01])(?:&|$)/.exec(location.search || '');
if (m) return m[1] === '1';
} catch (e) {}
return null;
};
/* Tên chuẩn của shop trong bucket JSON — cùng công thức _stdShop (info.json) trong start.js.php. */
NaviIconPack.stdName = function (shop, token) {
var s = String(shop || '').replace('.myshopify.com', '');
return (!token || token === '') ? s : token + '_' + s;
};
/**
* Quyết định + bắt đầu nạp gói (gọi trong start.js, trước khi preload font / nạp _NAVIPLUS.VARS).
* @returns {boolean} true = trang đang dùng gói → caller bỏ remixicon.css đầy đủ khỏi danh sách tài nguyên.
*/
NaviIconPack.start = function (env, shop, token, cdnJson, fullWoff2) {
var st = window._naviIconPack;
if (st) return st.usingPack();
var std = NaviIconPack.stdName(shop, token);
var ov = NaviIconPack.override();
/* arm = nhóm shop ĐƯỢC CHIA theo hash (không phụ thuộc giờ bật); chosen = trang này thật sự dùng gói. */
var arm = env === 'shopify' && std !== '' && NaviIconPack.bucket(std) < NaviIconPack.PERCENT ? 'pack' : 'control';
var started = !NaviIconPack.START_AT || Date.now() >= NaviIconPack.START_AT;
var chosen = ov !== null ? ov : (arm === 'pack' && started);
st = window._naviIconPack = NaviIconPack.createState(chosen && std !== '', fullWoff2);
st.std = std;
st.arm = arm;
st.forced = ov !== null; /* ép tay (test) → RUM gửi kèm để lọc bỏ khỏi phân tích */
st.env = env; /* RUM: chỉ Shopify mới có A/B (market khác luôn font đầy đủ → nhóm 'na') */
if (!st.usingPack()) return false;
try {
st.url = cdnJson + '/icons/' + std + '.css?v=' + Math.floor(Date.now() / NaviIconPack.VERSION_MS);
st.timer = setTimeout(function () { if (st.state === 'loading') st.ensureFull('timeout'); }, NaviIconPack.TIMEOUT);
var l = document.createElement('link');
l.rel = 'stylesheet';
/* CORS anonymous: dùng lại kết nối preconnect crossorigin tới cdn.naviplus.app (CDN trả
access-control-allow-origin: *) thay vì mở thêm 1 kết nối TLS (review V1 M2). */
l.crossOrigin = 'anonymous';
l.href = st.url;
l.onload = function () { try { NaviIconPack.onCssLoaded(st); } catch (e) { st.ensureFull('exception'); } };
l.onerror = function () { st.ensureFull('error'); };
document.head.appendChild(l);
} catch (e) {
/* Không chèn được gói → đánh dấu full TRƯỚC khi trả false: caller giữ remixicon.css trong VARS, preload chạy như cũ */
st.state = 'full'; st.reason = 'exception';
if (st.timer) clearTimeout(st.timer);
return false;
}
return true;
};
/* Đối tượng trạng thái window._naviIconPack (uigen chỉ gọi usingPack()/verify() — hook tuỳ chọn). */
NaviIconPack.createState = function (usePack, fullWoff2) {
var st = {
group: usePack ? 'pack' : 'control',
state: usePack ? 'loading' : 'off',
reason: '',
hash: '',
std: '',
tReady: -1,
skip: {},
pending: [],
timer: null,
fullWoff2: fullWoff2,
usingPack: function () { return st.state === 'loading' || st.state === 'ready'; },
/* Kiểm mọi class ri- trong JSON menu có glyph trong gói; gói chưa sẵn → xếp hàng. Không bao giờ ném lỗi. */
verify: function (data) {
try {
if (!st.usingPack()) return;
var s = typeof data === 'string' ? data : JSON.stringify(data);
if (!s || s.indexOf('ri-') < 0) return;
var re = /(^|[^A-Za-z0-9_-])(ri-[a-z0-9]+(?:-[a-z0-9]+)*)/g, m, toks = {};
while ((m = re.exec(s))) toks[m[2]] = 1;
if (st.state === 'loading') st.pending.push(toks);
else NaviIconPack.checkTokens(st, toks);
} catch (e) {}
},
/* Bỏ gói, nạp font đầy đủ như trước NAVI01347 (preload woff2 + remixicon.css). Gọi nhiều lần vô hại. */
ensureFull: function (reason) {
if (st.state === 'full') return;
if (st.timer) clearTimeout(st.timer);
var wasPack = st.usingPack();
st.state = 'full';
st.reason = reason || '';
st.pending = [];
if (!wasPack) return;
_navidebug('Navi+ icon pack', 'fallback → full Remix Icon font (' + st.reason + ')');
if (st.fullWoff2) navistart.preloadRemixFont(st.fullWoff2);
navistart.loadCSS(NaviIconPack.FULL_CSS, null);
}
};
return st;
};
/* CSS gói đã về: kiểm mốc canh (file trọn vẹn / không phải gói "full") rồi thử giải font. */
NaviIconPack.onCssLoaded = function (st) {
if (st.state !== 'loading') return;
var cs = getComputedStyle(document.documentElement);
var v = String(cs.getPropertyValue('--navi-icon-pack') || '').trim().replace(/^["']|["']$/g, '');
if (!v) return st.ensureFull('broken');
if (v === 'full') return st.ensureFull('server-full');
st.hash = v;
String(cs.getPropertyValue('--navi-icon-pack-skip') || '').replace(/["']/g, ' ').split(/\s+/).forEach(function (t) {
if (t) st.skip[t] = 1;
});
var ready = function () {
if (st.state !== 'loading') return;
if (st.timer) clearTimeout(st.timer);
st.state = 'ready';
try { st.tReady = Math.round(performance.now()); } catch (e) {} /* mốc "icon sẵn sàng" cho RUM */
var q = st.pending; st.pending = [];
q.forEach(function (toks) { if (st.state === 'ready') NaviIconPack.checkTokens(st, toks); });
};
if (!document.fonts || !document.fonts.load) return ready();
/* Ép giải font NGAY (data URI) → lúc uigen vẽ, face đã 'loaded' → icon hiện không chờ. Font hỏng → full. */
document.fonts.load('16px remixicon', NaviIconPack.PROBE_CHAR).then(function (faces) {
var bad = !faces || !faces.length;
(faces || []).forEach(function (f) { if (f.status === 'error') bad = true; });
if (bad) st.ensureFull('font'); else ready();
}, function () { st.ensureFull('font'); });
};
/* Mỗi token (trừ skip: class cỡ ri-2x…, chữ không phải icon) phải có ::before content trong CSS đang nạp. */
NaviIconPack.checkTokens = function (st, toks) {
var root = document.body || document.documentElement, probe = document.createElement('i'), miss = '', t, c;
probe.style.cssText = 'position:absolute;visibility:hidden;left:-9999px;top:0;';
root.appendChild(probe);
for (t in toks) {
if (st.skip[t]) continue;
/* Tên shop bắt đầu "ri-" (vd "shop":"ri-martin-smith.myshopify.com" trong all.json) không phải icon —
server chỉ quét cột data nên không đưa vào skip (review V1 M1) */
if (st.std && st.std.indexOf(t) === 0) continue;
probe.className = t;
c = getComputedStyle(probe, '::before').getPropertyValue('content');
if (!c || c === 'none' || c === 'normal') { miss = t; break; }
}
root.removeChild(probe);
if (miss) st.ensureFull('missing ' + miss);
};
/* Bỏ remixicon.css đầy đủ khỏi danh sách tài nguyên start.js khi dùng gói. */
NaviIconPack.stripFullCss = function (vars) {
return (vars || []).filter(function (u) { return u !== NaviIconPack.FULL_CSS; });
};
/** Chuẩn bị _NAVIPLUS và môi trường sử dụng ******************************************************/
(function () {
/* Thân xử lý 1 naviSetting (Bước 2 → Bước 5, giữ NGUYÊN TRẠNG từng dòng) tách thành hàm
để tái dùng: ngoài đường chạy cũ (Bước 1 bên dưới), còn được liveQueue gọi cho entry
push vào _navi_setting SAU khi start.js đã chạy xong (xem navistart.armLiveQueue). */
function processNaviSetting(naviSetting) {
// Bước 2: Lấy thuộc tính shop, env, token từ naviSetting
let shop = navistart.normalizeShop(navistart.getNaviSetting(naviSetting, 'shop', ''));
let env = navistart.getNaviSetting(naviSetting, 'env', '') || navistart.getNaviSetting(naviSetting, 'market', '');
naviSetting['env'] = env; // Đảm bảo copyAttribute truyền đúng env sang uigen.js
// NAVI01347. Start
/* RUM (rum/navi-rum.js, chỉ Shopify): bộ đệm Resource Timing mặc định 250 mục — trang Shopify nặng (nhiều ảnh) đầy trước lúc RUM
đọc mốc uigen/info/font → ghi −1, mẫu lệch về trang nhẹ (review V2 S2). Nâng 600 sớm nhất có thể; chỉ là bộ nhớ, không request.
Global/Wix/WP/demo: KHÔNG đụng (X7). */
if (env === 'shopify') { try { performance.setResourceTimingBufferSize(600); } catch (e) {} }
let token = navistart.getNaviSetting(naviSetting, 'token', '');
// Bước 2.5: WordPress SSO (env=wp) — override shop thành wp_TOKEN (domain thật không dùng)
if (WpMarket.isActive(env) && token) {
shop = WpMarket.buildShop(token);
naviSetting['shop'] = shop; // Đảm bảo copyAttribute cũng dùng shop mới
console.log('[Navi+ WP] Override shop →', shop);
console.log('[Navi+ WP] Expected JSON format: ' + cdnJson + '/' + token + '_' + shop + '.SF-XXXXXX.json');
}
// Bước 2.6: Demo mode (env=demo) — inject embed_id từ URL param ?embed=SF-xxx
if (typeof DemoMarket !== 'undefined' && DemoMarket.isActive(env)) {
DemoMarket.applyToNaviSetting(naviSetting);
}
// Bước 3: Nếu có shop, cập nhật _NAVIPLUS.SHOP và thay thế {shop} trên các url tài nguyên
navistart.updateShopAndResources(shop, _NAVIPLUS);
// Bước 4: Nếu không phải Shopify và chưa có tldts, load thư viện tldts (async) từ CDN
navistart.loadTLDTS(env);
// Bước 5: Nếu shop hợp lệ, khởi tạo Navi+
var isValid = navistart.isValidatedShop(shop, env); // WpMarket.isActive(env) bypass is inside isValidatedShop
if( isValid ) {
// Test trực tiếp trên site khách (?test=1&embed=): chỉ cho 1 instance render menu test.
// Trang có nhiều embed → các instance còn lại dừng tại đây, tránh menu test bị vẽ trùng
// và đảm bảo không có menu nào khác hiển thị trong chế độ test.
// Bọc typeof + try/catch: tính năng phụ, lỗi gì cũng KHÔNG được chặn start menu của khách.
try {
if (typeof DemoMarket !== 'undefined' && DemoMarket.isTestParam()) {
if (window._naviTestModeRendered) return;
window._naviTestModeRendered = true;
}
} catch (e) {}
// NAVI01347. Start
/* D2 — gói icon theo shop (start/IconPack.js): quyết định NGAY, trước mọi preload font và trước khi nạp
_NAVIPLUS.VARS. Dùng gói → bỏ remixicon.css đầy đủ khỏi danh sách; preload remixicon.woff2 tự bỏ qua
(navistart.preloadRemixFont kiểm usingPack). Gói lỗi/thiếu glyph → NaviIconPack tự nạp lại font đầy đủ.
try/catch: tính năng tối ưu, lỗi gì cũng không được chặn đường vẽ menu (nhánh lỗi = font đầy đủ như cũ). */
try {
if (NaviIconPack.start(env, shop, token, cdnJson, remixiconWoff2)) _NAVIPLUS.VARS = NaviIconPack.stripFullCss(_NAVIPLUS.VARS);
} catch (e) {}
// GP2: warm connection + prefetch shopinfo SONG SONG với lúc tải uigen.js
if (!window._naviPreconnectDone) {
window._naviPreconnectDone = true;
// JSON CDN: fetch dạng CORS → cần crossorigin để connection được tái dùng
var lJson = doc.createElement('link');
lJson.rel = 'preconnect'; lJson.href = 'https://cdn.naviplus.app'; lJson.crossOrigin = 'anonymous';
doc.head.appendChild(lJson);
// uigen CDN: tải bằng