@itwin/core-common
Version:
iTwin.js components common to frontend and backend
73 lines • 2.73 kB
JavaScript
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
const formatters = {
// eslint-disable-next-line @typescript-eslint/no-base-to-string
"string": (v, o) => formatString(v.toString(), o),
"datetime": (v, o) => formatString(formatDateTime(v, o?.dateTime), o),
// eslint-disable-next-line @typescript-eslint/no-base-to-string
"quantity": (v, o) => formatString(v.toString(), o),
"coordinate": (v, o) => formatString(formatPointBasic(v), o),
// eslint-disable-next-line @typescript-eslint/no-base-to-string
"boolean": (v, o) => formatString(v.toString(), o),
// eslint-disable-next-line @typescript-eslint/no-base-to-string
"int-enum": (v, o) => formatString(v.toString(), o),
// eslint-disable-next-line @typescript-eslint/no-base-to-string
"string-enum": (v, o) => formatString(v.toString(), o),
};
function formatString(s, o) {
if (undefined === s || !o) {
return s;
}
switch (o.case) {
case "upper":
s = s.toUpperCase();
break;
case "lower":
s = s.toLowerCase();
break;
}
if (o.prefix || o.suffix) {
s = `${o.prefix ?? ""}${s}${o.suffix ?? ""}`;
}
return s;
}
function formatDateTime(v, o) {
if (!(v instanceof Date))
return undefined;
if (!isNaN(v.getTime())) {
if (o?.formatOptions) {
const locale = o.locale ?? "en-US";
if (!Intl.DateTimeFormat.supportedLocalesOf([locale], { localeMatcher: "lookup" }).includes(locale)) {
return undefined;
}
const formatter = new Intl.DateTimeFormat(locale, o.formatOptions);
return formatter.format(v);
}
return v.toString();
}
return undefined;
}
// ###TODO replace this with actual quantity coordinate formatting.
function formatPointBasic(v) {
if (typeof v === "object" && "x" in v && "y" in v) {
const parts = [v.x, v.y];
const z = v.z;
if (undefined !== z) {
parts.push(z);
}
return `(${parts.join(", ")})`;
}
return undefined;
}
/** @internal */
export function formatFieldValue(value, options) {
const formatter = formatters[value.type];
return formatter ? formatter(value.value, options) : undefined;
}
/** @internal */
export function isKnownFieldPropertyType(type) {
return type in formatters;
}
//# sourceMappingURL=FieldFormatter.js.map