@jackens/nnn
Version:
Jackens’ JavaScript helpers.
259 lines (256 loc) • 9.78 kB
JavaScript
// src/nnn/is.ts
var is_array = Array.isArray;
var is_number = (arg) => typeof arg === "number";
var is_record = (arg) => typeof arg === "object" && arg != null && !is_array(arg);
var is_string = (arg) => typeof arg === "string";
// src/nnn/c.ts
var _c = (node, prefix, result, splitter) => {
const queue = [[node, prefix]];
while (queue.length > 0) {
const [style_0, prefix_0] = queue.shift() ?? [];
if (style_0 == null || prefix_0 == null) {
continue;
}
if (is_array(style_0)) {
result.push(prefix_0, prefix_0 !== "" ? "{" : "", style_0.join(";"), prefix_0 !== "" ? "}" : "");
} else {
const todo = [];
let attributes = [];
let attributes_pushed = false;
for (const key in style_0) {
const value = style_0[key];
if (is_string(value) || is_number(value)) {
if (!attributes_pushed) {
attributes_pushed = true;
attributes = [];
todo.push([attributes, prefix_0]);
}
const attribute = key.split(splitter)[0].replace(/_/g, "-").replace(/([A-Z])/g, (_, letter) => "-" + letter.toLowerCase());
attributes.push(`${attribute}:${value}`);
} else if (value != null) {
attributes_pushed = false;
const prefix_n = [];
const key_chunks = key.split(",");
prefix_0.split(",").forEach((prefix_chunk) => key_chunks.forEach((key_chunk) => prefix_n.push(prefix_chunk + key_chunk)));
todo.push([value, prefix_n.join()]);
}
}
queue.unshift(...todo);
}
}
};
var c = (root, splitter = "$$") => {
const chunks = [];
for (const key in root) {
const value = root[key];
if (value != null) {
if (key[0] === "@") {
chunks.push(key.split(splitter)[0] + "{");
_c(value, "", chunks, splitter);
chunks.push("}");
} else {
_c(value, key.split(splitter)[0], chunks, splitter);
}
}
}
return chunks.join("");
};
// src/nnn/csv_parse.ts
var csv_parse_raw = (csv, separator = ",") => {
const main_pattern = /\n|(?<!")("(?:[^"]|"")*")(?!")/g;
const line_pattern = new RegExp(`${separator}|(?<!")\\s*"((?:[^"]|"")*)"\\s*(?!")`, "g");
return csv.replace(/\r/g, "").replace(/\n+$/, "").replace(main_pattern, (_, chunk) => chunk ?? "\r").split("\r").map((line) => line.replace(line_pattern, (_, chunk) => chunk == null ? "\r" : chunk.replace(/""/g, '"')).split("\r"));
};
var csv_parse = (csv, separator = ",") => {
const rows = csv_parse_raw(csv, separator);
const keys = rows.shift();
return keys != null ? rows.map((row) => keys.reduce((record, key, index) => {
record[key] = row[index];
return record;
}, {})) : [];
};
// src/nnn/escape.ts
var escape_values = (escape_map, values) => values.map((value) => (escape_map.get(value?.constructor) ?? escape_map.get(undefined))?.(value) ?? "");
var escape = (escape_map, template, ...values) => String.raw(template, ...escape_values(escape_map, values));
// src/nnn/h.ts
var _h = (namespace_uri) => {
const create_element = namespace_uri == null ? (tag) => document.createElement(tag) : (tag) => document.createElementNS(namespace_uri, tag);
const h = (tag_or_node, ...args) => {
const node = is_string(tag_or_node) ? create_element(tag_or_node) : tag_or_node;
args.forEach((arg) => {
let child = null;
if (arg instanceof Node) {
child = arg;
} else if (is_array(arg)) {
child = h(...arg);
} else if (is_record(arg)) {
for (const name in arg) {
const value = arg[name];
if (name[0] === "$") {
const name1 = name.slice(1);
if (is_record(value)) {
node[name1] = node[name1] ?? {};
Object.assign(node[name1], value);
} else {
node[name1] = value;
}
} else if (node instanceof Element) {
const index_of_colon = name.indexOf(":");
if (index_of_colon >= 0) {
const ns_key = name.slice(0, index_of_colon);
if (ns_key === "xlink") {
const ns = "http://www.w3.org/1999/xlink";
const basename = name.slice(index_of_colon + 1);
if (value === true) {
node.setAttributeNS(ns, basename, "");
} else if (value === false) {
node.removeAttributeNS(ns, basename);
} else {
node.setAttributeNS(ns, basename, "" + value);
}
}
} else {
if (value === true) {
node.setAttribute(name, "");
} else if (value === false) {
node.removeAttribute(name);
} else {
node.setAttribute(name, "" + value);
}
}
}
}
} else if (is_string(arg)) {
child = document.createTextNode(arg);
}
if (child != null) {
node.appendChild(child);
}
});
return node;
};
return h;
};
var h = _h();
var s = _h("http://www.w3.org/2000/svg");
var svg_use = (id, ...args) => s("svg", ["use", { "xlink:href": "#" + id }], ...args);
// src/nnn/fix_typography.ts
var TAGS_TO_SKIP = ["IFRAME", "NOSCRIPT", "PRE", "SCRIPT", "STYLE", "TEXTAREA"];
var fix_typography = (node) => {
const queue = [node];
while (queue.length > 0) {
const node_0 = queue.shift();
if (node_0 instanceof Element) {
node_0.childNodes.forEach((child_node) => {
if (child_node instanceof Text) {
queue.push(child_node);
} else if (child_node instanceof Element && !TAGS_TO_SKIP.includes(child_node.tagName)) {
queue.push(child_node);
}
});
} else if (node_0 instanceof Text) {
const node_value = node_0.nodeValue?.trim?.();
if (node_value != null) {
let previous_node = node_0;
node_value.split(/(\s|\(|„)([aiouwz—]\s)/gi).forEach((chunk, i) => {
i %= 3;
const current_node = i === 2 ? h("span", { style: "white-space:nowrap" }, chunk) : i === 1 ? document.createTextNode(chunk) : document.createTextNode(chunk.replace(/(\/(?=[^/\s])|\.(?=[^\s]))/g, "$1"));
if (node_0.parentNode != null) {
node_0.parentNode.insertBefore(current_node, previous_node.nextSibling);
}
previous_node = current_node;
});
node_0.parentNode?.removeChild(node_0);
}
}
}
};
// src/nnn/has_own.ts
var has_own = (ref, key) => ref != null && Object.hasOwn(ref, key);
// src/nnn/js_on_parse.ts
var js_on_parse = (handlers, text) => JSON.parse(text, (key, value) => {
if (is_record(value)) {
let is_second_key = false;
for (key in value) {
if (is_second_key) {
return value;
}
is_second_key = true;
}
const handler = handlers[key];
const params = value[key];
if (handler instanceof Function && is_array(params)) {
return handler(...params);
}
}
return value;
});
// src/nnn/nanolight.ts
var nanolight = (pattern, highlighters, code) => {
const result = [];
code.split(pattern).forEach((chunk, index) => {
if (chunk != null && chunk !== "") {
index %= highlighters.length;
result.push(highlighters[index](chunk, index));
}
});
return result;
};
// src/nnn/nanolight_js.ts
var nanolight_js = nanolight.bind(0, /('.*?'|".*?"|`[\s\S]*?`)|(\/\/.*?\n|\/\*[\s\S]*?\*\/)|(any|bigint|break|boolean|case|catch|class|const|continue|debugger|default|delete|do|else|eval|export|extends|false|finally|for|from|function|goto|if|import|in|instanceof|is|keyof|let|NaN|new|number|null|package|return|string|super|switch|symbol|this|throw|true|try|type|typeof|undefined|unknown|var|void|while|with|yield)(?!\w)|([<>=.?:&|!^~*/%+-])|(0x[\dabcdef_]+|0o[01234567_]+|0b[01_]+|\d[\d_]*(?:\.[\d_]+)?(?:e[+-]?[\d_]+)?)|([$\w]+)(?=\()|([$\wąćęłńóśżźĄĆĘŁŃÓŚŻŹ]+)/, [
(chunk) => chunk,
(chunk) => ["span", { class: "string" }, chunk],
(chunk) => ["span", { class: "comment" }, chunk],
(chunk) => ["span", { class: "keyword" }, chunk],
(chunk) => ["span", { class: "operator" }, chunk],
(chunk) => ["span", { class: "number" }, chunk],
(chunk) => ["span", { class: "function" }, chunk],
(chunk) => ["span", { class: "literal" }, chunk]
]);
// src/nnn/pick.ts
var pick = (ref, keys) => Object.fromEntries(Object.entries(ref).filter(([key]) => keys.includes(key)));
var omit = (ref, keys) => Object.fromEntries(Object.entries(ref).filter(([key]) => !keys.includes(key)));
// src/nnn/pl_ural.ts
var pl_ural = (singular, plural_2, plural_5, value) => {
const abs_value = Math.abs(value);
const abs_value_mod_10 = abs_value % 10;
return value === 1 ? singular : (abs_value_mod_10 === 2 || abs_value_mod_10 === 3 || abs_value_mod_10 === 4) && abs_value !== 12 && abs_value !== 13 && abs_value !== 14 ? plural_2 : plural_5;
};
// src/nnn/pro.ts
var pro = (ref) => new Proxy(ref, {
get(target, key) {
return pro(target[key] = target[key] ?? {});
}
});
// src/nnn/uuid_v1.ts
var ZEROS = "0".repeat(16);
var counter = 0;
var uuid_v1 = (date = new Date, node = Math.random().toString(16).slice(2)) => {
const time = ZEROS + (1e4 * (+date + 12219292800000)).toString(16);
counter = counter + 1 & 16383;
return time.slice(-8).concat("-", time.slice(-12, -8), -1, time.slice(-15, -12), "-", (8 | counter >> 12).toString(16), (ZEROS + (counter & 4095).toString(16)).slice(-3), "-", (ZEROS + node).slice(-12));
};
export {
uuid_v1,
svg_use,
s,
pro,
pl_ural,
pick,
omit,
nanolight_js,
nanolight,
js_on_parse,
is_string,
is_record,
is_number,
is_array,
has_own,
h,
fix_typography,
escape_values,
escape,
csv_parse_raw,
csv_parse,
c
};