1
0
Fork 0
mirror of https://github.com/anyproto/anytype-ts.git synced 2025-06-08 05:57:02 +09:00

Merge pull request #1431 from anyproto/docs/util-common-docs

Docs/Document lib/util
This commit is contained in:
Razor 2025-06-02 14:13:28 +02:00 committed by GitHub
commit 79ae67fa27
Signed by: github
GPG key ID: B5690EEEBB952194
7 changed files with 746 additions and 7 deletions

File diff suppressed because it is too large Load diff

View file

@ -19,11 +19,22 @@ const IFRAME_PARAM = 'frameborder="0" scrolling="no" allowfullscreen';
class UtilEmbed {
/**
* Returns the HTML for embedding content based on the processor type.
* @param {I.EmbedProcessor} processor - The embed processor type.
* @param {any} content - The content to embed.
* @returns {string} The HTML string for embedding.
*/
getHtml (processor: I.EmbedProcessor, content: any): string {
const fn = U.Common.toCamelCase(`get-${I.EmbedProcessor[processor]}-html`);
return this[fn] ? this[fn](content) : content;
};
/**
* Returns the HTML for embedding a YouTube video.
* @param {string} content - The YouTube URL.
* @returns {string} The HTML iframe string.
*/
getYoutubeHtml (content: string): string {
let url = '';
@ -35,30 +46,65 @@ class UtilEmbed {
return `<iframe id="player" src="${url.toString()}" ${IFRAME_PARAM} title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"></iframe>`;
};
/**
* Returns the HTML for embedding a Vimeo video.
* @param {string} content - The Vimeo URL.
* @returns {string} The HTML iframe string.
*/
getVimeoHtml (content: string): string {
return `<iframe src="${content}" ${IFRAME_PARAM} allow="autoplay; fullscreen; picture-in-picture"></iframe>`;
};
/**
* Returns the HTML for embedding a Google Maps location.
* @param {string} content - The Google Maps URL.
* @returns {string} The HTML iframe string.
*/
getGoogleMapsHtml (content: string): string {
return `<iframe src="${content}" ${IFRAME_PARAM} loading="lazy"></iframe>`;
};
/**
* Returns the HTML for embedding a Miro board.
* @param {string} content - The Miro URL.
* @returns {string} The HTML iframe string.
*/
getMiroHtml (content: string): string {
return `<iframe src="${content}" ${IFRAME_PARAM} allow="fullscreen; clipboard-read; clipboard-write"></iframe>`;
};
/**
* Returns the HTML for embedding a Figma file.
* @param {string} content - The Figma URL.
* @returns {string} The HTML iframe string.
*/
getFigmaHtml (content: string): string {
return `<iframe src="${content}" ${IFRAME_PARAM}></iframe>`;
};
/**
* Returns the HTML for embedding an OpenStreetMap view.
* @param {string} content - The OpenStreetMap URL.
* @returns {string} The HTML iframe string.
*/
getOpenStreetMapHtml (content: string): string {
return `<iframe src="${content}" ${IFRAME_PARAM}></iframe>`;
};
/**
* Returns the HTML for embedding a GitHub Gist.
* @param {string} content - The Gist URL.
* @returns {string} The HTML script tag.
*/
getGithubGistHtml (content: string): string {
return `<script src="${content}.js"></script>`;
};
/**
* Returns the HTML for embedding a Codepen snippet.
* @param {string} content - The Codepen URL.
* @returns {string} The HTML string for Codepen.
*/
getCodepenHtml (content: string): string {
let p = [];
@ -75,22 +121,47 @@ class UtilEmbed {
return `<p class="codepen" data-height="300" data-default-tab="html,result" data-slug-hash="${p[3]}" data-user="${p[1]}"></p>`;
};
/**
* Returns the HTML for embedding a Bilibili video.
* @param {string} content - The Bilibili URL.
* @returns {string} The HTML iframe string.
*/
getBilibiliHtml (content: string): string {
return `<iframe src="${content}" ${IFRAME_PARAM}></iframe>`;
};
/**
* Returns the HTML for embedding a Sketchfab model.
* @param {string} content - The Sketchfab URL.
* @returns {string} The HTML iframe string.
*/
getSketchfabHtml (content: string): string {
return `<iframe src="${content}" ${IFRAME_PARAM}></iframe>`;
};
/**
* Returns the HTML for embedding a Drawio diagram or SVG.
* @param {string} content - The Drawio URL or SVG content.
* @returns {string} The HTML iframe or SVG string.
*/
getDrawioHtml (content: string): string {
return content.match(/^<svg/) ? content : `<iframe src="${content}" ${IFRAME_PARAM}></iframe>`;
};
/**
* Returns the HTML for embedding an image.
* @param {string} content - The image URL.
* @returns {string} The HTML img tag.
*/
getImageHtml (content: string): string {
return `<img src="${content}" />`;
};
/**
* Determines the embed processor type for a given URL.
* @param {string} url - The URL to check.
* @returns {I.EmbedProcessor|null} The processor type or null if not found.
*/
getProcessorByUrl (url: string): I.EmbedProcessor {
let p = null;
for (const i in DOMAINS) {
@ -115,6 +186,11 @@ class UtilEmbed {
return p;
};
/**
* Returns a parsed embed URL for a given processor type.
* @param {string} url - The original URL.
* @returns {string|undefined} The parsed embed URL or undefined.
*/
getParsedUrl (url: string): string {
const processor = this.getProcessorByUrl(url);

View file

@ -12,6 +12,11 @@ const UNITS = {
class UtilFile {
/**
* Returns a human-readable file size string for a given number of bytes.
* @param {number} v - The file size in bytes.
* @returns {string} The formatted file size string.
*/
size (v: number): string {
v = Number(v) || 0;
@ -30,6 +35,11 @@ class UtilFile {
return ret ? U.Common.formatNumber(Number(U.Common.sprintf(`%0.2f`, ret))) + unit : '';
};
/**
* Returns the icon name for a file object based on its properties.
* @param {any} object - The file object.
* @returns {string} The icon name.
*/
icon (object: any): string {
object = object || {};
@ -120,10 +130,21 @@ class UtilFile {
return icon;
};
/**
* Returns the icon path for a file object based on its properties and theme.
* @param {any} object - The file object.
* @returns {string} The icon path.
*/
iconPath (object: any) {
return `./img/${S.Common.getThemePath()}icon/file/${this.icon(object)}.svg`;
};
/**
* Loads a preview canvas for an image file and calls a callback with the canvas.
* @param {any} file - The image file.
* @param {any} param - The parameters for loading.
* @param {function} [success] - Callback with the loaded canvas.
*/
loadPreviewCanvas (file: any, param: any, success?: (canvas: any) => void) {
if (!file) {
return;
@ -145,6 +166,13 @@ class UtilFile {
});
};
/**
* Loads a preview image as a base64 string and calls a callback with the image and parameters.
* @param {any} file - The image file.
* @param {any} param - The parameters for loading.
* @param {function} [success] - Callback with the image and parameters.
* @param {function} [error] - Callback if loading fails.
*/
loadPreviewBase64 (file: any, param: any, success?: (image: string, param: any) => void, error?: (error: string) => void) {
this.loadPreviewCanvas(file, param, (canvas: any) => {
const image = canvas.toDataURL(param.type, param.quality);
@ -159,10 +187,19 @@ class UtilFile {
});
};
/**
* Returns the current date as a string suitable for filenames.
* @returns {string} The date string.
*/
date () {
return new Date().toISOString().replace(/:/g, '_').replace(/\..+/, '');
};
/**
* Returns the file name for a file object, appending the extension if needed.
* @param {any} object - The file object.
* @returns {string} The file name.
*/
name (object: any) {
object = object || {};
@ -176,6 +213,11 @@ class UtilFile {
return `${name}.${fileExt}`;
};
/**
* Returns the object layout type for a given mime type.
* @param {string} mime - The mime type string.
* @returns {I.ObjectLayout} The object layout type.
*/
layoutByMime (mime: string) {
const t = mime.split('/');
@ -199,6 +241,11 @@ class UtilFile {
return layout;
};
/**
* Checks if a drag event contains files.
* @param {React.DragEvent} e - The drag event.
* @returns {boolean} True if files are present, false otherwise.
*/
checkDropFiles (e: React.DragEvent): boolean {
return (e.dataTransfer.files && e.dataTransfer.files.length) ? true : false;
};

View file

@ -2,6 +2,11 @@ import { I, S, U, J, Relation } from 'Lib';
class UtilGraph {
/**
* Returns the image source path for a graph node based on its layout and properties.
* @param {any} d - The node data object.
* @returns {string} The image source path.
*/
imageSrc (d: any) {
d = d || {};

View file

@ -10,6 +10,11 @@ class UtilPrism {
this.aliasMap = this.getAliasMap();
};
/**
* Returns an array of dependencies for a given Prism language, in load order.
* @param {string} lang - The language key.
* @returns {string[]} The array of dependencies.
*/
private getDependencies (lang: string): string[] {
const result = [];
const language = Components.languages[lang] || {};
@ -24,7 +29,10 @@ class UtilPrism {
return result;
};
/** returns an array which is the correct order of loading all Prism components */
/**
* Returns an array which is the correct order of loading all Prism components.
* @returns {string[]} The ordered list of component keys.
*/
get components (): string[] {
const result = [];
for (const key in Components.languages) {
@ -33,6 +41,10 @@ class UtilPrism {
return [ ...new Set(result) ];
};
/**
* Returns a map of language keys to their display titles.
* @returns {object} The map of language keys to titles.
*/
private getMap () {
const result = {};
@ -52,6 +64,10 @@ class UtilPrism {
return result;
};
/**
* Returns a map of display titles to arrays of language keys.
* @returns {Map<string, string[]>} The value-key map.
*/
getValueKeyMap (): Map<string, string[]> {
const ret: Map<string, string[]> = new Map();
for (const [ key, value ] of Object.entries(this.map)) {
@ -60,6 +76,10 @@ class UtilPrism {
return ret;
};
/**
* Returns a map of language keys to their canonical alias.
* @returns {object} The alias map.
*/
getAliasMap () {
const map = this.getValueKeyMap();
const result: { [ key: string ]: string } = {};
@ -73,6 +93,10 @@ class UtilPrism {
return result;
};
/**
* Returns an array of language titles and their canonical key.
* @returns {{ id: string, name: string }[]} The array of language titles.
*/
getTitles () {
const map = this.getValueKeyMap();
const result: { id: string; name: string }[] = [];

View file

@ -5,10 +5,10 @@ interface RouteParam {
page: string;
action: string;
id: string;
spaceId: string;
viewId: string;
relationKey: string;
additional: { key: string, value: string }[];
spaceId?: string;
viewId?: string;
relationKey?: string;
additional?: { key: string, value: string }[];
};
class UtilRouter {
@ -16,10 +16,19 @@ class UtilRouter {
history: any = null;
isOpening = false;
/**
* Initializes the router with a history object.
* @param {any} history - The history object to use for navigation.
*/
init (history: any) {
this.history = history;
};
/**
* Parses a route path into its parameter object.
* @param {string} path - The route path string.
* @returns {RouteParam} The parsed route parameters.
*/
getParam (path: string): any {
const route = path.split('/');
if (!route.length) {
@ -45,6 +54,11 @@ class UtilRouter {
return param;
};
/**
* Builds a route string from route parameters.
* @param {Partial<RouteParam>} param - The route parameters.
* @returns {string} The route string.
*/
build (param: Partial<RouteParam>): string {
const { page, action } = param;
const id = String(param.id || '');
@ -71,6 +85,11 @@ class UtilRouter {
return route.join('/');
};
/**
* Navigates to a route with optional parameters and animation.
* @param {string} route - The route string.
* @param {Partial<I.RouteParam>} param - Additional navigation parameters.
*/
go (route: string, param: Partial<I.RouteParam>) {
if (!route) {
return;
@ -154,6 +173,14 @@ class UtilRouter {
timeout ? window.setTimeout(() => onTimeout(), timeout) : onTimeout();
};
/**
* Switches to a different space, handling errors and fallbacks.
* @param {string} id - The space ID to switch to.
* @param {string} route - The route to navigate after switching.
* @param {boolean} sendEvent - Whether to send analytics event.
* @param {any} routeParam - Additional route parameters.
* @param {boolean} useFallback - Whether to use fallback on error.
*/
switchSpace (id: string, route: string, sendEvent: boolean, routeParam: any, useFallback: boolean) {
if (this.isOpening) {
return;
@ -220,10 +247,18 @@ class UtilRouter {
});
};
/**
* Gets the current route path as a string.
* @returns {string} The current route path.
*/
getRoute () {
return String(this.history?.location?.pathname || '');
};
/**
* Gets the spaceId from the current route or the default space.
* @returns {string} The spaceId.
*/
getRouteSpaceId () {
const param = this.getParam(this.getRoute());
return param.spaceId || S.Common.space;

View file

@ -10,6 +10,9 @@ class UtilSmile {
cache: any = {};
aliases: any = {};
/**
* Initializes the emoji data, icons, cache, and aliases.
*/
init () {
init({ data: J.Emoji });
@ -28,6 +31,12 @@ class UtilSmile {
};
};
/**
* Returns the native emoji character by its ID and skin tone.
* @param {string} id - The emoji ID.
* @param {number} skin - The skin tone index.
* @returns {string} The native emoji character.
*/
nativeById (id: string, skin: number): string {
if (!id) {
return '';
@ -51,6 +60,10 @@ class UtilSmile {
return skinItem.native;
};
/**
* Returns a random emoji parameter (id and skin).
* @returns {{ id: string, skin: number }} The random emoji parameter.
*/
randomParam (): { id: string, skin: number } {
return {
id: this.icons[U.Common.rand(0, this.icons.length - 1)],
@ -58,11 +71,20 @@ class UtilSmile {
};
};
/**
* Returns a random native emoji character.
* @returns {string} The random emoji character.
*/
random (): string {
const param = this.randomParam();
return this.nativeById(param.id, param.skin);
};
/**
* Returns the image source path for an emoji given its colons code.
* @param {string} colons - The emoji colons code.
* @returns {string} The image source path.
*/
srcFromColons (colons: string) {
if (!colons) {
return '';
@ -94,6 +116,11 @@ class UtilSmile {
return `${prefix}${code}.png`;
};
/**
* Returns the shortcodes for a native emoji character.
* @param {string} icon - The native emoji character.
* @returns {string} The shortcodes for the emoji.
*/
getCode (icon: string) {
icon = icon.trim();
@ -129,11 +156,20 @@ class UtilSmile {
return this.cache[icon] || '';
};
/**
* Removes emoji characters from a string.
* @param {string} t - The string to strip.
* @returns {string} The string without emojis.
*/
strip (t: string) {
const r = /(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff]|[\u0023-\u0039]\ufe0f?\u20e3|\u3299|\u3297|\u303d|\u3030|\u24c2|\ud83c[\udd70-\udd71]|\ud83c[\udd7e-\udd7f]|\ud83c\udd8e|\ud83c[\udd91-\udd9a]|\ud83c[\udde6-\uddff]|\ud83c[\ude01-\ude02]|\ud83c\ude1a|\ud83c\ude2f|\ud83c[\ude32-\ude3a]|\ud83c[\ude50-\ude51]|\u203c|\u2049|[\u25aa-\u25ab]|\u25b6|\u25c0|[\u25fb-\u25fe]|\u00a9|\u00ae|\u2122|\u2139|\ud83c\udc04|[\u2600-\u26FF]|\u2b05|\u2b06|\u2b07|\u2b1b|\u2b1c|\u2b50|\u2b55|\u231a|\u231b|\u2328|\u23cf|[\u23e9-\u23f3]|[\u23f8-\u23fa]|\ud83c\udccf|\u2934|\u2935|[\u2190-\u21ff])/g;
return t.replace(r, '');
};
/**
* Returns the list of emoji categories with translated names.
* @returns {any[]} The list of emoji categories.
*/
getCategories () {
return J.Emoji.categories.filter(it => it.id != 'frequent').map(it => ({
...it,