code
stringlengths
10
343k
docstring
stringlengths
36
21.9k
func_name
stringlengths
1
3.35k
language
stringclasses
1 value
repo
stringlengths
7
58
path
stringlengths
4
131
url
stringlengths
44
195
license
stringclasses
5 values
export const createFileList = (files) => { /** @type {BaseEntryListItem[]} */ const entryFiles = []; /** @type {BaseAssetListItem[]} */ const assetFiles = []; files.forEach((fileInfo) => { const { path } = fileInfo; const [entryFolder] = getEntryFoldersByPath(path); const [assetFolder] = getAssetFoldersByPath(path, { matchSubFolders: true }); if (entryFolder) { entryFiles.push({ ...fileInfo, type: 'entry', folder: entryFolder }); } // Exclude files already listed as entries. These files can appear in the file list when a // relative media path is configured for a collection if (assetFolder && !entryFiles.find((e) => e.path === path)) { assetFiles.push({ ...fileInfo, type: 'asset', folder: assetFolder }); } }); const allFiles = [...entryFiles, ...assetFiles]; return { entryFiles, assetFiles, allFiles, count: allFiles.length }; };
Parse a list of all files on the repository/filesystem to create entry and asset lists, with the relevant collection/file configuration added. @param {BaseFileListItem[]} files Unfiltered file list. @returns {BaseFileList} File list, including both entries and assets.
createFileList
javascript
sveltia/sveltia-cms
src/lib/services/backends/shared/data.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/shared/data.js
MIT
export const getHandleByPath = async (rootDirHandle, path) => { /** @type {FileSystemFileHandle | FileSystemDirectoryHandle} */ let handle = rootDirHandle; if (!path) { return handle; } const pathParts = stripSlashes(path).split('/'); const create = true; for (const name of pathParts) { handle = await (name.includes('.') ? /** @type {FileSystemDirectoryHandle} */ (handle).getFileHandle(name, { create }) : /** @type {FileSystemDirectoryHandle} */ (handle).getDirectoryHandle(name, { create })); } return handle; };
Get a file or directory handle at the given path. @param {FileSystemDirectoryHandle} rootDirHandle Root directory handle. @param {string} path Path to the file/directory. @returns {Promise<FileSystemFileHandle | FileSystemDirectoryHandle>} Handle.
getHandleByPath
javascript
sveltia/sveltia-cms
src/lib/services/backends/shared/fs.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/shared/fs.js
MIT
const getRegEx = (path) => new RegExp(`^${escapeRegExp(path)}\\b`);
Get a regular expression to match the given path. @param {string} path Path. @returns {RegExp} RegEx.
getRegEx
javascript
sveltia/sveltia-cms
src/lib/services/backends/shared/fs.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/shared/fs.js
MIT
const iterate = async (dirHandle) => { for await (const [name, handle] of dirHandle.entries()) { if (name.startsWith('.')) { continue; } const path = (await rootDirHandle.resolve(handle))?.join('/') ?? ''; const hasMatchingPath = scanningPathsRegEx.some((regex) => regex.test(path)); if (handle.kind === 'file') { if (!hasMatchingPath) { continue; } try { /** @type {File} */ let file = await handle.getFile(); // Clone the file immediately to avoid potential permission problems file = new File([file], file.name, { type: file.type, lastModified: file.lastModified }); availableFileList.push({ file, path }); } catch (/** @type {any} */ ex) { // eslint-disable-next-line no-console console.error(ex); } } if (handle.kind === 'directory') { const regex = getRegEx(path); if (!hasMatchingPath && !scanningPaths.some((p) => regex.test(p))) { continue; } await iterate(handle); } } };
Retrieve all the files under the given directory recursively. @param {FileSystemDirectoryHandle | any} dirHandle Directory handle.
iterate
javascript
sveltia/sveltia-cms
src/lib/services/backends/shared/fs.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/shared/fs.js
MIT
export const loadFiles = async (rootDirHandle) => { const { entryFiles, assetFiles } = createFileList(await getAllFiles(rootDirHandle)); // Load all entry text content await Promise.all( entryFiles.map(async (entryFile) => { try { entryFile.text = await readAsText(/** @type {File} */ (entryFile.file)); } catch (/** @type {any} */ ex) { entryFile.text = ''; // eslint-disable-next-line no-console console.error(ex); } }), ); const { entries, errors } = await prepareEntries(entryFiles); allEntries.set(entries); entryParseErrors.set(errors); allAssets.set(parseAssetFiles(assetFiles)); dataLoaded.set(true); };
Load file list and all the entry files from the file system, then cache them in the {@link allEntries} and {@link allAssets} stores. @param {FileSystemDirectoryHandle} rootDirHandle Root directory handle.
loadFiles
javascript
sveltia/sveltia-cms
src/lib/services/backends/shared/fs.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/shared/fs.js
MIT
export const initServerSideAuth = async ({ backendName, siteDomain, authURL, scope }) => { try { // `siteDomain` may contain non-ASCII characters. When authenticating with Netlify, such // internationalized domain names (IDNs) must be written in Punycode. Use `URL` for conversion, // e.g `日本語.jp` -> `xn--wgv71a119e.jp` if (new URL(authURL).origin === 'https://api.netlify.com') { siteDomain = new URL(`https://${siteDomain}`).hostname; } } catch { // } const params = new URLSearchParams({ provider: backendName, site_id: siteDomain, scope, }); return authorize({ backendName, authURL: `${authURL}?${params.toString()}`, }); };
Initialize the server-side Authorization Code Flow. @param {object} args Arguments. @param {string} args.backendName Backend name, e.g. `github`. @param {string} args.siteDomain Domain of the site hosting the CMS. @param {string} args.authURL Authorization site URL. @param {string} args.scope Authorization scope. @returns {Promise<string>} Auth token.
initServerSideAuth
javascript
sveltia/sveltia-cms
src/lib/services/backends/shared/auth.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/shared/auth.js
MIT
export const initClientSideAuth = async ({ backendName, clientId, authURL, scope }) => { const { csrfToken, codeVerifier, codeChallenge } = await createAuthSecrets(); const { origin, pathname } = window.location; const redirectURL = `${origin}${pathname}`; const params = new URLSearchParams({ client_id: clientId, redirect_uri: redirectURL, response_type: 'code', state: csrfToken, scope, code_challenge: codeChallenge, code_challenge_method: 'S256', }); // Store the temporary secret and real auth URL await LocalStorage.set('sveltia-cms.auth', { csrfToken, codeVerifier, realAuthURL: `${authURL}?${params.toString()}`, }); // Store the user info only with the backend name, so the automatic sign-in flow that triggers // `finishClientSideAuth` below will work await LocalStorage.set('sveltia-cms.user', { backendName }); return authorize({ backendName, authURL: redirectURL, }); };
Initialize the client-side Authorization Code Flow with PKCE. @param {object} args Arguments. @param {string} args.backendName Backend name, e.g. `gitlab`. @param {string} args.clientId OAuth application ID. @param {string} args.authURL Authorization site URL. @param {string} args.scope Authorization scope. @returns {Promise<string>} Auth token. @see https://docs.gitlab.com/ee/api/oauth2.html#authorization-code-with-proof-key-for-code-exchange-pkce
initClientSideAuth
javascript
sveltia/sveltia-cms
src/lib/services/backends/shared/auth.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/shared/auth.js
MIT
const sendMessage = ({ provider = 'unknown', token, error, errorCode }) => { const _state = error ? 'error' : 'success'; const content = error ? { provider, error, errorCode } : { provider, token }; window.addEventListener('message', ({ data, origin }) => { if (data === `authorizing:${provider}`) { window.opener?.postMessage( `authorization:${provider}:${_state}:${JSON.stringify(content)}`, origin, ); } }); window.opener?.postMessage(`authorizing:${provider}`, '*'); };
Communicate with the window opener as part of {@link finishClientSideAuth}. @param {object} args Options. @param {string} [args.provider] Backend name, e,g. `github`. @param {string} [args.token] OAuth token. @param {string} [args.error] Error message when an OAuth token is not available. @param {string} [args.errorCode] Error code to be used to localize the error message in Sveltia CMS.
sendMessage
javascript
sveltia/sveltia-cms
src/lib/services/backends/shared/auth.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/shared/auth.js
MIT
export const handleClientSideAuthPopup = async ({ backendName, clientId, authURL }) => { inAuthPopup.set(true); const { search } = window.location; const { code, state } = Object.fromEntries(new URLSearchParams(search)); if (code && state) { await finishClientSideAuth({ backendName, clientId, authURL, code, state }); } else { const { realAuthURL } = (await LocalStorage.get('sveltia-cms.auth')) ?? {}; if (realAuthURL) { window.location.href = realAuthURL; } } };
Handle the client-side Authorization Code Flow with PKCE within the auth popup window. Redirect to the authorization site or finish the flow after being redirected from the auth site. @param {object} args Arguments. @param {string} args.backendName Backend name, e.g. `gitlab`. @param {string} args.clientId OAuth application ID. @param {string} args.authURL Authorization site URL.
handleClientSideAuthPopup
javascript
sveltia/sveltia-cms
src/lib/services/backends/shared/auth.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/shared/auth.js
MIT
export const signInAutomatically = async () => { // Find cached user info, including a compatible Netlify/Decap CMS user object const userCache = (await LocalStorage.get('sveltia-cms.user')) || (await LocalStorage.get('decap-cms-user')) || (await LocalStorage.get('netlify-cms-user')); let _user = isObject(userCache) && !!userCache.backendName ? userCache : undefined; // Netlify/Decap CMS uses `proxy` as the backend name when running the local proxy server and // leaves it in local storage. Sveltia CMS uses `local` instead. const _backendName = _user?.backendName?.replace('proxy', 'local') ?? get(siteConfig)?.backend?.name; backendName.set(_backendName); const _backend = get(backend); if (_user && _backend) { try { _user = await _backend.signIn({ token: _user.token, auto: true }); } catch { // The local backend may throw if the file handle permission is not given _user = undefined; } } unauthenticated.set(!_user); if (!_user || !_backend) { return; } // Use the cached user to start fetching files user.set(_user); try { await _backend.fetchFiles(); // Reset error signInError.set({ message: '', canRetry: false }); } catch (/** @type {any} */ ex) { // The API request may fail if the cached token has been expired or revoked. Then let the user // sign in again. 404 Not Found is also considered an authentication error. // https://docs.github.com/en/rest/overview/troubleshooting-the-rest-api#404-not-found-for-an-existing-resource if ([401, 403, 404].includes(ex.cause?.status)) { unauthenticated.set(true); } else { logError(ex); } } };
Check if the user info is cached, set the backend, and automatically start loading files if the backend is Git-based and user’s auth token is found.
signInAutomatically
javascript
sveltia/sveltia-cms
src/lib/services/user/auth.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/user/auth.js
MIT
export const signInManually = async (_backendName) => { backendName.set(_backendName); const _backend = get(backend); if (!_backend) { return; } let _user; try { _user = await _backend.signIn({ auto: false }); } catch (/** @type {any} */ ex) { unauthenticated.set(true); logError(ex); return; } unauthenticated.set(!_user); if (!_user) { return; } user.set(_user); try { await _backend.fetchFiles(); // Reset error signInError.set({ message: '', canRetry: false }); } catch (/** @type {any} */ ex) { logError(ex); } };
Sign in with the given backend. @param {string} _backendName Backend name to be used.
signInManually
javascript
sveltia/sveltia-cms
src/lib/services/user/auth.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/user/auth.js
MIT
export const encodeFilePath = (path) => { const hasAtPrefix = path.startsWith('@'); if (hasAtPrefix) { path = path.slice(1); } path = path.split('/').map(encodeURIComponent).join('/'); if (hasAtPrefix) { return `@${path}`; } return path; };
Encode the given (partial) file path or file name. Since {@link encodeURIComponent} encodes slashes, we need to split and join. The `@` prefix is an exception; it shouldn’t be encoded. @param {string} path Original path. @returns {string} Encoded path.
encodeFilePath
javascript
sveltia/sveltia-cms
src/lib/services/utils/file.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/utils/file.js
MIT
export const decodeFilePath = (path) => decodeURIComponent(path);
Encode the given (partial) file path or file name. We can use {@link decodeURIComponent} as is. @param {string} path Original path. @returns {string} Decoded path.
decodeFilePath
javascript
sveltia/sveltia-cms
src/lib/services/utils/file.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/utils/file.js
MIT
export const sanitizeFileName = (name) => sanitize(name.normalize());
Sanitize the given file name for upload. @param {string} name Original name. @returns {string} Normalized name.
sanitizeFileName
javascript
sveltia/sveltia-cms
src/lib/services/utils/file.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/utils/file.js
MIT
export const renameIfNeeded = (name, otherNames) => { if (!otherNames.length) { return name; } const { filename: slug, extension } = getPathInfo(name); const regex = new RegExp( `^${escapeRegExp(slug)}(?:-(?<num>\\d+?))?${extension ? `\\.${extension}` : ''}$`, ); const dupName = otherNames .sort((a, b) => compare(a.split('.')[0], b.split('.')[0])) .findLast((p) => regex.test(p)); if (!dupName) { return name; } const number = Number(dupName.match(regex)?.groups?.num ?? 0) + 1; return `${slug}-${number}${extension ? `.${extension}` : ''}`; };
Check if the given file name or slug has duplicate(s) or its variant in the other names. If found, rename it by prepending a number like `summer-beach-2.jpg`. @param {string} name Original name. @param {string[]} otherNames Other names (of files in the same folder). @returns {string} Determined name.
renameIfNeeded
javascript
sveltia/sveltia-cms
src/lib/services/utils/file.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/utils/file.js
MIT
export const createPath = (segments) => segments.filter(Boolean).join('/');
Join the given path segments while ignoring any falsy value. @param {(string | null | undefined)[]} segments List of path segments. @returns {string} Path.
createPath
javascript
sveltia/sveltia-cms
src/lib/services/utils/file.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/utils/file.js
MIT
export const resolvePath = (path) => { /** @type {(string | null)[]} */ const segments = path.split('/'); let nameFound = false; segments.forEach((segment, index) => { if (segment === '.' || segment === '..') { if (nameFound) { segments[index] = null; if (segment === '..') { const lastIndex = segments.findLastIndex((s, i) => !!s && i < index); if (lastIndex > -1) { segments[lastIndex] = null; } } } } else { nameFound = true; } }); return createPath(segments); };
Resolve the given file path. This processes only dot(s) in the middle of the path; leading dots like `../../foo/image.jpg` will be untouched. @param {string} path Unresolved path, e.g. `foo/bar/baz/../../image.jpg`. @returns {string} Resolved path, e.g. `foo/image.jpg`.
resolvePath
javascript
sveltia/sveltia-cms
src/lib/services/utils/file.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/utils/file.js
MIT
export const sendRequest = async (url, init = {}, { responseType = 'json' } = {}) => { /** @type {Response} */ let response; init.cache = 'no-cache'; init.headers = new Headers(init.headers); if (responseType === 'json') { init.headers.set('Accept', 'application/json'); } if (init.method === 'POST' && isObject(init.body)) { init.headers.set('Content-Type', 'application/json'); init.body = JSON.stringify(init.body); } try { response = await fetch(url, init); } catch (ex) { throw new Error('Failed to send the request', { cause: ex }); } if (responseType === 'raw') { return response; } /** @type {any} */ let result; try { if (responseType === 'blob') { return response.blob(); } if (responseType === 'text') { return response.text(); } result = await response.json(); } catch (ex) { throw new Error('Failed to parse the response', { cause: ex }); } const { ok, status } = response; // Return the parsed result for a successful response, but a GraphQL error is typically returned // with 200 OK so we need to check the content for the `errors` key if (ok && !(url.endsWith('/graphql') && isObject(result) && result.errors)) { return result; } if (!isObject(result)) { throw new Error('Server responded with an error', { cause: { status } }); } let message = ''; if (typeof result.error === 'string') { message = result.error; } // Typical REST if (typeof result.message === 'string') { message = result.message; } if (Array.isArray(result.errors)) { if (typeof result.errors[0] === 'string') { message = result.errors.join(', '); } // Typical GraphQL if (isObject(result.errors[0]) && typeof result.errors[0].message === 'string') { message = /** @type {any[]} */ (result.errors).map((e) => e.message).join(', '); } } throw new Error('Server responded with an error', { cause: { status, message } }); };
A `fetch` wrapper to send an HTTP request to an API endpoint, parse the response as JSON or other specified format, and handle errors gracefully. @param {string} url URL. @param {RequestInit} [init] Request options. @param {object} [options] Options. @param {'json' | 'text' | 'blob' | 'raw'} [options.responseType] Response parser type. The default is `json`. Use `raw` to return a `Response` object as is. @returns {Promise<object | string | Blob | Response>} Response data or `Response` itself, depending on the `responseType` option. @throws {Error} When there was an error in the request or response.
sendRequest
javascript
sveltia/sveltia-cms
src/lib/services/utils/networking.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/utils/networking.js
MIT
export const resizeCanvas = (canvas, source, target) => { const { scale, width, height } = calculateResize(source, target); canvas.width = width; canvas.height = height; return { scale, width, height }; };
Resize a Canvas based on the given dimension. @param {HTMLCanvasElement | OffscreenCanvas} canvas Canvas to be resized. @param {{ width: number, height: number }} source Source dimensions. @param {{ width?: number, height?: number, fit?: ImageFitOption }} [target] Target dimensions and fit option. @returns {{ scale: number, width: number, height: number }} Scale and new width/height.
resizeCanvas
javascript
sveltia/sveltia-cms
src/lib/services/utils/media/image.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/utils/media/image.js
MIT
const checkIfEncodingIsSupported = async (format) => { if (format in encodingSupportMap) { return encodingSupportMap[format]; } const type = `image/${format}`; const canvas = new OffscreenCanvas(1, 1); // Need this for Chrome // eslint-disable-next-line no-unused-vars const context = /** @type {OffscreenCanvasRenderingContext2D} */ (canvas.getContext('2d')); const blob = await canvas.convertToBlob({ type }); const result = blob.type === type; encodingSupportMap[format] = result; return result; };
Check if the browser supports `canvas.convertToBlob()` encoding for the given format. @param {string} format Format, like `webp`. @returns {Promise<boolean>} Result.
checkIfEncodingIsSupported
javascript
sveltia/sveltia-cms
src/lib/services/utils/media/image.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/utils/media/image.js
MIT
export const exportCanvasAsBlob = async (canvas, { format = 'webp', quality = 85 } = {}) => { const type = `image/${format}`; if ( !(await checkIfEncodingIsSupported(format)) && /** @type {string[]} */ (rasterImageConversionFormats).includes(format) ) { const context = /** @type {OffscreenCanvasRenderingContext2D} */ (canvas.getContext('2d')); const imageData = context.getImageData(0, 0, canvas.width, canvas.height); try { /** @type {import('@jsquash/webp').encode} */ const encode = (await loadModule(`@jsquash/${format}`, '/encode.js?module')).default; const buffer = await encode(imageData, { quality }); return new Blob([buffer], { type }); } catch { // } } return canvas.convertToBlob({ type, quality: quality / 100 }); };
Export Canvas data as an image blob. If the browser doesn’t support native encoding for the given format (e.g. WebP on Safari), use the jSquash library as fallback. @param {OffscreenCanvas} canvas Canvas to be exported. @param {object} [options] Options. @param {string} [options.format] Format, like `webp`. @param {number} [options.quality] Image quality between 0 and 100. @returns {Promise<Blob>} Image blob. @see https://github.com/jamsinclair/jSquash
exportCanvasAsBlob
javascript
sveltia/sveltia-cms
src/lib/services/utils/media/image.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/utils/media/image.js
MIT
export const optimizeSVG = async (blob) => { const string = await blob.text(); try { /** @type {import('svgo')} */ const { optimize } = await loadModule('svgo', '/dist/svgo.browser.js'); const { data } = optimize(string); return new Blob([data], { type: blob.type }); } catch { // } return blob; };
Optimize a SVG image using the SVGO library. @param {File | Blob} blob Source file. @returns {Promise<Blob>} Optimized image file. @see https://github.com/svg/svgo/issues/1050
optimizeSVG
javascript
sveltia/sveltia-cms
src/lib/services/utils/media/image.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/utils/media/image.js
MIT
export const formatDuration = (duration) => new Date(duration * 1000).toISOString().substr(11, 8);
Format the given duration in the `hh:mm:ss` format. Note that it assumes the duration is less than 24 hours. @param {number} duration Duration in seconds. @returns {string} Formatted duration.
formatDuration
javascript
sveltia/sveltia-cms
src/lib/services/utils/media/video.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/utils/media/video.js
MIT
export const isYouTubeVideoURL = (string) => { if (!isURL(string)) { return false; } const { origin, pathname, searchParams } = new URL(string); if ( (origin === 'https://www.youtube.com' || origin === 'https://www.youtube-nocookie.com') && ((pathname === '/watch' && searchParams.has('v')) || (pathname === '/playlist' && searchParams.has('list')) || pathname.startsWith('/embed/')) ) { return true; } if (origin === 'https://youtu.be' && !!pathname) { return true; } return false; };
Check if the given string is a YouTube video URL. @param {string} string URL-like string. @returns {boolean} Result.
isYouTubeVideoURL
javascript
sveltia/sveltia-cms
src/lib/services/utils/media/video.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/utils/media/video.js
MIT
export const getYouTubeEmbedURL = (string) => { const origin = 'https://www.youtube-nocookie.com'; const { pathname, search, searchParams } = new URL(string); if (pathname === '/watch') { const params = new URLSearchParams(searchParams); let src = `${origin}/embed/${params.get('v')}`; if (params.get('list')) { params.delete('v'); params.set('listType', 'playlist'); src += `?${params.toString()}`; } return src; } if (pathname === '/playlist') { return `${origin}/embed/videoseries${search}`; } if (pathname.startsWith('/embed/')) { return `${origin}${pathname}${search}`; } // https://youtu.be return `${origin}/embed${pathname}${search}`; };
Get an embeddable YouTube video URL from the given string. @param {string} string URL-like string. @returns {string} URL with privacy-enhanced mode enabled.
getYouTubeEmbedURL
javascript
sveltia/sveltia-cms
src/lib/services/utils/media/video.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/utils/media/video.js
MIT
const format = (summary, options = {}) => getEntrySummary({ ...collection, summary }, entry, { locale: 'de', useTemplate: true, ...options, }); test('metadata', () => { expect(format('{{slug}}')).toEqual('net'); expect(format('{{dirname}}')).toEqual('net'); expect(format('{{filename}}')).toEqual('index'); expect(format('{{extension}}')).toEqual('md'); }); test('fields', () => { expect(format('{{title}}')).toEqual('.Net'); expect(format('{{fields.title}}')).toEqual('.Net'); expect(format('{{fields.slug}}')).toEqual('dotnet'); }); test('transformations', () => { expect(format("{{date | date('MMM D, YYYY')}}")).toEqual('Jan 23, 2024'); expect(format("{{draft | ternary('Draft', 'Public')}}")).toEqual('Public'); }); test('Markdown', () => { const markdownStr = 'This `code` on [GitHub](https://github.com/sveltia/sveltia-cms) _is_ ~~so~~ **good**!'; expect(format(markdownStr, { allowMarkdown: true })).toEqual( 'This <code>code</code> on GitHub <em>is</em> so <strong>good</strong>!', ); expect(format(markdownStr, { allowMarkdown: false })).toEqual( 'This code on GitHub is so good!', ); const charRefStr = '&laquo;ABC&shy;DEF&nbsp;GH&raquo;'; expect(format(charRefStr, { allowMarkdown: true })).toEqual('«ABC\u00adDEF\u00a0GH»'); expect(format(charRefStr, { allowMarkdown: false })).toEqual('«ABC\u00adDEF\u00a0GH»'); }); });
Wrapper for {@link getEntrySummary}. @param {string} summary Summary string template. @param {object} [options] Options. @returns {string} Formatted summary.
format
javascript
sveltia/sveltia-cms
src/lib/services/contents/entry/summary.spec.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/entry/summary.spec.js
MIT
export const getEntryThumbnail = async (collection, entry) => { const { _i18n: { defaultLocale }, _thumbnailFieldNames, } = collection; const { locales } = entry; const { content } = locales[defaultLocale] ?? Object.values(locales)[0] ?? {}; if (!content) { return undefined; } /** @type {FieldKeyPath[]} */ const keyPathList = _thumbnailFieldNames .map((name) => { // Support a wildcard in the key path, e.g. `images.*.src` if (name.includes('*')) { const regex = new RegExp(`^${escapeRegExp(name).replace('\\*', '.+')}$`); return Object.keys(content).filter((keyPath) => regex.test(keyPath)); } return name; }) .flat(1); // Cannot use `Promise.all` or `Promise.any` here because we need the first available URL // eslint-disable-next-line no-restricted-syntax for (const keyPath of keyPathList) { const url = content[keyPath] ? // eslint-disable-next-line no-await-in-loop await getMediaFieldURL(content[keyPath], entry, { thumbnail: true }) : undefined; if (url) { return url; } } return undefined; };
Get the given entry’s thumbnail URL. @param {EntryCollection} collection Entry’s collection. @param {Entry} entry Entry. @returns {Promise<string | undefined>} URL.
getEntryThumbnail
javascript
sveltia/sveltia-cms
src/lib/services/contents/entry/assets.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/entry/assets.js
MIT
const sanitizeEntrySummary = (str, { allowMarkdown = false } = {}) => { str = /** @type {string} */ (parseInline(str)); str = sanitize(str, { ALLOWED_TAGS: allowMarkdown ? ['strong', 'em', 'code'] : [] }); str = parseEntities(str); return str.trim(); };
Parse the given entry summary as Markdown and sanitize HTML with a few exceptions if the Markdown option is enabled. Also, parse HTML character references (entities). @param {string} str Original string. @param {object} [options] Options. @param {boolean} [options.allowMarkdown] Whether to allow Markdown and return HTML string. @returns {string} Parsed string.
sanitizeEntrySummary
javascript
sveltia/sveltia-cms
src/lib/services/contents/entry/summary.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/entry/summary.js
MIT
export const getI18nConfig = (collection, file) => { const _siteConfig = /** @type {InternalSiteConfig} */ (get(siteConfig)); /** @type {I18nOptions | undefined} */ let config; if (isObject(_siteConfig.i18n)) { config = /** @type {I18nOptions} */ (_siteConfig.i18n); if (collection.i18n) { if (isObject(collection.i18n)) { Object.assign(config, collection.i18n); } if (file) { if (file.i18n) { if (isObject(file.i18n)) { Object.assign(config, file.i18n); } } else { config = undefined; } } } else { config = undefined; } } const { structure: _structure = 'single_file', locales: _locales = [], default_locale: _defaultLocale = undefined, initial_locales: _initialLocales = undefined, save_all_locales: _saveAllLocales = true, canonical_slug: { key: canonicalSlugKey = 'translationKey', value: canonicalSlugTemplate = '{{slug}}', } = {}, } = /** @type {I18nOptions} */ (config ?? {}); const i18nEnabled = !!_locales.length; const allLocales = i18nEnabled ? _locales : ['_default']; const saveAllLocales = i18nEnabled ? _saveAllLocales === true && _initialLocales === undefined : true; const defaultLocale = !i18nEnabled ? '_default' : _defaultLocale && allLocales.includes(_defaultLocale) ? _defaultLocale : allLocales[0]; const initialLocales = _initialLocales === 'all' ? allLocales : _initialLocales === 'default' ? [defaultLocale] : allLocales.filter( (locale) => // Default locale cannot be disabled locale === defaultLocale || (Array.isArray(_initialLocales) ? _initialLocales.includes(locale) : true), ); const structure = !file ? _structure : file.file.includes('{{locale}}') ? 'multiple_files' : 'single_file'; return { i18nEnabled, saveAllLocales, allLocales, defaultLocale, initialLocales, structure, canonicalSlug: { key: canonicalSlugKey, value: canonicalSlugTemplate, }, }; };
Get the normalized i18n configuration for the given collection or collection file. @param {Collection} collection Developer-defined collection. @param {CollectionFile} [file] Developer-defined collection file. @returns {InternalI18nOptions} Config. @see https://decapcms.org/docs/i18n/
getI18nConfig
javascript
sveltia/sveltia-cms
src/lib/services/contents/i18n/index.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/i18n/index.js
MIT
export const getCanonicalLocale = (locale) => { let canonicalLocale = undefined; if (locale !== '_default') { try { [canonicalLocale] = Intl.getCanonicalLocales(locale); } catch { // } } return canonicalLocale; };
Get the canonical locale of the given locale that can be used for various `Intl` methods. @param {InternalLocaleCode} locale Locale. @returns {LocaleCode | undefined} Locale or `undefined` if not determined. @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument
getCanonicalLocale
javascript
sveltia/sveltia-cms
src/lib/services/contents/i18n/index.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/i18n/index.js
MIT
export const getLocaleLabel = (locale) => { const canonicalLocale = getCanonicalLocale(locale); if (!canonicalLocale) { return locale; } const formatter = new Intl.DisplayNames(/** @type {string} */ (get(appLocale)), { type: 'language', }); try { return formatter.of(canonicalLocale) ?? locale; } catch (/** @type {any} */ ex) { // eslint-disable-next-line no-console console.error(ex); return locale; } };
Translate the given locale code in the application UI locale. @param {InternalLocaleCode} locale Locale code like `en`. @returns {string} Locale label like `English`. If the formatter raises an error, just return the locale code as is.
getLocaleLabel
javascript
sveltia/sveltia-cms
src/lib/services/contents/i18n/index.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/i18n/index.js
MIT
const removeMarkdownChars = (str) => str.replace(/[_*`]+/g, ''); /** * Sort the given entries. * @param {Entry[]} entries Entry list. * @param {InternalCollection} collection Collection that the entries belong to. * @param {SortingConditions} [conditions] Sorting conditions. * @returns {Entry[]} Sorted entry list. * @see https://decapcms.org/docs/configuration-options/#sortable_fields */ const sortEntries = (entries, collection, { key, order } = {}) => { const _entries = [...entries]; const { name: collectionName, _i18n: { defaultLocale: locale }, } = collection; if (key === undefined) { const options = { useTemplate: true, allowMarkdown: true }; return _entries.sort((a, b) => getEntrySummary(collection, a, options).localeCompare( getEntrySummary(collection, b, options), ), ); } const type = { slug: String, commit_author: String, commit_date: Date }[key] || (_entries.length ? getPropertyValue({ entry: _entries[0], locale, collectionName, key })?.constructor : String) || String; const valueMap = Object.fromEntries( _entries.map((entry) => [entry.slug, getPropertyValue({ entry, locale, collectionName, key })]), ); const fieldConfig = getFieldConfig({ collectionName, keyPath: key }); const dateFieldConfig = fieldConfig?.widget === 'datetime' ? /** @type {DateTimeField} */ (fieldConfig) : undefined; _entries.sort((a, b) => { const aValue = valueMap[a.slug]; const bValue = valueMap[b.slug]; if (aValue === undefined || bValue === undefined) { return 0; } if (dateFieldConfig) { const aDate = getDate(aValue, dateFieldConfig); const bDate = getDate(bValue, dateFieldConfig); if (aDate && bDate) { return Number(aDate) - Number(bDate); } } if (type === String) { return compare(removeMarkdownChars(aValue), removeMarkdownChars(bValue)); } if (type === Date) { return Number(aValue) - Number(bValue); } return aValue - bValue; }); if (order === 'descending') { _entries.reverse(); } return _entries; }; /** * Filter the given entries. * @param {Entry[]} entries Entry list. * @param {InternalCollection} collection Collection that the entries belong to. * @param {FilteringConditions[]} filters One or more filtering conditions. * @returns {Entry[]} Filtered entry list. * @see https://decapcms.org/docs/configuration-options/#view_filters */ const filterEntries = (entries, collection, filters) => { const { name: collectionName, view_filters: configuredFilters = [], _i18n: { defaultLocale: locale }, } = collection; // Ignore invalid filters const validFilters = filters.filter( ({ field, pattern }) => field !== undefined && pattern !== undefined && configuredFilters.some((f) => f.field === field && f.pattern === pattern), ); return entries.filter((entry) => validFilters.every(({ field, pattern }) => { // Check both the raw value and referenced value const args = { entry, locale, collectionName, key: field }; const rawValue = getPropertyValue({ ...args, resolveRef: false }); const refValue = getPropertyValue({ ...args }); const regex = typeof pattern === 'string' ? new RegExp(pattern) : undefined; if (rawValue === undefined || refValue === undefined) { return false; } if (regex) { return regex.test(String(rawValue)) || regex.test(String(refValue)); } return rawValue === pattern || refValue === pattern; }), ); }; /** * Group the given entries. * @param {Entry[]} entries Entry list. * @param {InternalCollection} collection Collection that the entries belong to. * @param {GroupingConditions} [conditions] Grouping conditions. * @returns {{ name: string, entries: Entry[] }[]} Grouped entries, where each group object contains * a name and an entry list. When ungrouped, there will still be one group object named `*`. * @see https://decapcms.org/docs/configuration-options/#view_groups */ const groupEntries = ( entries, collection, { field, pattern } = { field: '', pattern: undefined }, ) => { if (!field) { return entries.length ? [{ name: '*', entries }] : []; } const { name: collectionName, _i18n: { defaultLocale: locale }, } = collection; const sortCondition = get(currentView).sort; const regex = typeof pattern === 'string' ? new RegExp(pattern) : undefined; /** @type {Record<string, Entry[]>} */ const groups = {}; const otherKey = get(_)('other'); entries.forEach((entry) => { const value = getPropertyValue({ entry, locale, collectionName, key: field }); const key = value === undefined ? otherKey : regex ? (String(value).match(regex)?.[0] ?? otherKey) : String(value); if (!(key in groups)) { groups[key] = []; } groups[key].push(entry); }); // Sort groups by key const sortedGroups = Object.entries(groups) .map(([name, _entries]) => ({ name, entries: _entries })) .sort(({ name: aKey }, { name: bKey }) => compare(aKey, bKey)); // Keep the descending order if already sorted, especially on the date field if (sortCondition?.key === field && sortCondition.order === 'descending') { sortedGroups.reverse(); } return sortedGroups; }; /** * View settings for all the folder collections. * @type {Writable<Record<string, EntryListView> | undefined>} */ const entryListSettings = writable(); /** * Get sortable fields for the given collection. * @param {EntryCollection} collection Collection. * @returns {{ fields: string[], default: SortingConditions }} A list of sortable fields and default * sort conditions. */ export const getSortableFields = (collection) => { const { name: collectionName, identifier_field: customIdField, sortable_fields: customSortableFields, } = collection; /** @type {string[]} */ let fields = []; /** @type {string | undefined} */ let defaultKey; /** @type {SortOrder | undefined} */ let defaultOrder; if (customSortableFields) { if (Array.isArray(customSortableFields)) { fields = customSortableFields; } if (isObject(customSortableFields)) { const def = /** @type {SortableFields} */ (customSortableFields); if (Array.isArray(def.fields)) { fields = def.fields; } if (def.default && isObject(def.default)) { defaultKey = def.default.field; defaultOrder = ['descending', 'Descending'].includes(def.default.direction ?? '') ? 'descending' : 'ascending'; } } } else { fields = [...defaultSortableFields]; if (customIdField) { fields.unshift(customIdField); defaultKey = customIdField; } } // Make sure the fields exist fields = unique(fields).filter((keyPath) => !!getFieldConfig({ collectionName, keyPath })); return { fields, default: { key: defaultKey ?? fields[0], order: defaultOrder ?? 'ascending', }, }; }; /** * Get a field’s label by key. * @param {EntryCollection} collection Collection. * @param {FieldKeyPath | string} key Field key path or one of other entry metadata property keys: * `slug`, `commit_author` and `commit_date`. * @returns {string} Label. For a nested field, it would be something like `Name – English`. */ const getSortFieldLabel = (collection, key) => { if (['name', 'commit_author', 'commit_date'].includes(key)) { return get(_)(`sort_keys.${key}`); } if (key.includes('.')) { return key .split('.') .map((_key, index, arr) => { if (/^\d+$/.test(_key)) { return undefined; }
Remove some Markdown syntax characters from the given string for proper sorting. This includes bold, italic and code that might appear in the entry title. @param {string} str Original string. @returns {string} Modified string.
removeMarkdownChars
javascript
sveltia/sveltia-cms
src/lib/services/contents/collection/view.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/collection/view.js
MIT
export const getEntriesByCollection = (collectionName) => { const collection = getCollection(collectionName); if (!collection) { return []; } const { filter, _i18n: { defaultLocale: locale }, } = collection; const filterField = filter?.field; const filterPattern = typeof filter?.pattern === 'string' ? new RegExp(filter.pattern) : undefined; const filterValues = filter?.value === undefined ? [] : Array.isArray(filter.value) ? filter.value : [filter.value]; return get(allEntries).filter((entry) => { if (!getAssociatedCollections(entry).some(({ name }) => name === collectionName)) { return false; } if (!filterField) { return true; } const value = getPropertyValue({ entry, locale, collectionName, key: filterField }) ?? null; if (filterPattern) { return filterPattern.test(value); } return filterValues.includes(value); }); };
Get entries by the given collection name, while applying a filer if needed. @param {string} collectionName Collection name. @returns {Entry[]} Entries. @see https://decapcms.org/docs/collection-folder/#filtered-folder-collections
getEntriesByCollection
javascript
sveltia/sveltia-cms
src/lib/services/contents/collection/entries.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/collection/entries.js
MIT
const hasAsset = async (collectionFile) => { const field = getFieldConfig({ ...getFieldConfigArgs, fileName: collectionFile?.name, }); if (!field) { return false; } const { widget: widgetName = 'string' } = field; if (['image', 'file'].includes(widgetName)) { const match = (await getMediaFieldURL(value, entry)) === assetURL; if (match && newURL) { content[keyPath] = newURL; } return match; } // Search images in markdown body if (widgetName === 'markdown') { const matches = [...value.matchAll(markdownImageRegEx)]; if (matches.length) { return ( await Promise.all( matches.map(async ([, src]) => { const match = (await getMediaFieldURL(src, entry)) === assetURL; if (match && newURL) { content[keyPath] = content[keyPath].replace(src, newURL); } return match; }), ) ).some(Boolean); } } return false; };
Check if the field contains the asset. @param {InternalCollectionFile} [collectionFile] Collection file. File collection only. @returns {Promise<boolean>} Result.
hasAsset
javascript
sveltia/sveltia-cms
src/lib/services/contents/collection/entries.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/collection/entries.js
MIT
export const getFilesByEntry = (collection, entry) => { const _fileMap = collection.files ? /** @type {FileCollection} */ (collection)._fileMap : undefined; if (!_fileMap) { // It’s an entry collection return []; } return Object.values(_fileMap).filter( ({ _file, _i18n }) => _file.fullPath === entry.locales[_i18n.defaultLocale]?.path, ); };
Get a file collection’s file configurations that matches the given entry. One file can theoretically appear in multiple collections files depending on the configuration, so that the result is an array. @param {InternalCollection} collection Collection. @param {Entry} entry Entry. @returns {InternalCollectionFile[]} Collection files.
getFilesByEntry
javascript
sveltia/sveltia-cms
src/lib/services/contents/collection/files.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/collection/files.js
MIT
const getThumbnailFieldNames = (rawCollection) => { const { folder, fields, thumbnail } = rawCollection; if (!folder) { return []; } if (typeof thumbnail === 'string') { return [thumbnail]; } // Support multiple field names if (Array.isArray(thumbnail)) { return thumbnail; } // Collect the names of all non-nested Image/File fields for inference if (fields?.length) { return fields .filter(({ widget = 'string' }) => ['image', 'file'].includes(widget)) .map(({ name }) => name); } return []; };
Get a list of field key paths to be used to find an entry thumbnail. @param {Collection} rawCollection Raw collection definition. @returns {FieldKeyPath[]} Key path list.
getThumbnailFieldNames
javascript
sveltia/sveltia-cms
src/lib/services/contents/collection/index.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/collection/index.js
MIT
const copy = (omitEmptyOptionalFields = false) => { /** @type {FlattenedEntryContent} */ const sortedMap = {}; /** @type {FlattenedEntryContent} */ const unsortedMap = { ...structuredClone(content), 'variables.foo': 'foo', 'variables.bar': 'bar', }; const args = { locale: 'en', unsortedMap, sortedMap, isTomlOutput: false, omitEmptyOptionalFields, }; fields.forEach((field) => { copyProperty({ ...args, key: field.name, field }); }); return sortedMap; }; test('omit option unspecified', () => { expect(copy()).toEqual(content); }); test('omit option disabled', () => { expect(copy(false)).toEqual(content); }); test('omit option enabled', () => { // Here `variables.X` are not included but that’s fine; it’s done is `finalizeContent` expect(copy(true)).toEqual({ title: 'My Post', variables: {} }); }); });
Wrapper for {@link copyProperty}. @param {boolean} [omitEmptyOptionalFields] The omit option. @returns {FlattenedEntryContent} Copied content. Note: It’s not sorted here because sorting is done in `finalizeContent`.
copy
javascript
sveltia/sveltia-cms
src/lib/services/contents/draft/save.spec.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/draft/save.spec.js
MIT
get: (obj, prop) => (prop === 'valid' ? !Object.values(obj).some(Boolean) : obj[prop]), }, ); validities[locale][keyPath] = validity; if (!validity.valid) { validated = false; } }; valueEntries.forEach(([keyPath, value]) => { validateField(keyPath, value); }); }); /** @type {Writable<EntryDraft>} */ (entryDraft).update((_draft) => ({ ..._draft, validities })); return validated; };
Getter. @param {Record<string, boolean>} obj Object itself. @param {string} prop Property name. @returns {boolean | undefined} Property value.
=>.some ( Boolean )
javascript
sveltia/sveltia-cms
src/lib/services/contents/draft/validate.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/draft/validate.js
MIT
export const deleteBackup = async (collectionName, slug = '') => { await backupDB?.delete([collectionName, slug]); };
Delete a draft stored in IndexedDB. @param {string} collectionName Collection name. @param {string} [slug] Entry slug. Existing entry only. @returns {Promise<void>} Result.
deleteBackup
javascript
sveltia/sveltia-cms
src/lib/services/contents/draft/backup.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/draft/backup.js
MIT
export const getBackup = async (collectionName, slug = '') => { /** @type {EntryDraftBackup | undefined} */ const backup = await backupDB?.get([collectionName, slug]); if (!backup) { return null; } if (backup.siteConfigVersion === get(siteConfigVersion)) { return backup; } // Discard the backup if the site configuration has been changed since the backup was created, // because there is a risk of data corruption await deleteBackup(collectionName, slug); return null; };
Get a draft backup stored in IndexedDB. @param {string} collectionName Collection name. @param {string} [slug] Entry slug. Existing entry only. @returns {Promise<EntryDraftBackup | null>} Backup.
getBackup
javascript
sveltia/sveltia-cms
src/lib/services/contents/draft/backup.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/draft/backup.js
MIT
export const showBackupToastIfNeeded = async () => { if (!(get(prefs).useDraftBackup ?? true)) { return; } const draft = get(entryDraft); if (!draft || get(backupToastState).saved) { return; } const { collectionName, originalEntry } = draft; const backup = await getBackup(collectionName, originalEntry?.slug); if (backup) { backupToastState.set({ restored: false, deleted: false, saved: true }); } };
Check if the current entry’s draft backup has been saved, and if so, show a toast notification.
showBackupToastIfNeeded
javascript
sveltia/sveltia-cms
src/lib/services/contents/draft/backup.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/draft/backup.js
MIT
export const syncExpanderStates = (stateMap) => { entryDraft.update((_draft) => { if (_draft) { Object.entries(stateMap).forEach(([keyPath, expanded]) => { if (_draft.expanderStates._[keyPath] !== expanded) { _draft.expanderStates._[keyPath] = expanded; } }); } return _draft; }); };
Sync the field object/list expander states between locales. @param {Record<FieldKeyPath, boolean>} stateMap Map of key path and state.
syncExpanderStates
javascript
sveltia/sveltia-cms
src/lib/services/contents/draft/editor.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/draft/editor.js
MIT
export const expandInvalidFields = ({ collectionName, fileName, currentValues }) => { const { validities } = /** @type {EntryDraft} */ (get(entryDraft)); /** @type {Record<FieldKeyPath, boolean>} */ const stateMap = {}; Object.entries(validities ?? {}).forEach(([locale, validityMap]) => { Object.entries(validityMap).forEach(([keyPath, { valid }]) => { if (!valid) { getExpanderKeys({ collectionName, fileName, valueMap: currentValues[locale], keyPath, }).forEach((key) => { stateMap[key] = true; }); } }); }); syncExpanderStates(stateMap); };
Expand any invalid fields, including the parent list/object(s). @param {object} args Partial arguments for {@link getFieldConfig}. @param {string} args.collectionName Collection name. @param {string} [args.fileName] File name. @param {LocaleContentMap} args.currentValues Field values.
expandInvalidFields
javascript
sveltia/sveltia-cms
src/lib/services/contents/draft/editor.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/draft/editor.js
MIT
const initSettings = async ({ repository }) => { const { databaseName } = repository ?? {}; const settingsDB = databaseName ? new IndexedDB(databaseName, 'ui-settings') : null; const storageKey = 'entry-view'; const settings = { showPreview: true, syncScrolling: true, selectAssetsView: { type: 'grid' }, ...((await settingsDB?.get(storageKey)) ?? {}), };
Initialize {@link entryEditorSettings}, {@link selectAssetsView} and relevant subscribers. @param {BackendService} _backend Backend service.
initSettings
javascript
sveltia/sveltia-cms
src/lib/services/contents/draft/editor.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/draft/editor.js
MIT
const updateObject = (obj, newProps) => { Object.entries(newProps).forEach(([key, value]) => { if (obj[key] !== value) { obj[key] = value; } }); Object.keys(obj).forEach((key) => { if (!(key in newProps)) { delete obj[key]; } }); };
Update a flatten object with new properties by adding, updating and deleting properties. @param {Record<string, any>} obj Original object. @param {Record<string, any>} newProps New properties.
updateObject
javascript
sveltia/sveltia-cms
src/lib/services/contents/draft/update.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/draft/update.js
MIT
const getItemList = (obj, keyPath) => { const regex = new RegExp(`^${escapeRegExp(keyPath)}\\b(?!#)`); const filtered = Object.entries(obj) .filter(([k]) => regex.test(k)) .map(([k, v]) => [k.replace(regex, '_'), v]) .sort(); return [ unflatten(Object.fromEntries(filtered))._ ?? [], Object.fromEntries(Object.entries(obj).filter(([k]) => !regex.test(k))), ]; };
Traverse the given object by decoding dot-notated key path. @param {any} obj Original object. @param {FieldKeyPath} keyPath Dot-notated field name. @returns {[values: any, remainder: any]} Unflatten values and flatten remainder.
getItemList
javascript
sveltia/sveltia-cms
src/lib/services/contents/draft/update.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/draft/update.js
MIT
export const toggleLocale = (locale) => { /** @type {Writable<EntryDraft>} */ (entryDraft).update((_draft) => { const { fields, currentLocales, currentValues, validities } = _draft; const enabled = !currentLocales[locale]; // Initialize the content for the locale if (enabled && !currentValues[locale]) { const { collectionName, fileName, originalValues } = _draft; const newContent = getDefaultValues(fields, locale); return { ..._draft, currentLocales: { ...currentLocales, [locale]: enabled }, originalValues: { ...originalValues, [locale]: newContent }, currentValues: { ...currentValues, [locale]: createProxy({ draft: { collectionName, fileName }, locale, target: copyDefaultLocaleValues(newContent), }), }, }; } return { ..._draft, currentLocales: { ...currentLocales, [locale]: enabled }, validities: { ...validities, [locale]: {} }, }; });
Enable or disable the given locale’s content output for the current entry draft. @param {InternalLocaleCode} locale Locale.
toggleLocale
javascript
sveltia/sveltia-cms
src/lib/services/contents/draft/update.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/draft/update.js
MIT
const updateToast = (status, message) => { copyFromLocaleToast.set({ id: Date.now(), show: true, status, message, count, sourceLocale, }); }; if (!count) { updateToast('info', `${operationType}.none`); return; } if (translate) { const _translator = get(translator); const apiKey = get(prefs).apiKeys?.[_translator.serviceId] || (await new Promise((resolve) => { // The promise will be resolved once the user enters an API key on the dialog translatorApiKeyDialogState.set({ show: true, multiple: count > 1, resolve }); })); if (!apiKey) { return; } updateToast('info', 'translation.started'); try { const translatedValues = await _translator.translate(Object.values(copingFields), { apiKey, sourceLocale, targetLocale, }); Object.keys(copingFields).forEach((_keyPath, index) => { currentValues[targetLocale][_keyPath] = translatedValues[index]; }); updateToast('success', `translation.complete.${countType}`); } catch (/** @type {any} */ ex) { // @todo Show a detailed error message. // @see https://www.deepl.com/docs-api/api-access/error-handling/ updateToast('error', 'translation.error'); // eslint-disable-next-line no-console console.error(ex); } } else { Object.entries(copingFields).forEach(([_keyPath, value]) => { currentValues[targetLocale][_keyPath] = value; }); updateToast('success', `copy.complete.${countType}`); } /** @type {Writable<EntryDraft>} */ (entryDraft).update((_draft) => ({ ..._draft, currentValues, })); };
Update the toast notification. @param {'info' | 'success' | 'error'} status Status. @param {string} message Message key.
updateToast
javascript
sveltia/sveltia-cms
src/lib/services/contents/draft/update.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/draft/update.js
MIT
const revert = (_locale, valueMap, reset = false) => { const getFieldConfigArgs = { collectionName: collection.name, fileName, valueMap }; Object.entries(valueMap).forEach(([_keyPath, value]) => { if (!keyPath || _keyPath.startsWith(keyPath)) { const fieldConfig = getFieldConfig({ ...getFieldConfigArgs, keyPath: _keyPath }); if (_locale === defaultLocale || [true, 'translate'].includes(fieldConfig?.i18n ?? false)) { if (reset) { delete currentValues[_locale][_keyPath]; } else { currentValues[_locale][_keyPath] = value; } } } }); };
Revert changes. @param {InternalLocaleCode} _locale Iterating locale. @param {FlattenedEntryContent} valueMap Flattened entry content. @param {boolean} reset Whether ro remove the current value.
revert
javascript
sveltia/sveltia-cms
src/lib/services/contents/draft/update.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/draft/update.js
MIT
const fillList = () => { newContent[keyPath] = []; value.split(/,\s*/).forEach((val, index) => { newContent[`${keyPath}.${index}`] = val; }); }; if (widgetName === 'boolean') { newContent[keyPath] = value === 'true'; return; } if (widgetName === 'list') { const { field: subField, fields: subFields, types } = /** @type {ListField} */ (fieldConfig); const hasSubFields = !!subField || !!subFields || !!types; // Handle simple list if (!hasSubFields) { fillList(); return; } } if (widgetName === 'markdown') { // Sanitize the given value to prevent XSS attacks as the preview may not be sanitized newContent[keyPath] = stripTags(value); return; } if (widgetName === 'number') { const { value_type: valueType = 'int' } = /** @type {NumberField} */ (fieldConfig); if (valueType === 'int' || valueType === 'float') { const val = valueType === 'int' ? Number.parseInt(value, 10) : Number.parseFloat(value); if (!Number.isNaN(val)) { newContent[keyPath] = val; } } else { newContent[keyPath] = value; } return; } if (widgetName === 'relation' || widgetName === 'select') { const { multiple = false } = /** @type {RelationField | SelectField} */ (fieldConfig); if (multiple) { fillList(); return; } } // Just use the string as is newContent[keyPath] = value; };
Parse the value as a list and add the items to the key-value map.
fillList
javascript
sveltia/sveltia-cms
src/lib/services/contents/draft/create.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/draft/create.js
MIT
export const getDefaultValues = (fields, locale, dynamicValues = {}) => { /** @type {FlattenedEntryContent} */ const newContent = {}; fields.forEach((fieldConfig) => { populateDefaultValue({ newContent, keyPath: fieldConfig.name, fieldConfig, locale, dynamicValues, }); }); return newContent; };
Get the default values for the given fields. If dynamic default values are given, these values take precedence over static default values defined with the site configuration. @param {Field[]} fields Field list of a collection. @param {InternalLocaleCode} locale Locale. @param {Record<string, string>} [dynamicValues] Dynamic default values. @returns {FlattenedEntryContent} Flattened entry content for creating a new draft content or adding a new list item. @todo Make this more diligent.
getDefaultValues
javascript
sveltia/sveltia-cms
src/lib/services/contents/draft/create.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/draft/create.js
MIT
export const entryDraftModified = derived([entryDraft], ([draft]) => { if (!draft) { return false; } const { originalLocales, currentLocales, originalSlugs, currentSlugs, originalValues, currentValues, } = draft; return ( !equal(originalLocales, currentLocales) || !equal(originalSlugs, currentSlugs) || !equal(originalValues, currentValues) ); });
Whether the current {@link entryDraft} has been modified. @type {Readable<boolean>}
(anonymous)
javascript
sveltia/sveltia-cms
src/lib/services/contents/draft/index.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/draft/index.js
MIT
const getSlug = ({ subPath, subPathTemplate }) => { if (subPathTemplate?.includes('{{slug}}')) { const [, slug] = subPath.match( new RegExp(`^${escapeRegExp(subPathTemplate).replace('\\{\\{slug\\}\\}', '(.+)')}$`), ) ?? []; if (slug) { return slug; } } return subPath; };
Determine the slug for the given entry content. @param {object} args Arguments. @param {string} args.subPath File path without the collection folder, locale and extension. It’s a slug in most cases, but it may be a path containing slash(es) when the Folder Collections Path is configured. @param {string | undefined} args.subPathTemplate Collection’s `subPath` configuration. @returns {string} Slug. @see https://decapcms.org/docs/configuration-options/#slug @see https://decapcms.org/docs/collection-folder/#folder-collections-path
getSlug
javascript
sveltia/sveltia-cms
src/lib/services/contents/file/process.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/file/process.js
MIT
const parseJSON = (str) => JSON.parse(str);
Parse a JSON document using the built-in method. @param {string} str JSON document. @returns {any} Parsed object.
parseJSON
javascript
sveltia/sveltia-cms
src/lib/services/contents/file/parse.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/file/parse.js
MIT
const parseTOML = (str) => toRaw(TOML.parse(str));
Parse a TOML document using a library. The TOML parser returns date fields as `Date` objects, but we need strings to match the JSON and YAML parsers, so we have to parse twice. @param {string} str TOML document. @returns {any} Parsed object.
parseTOML
javascript
sveltia/sveltia-cms
src/lib/services/contents/file/parse.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/file/parse.js
MIT
const parseYAML = (str) => YAML.parse(str);
Parse a YAML document using a library. @param {string} str YAML document. @returns {any} Parsed object.
parseYAML
javascript
sveltia/sveltia-cms
src/lib/services/contents/file/parse.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/file/parse.js
MIT
const detectFrontMatterFormat = (text) => { if (text.startsWith('+++')) { return 'toml-frontmatter'; } if (text.startsWith('{')) { return 'json-frontmatter'; } return 'yaml-frontmatter'; };
Detect the Markdown front matter serialization format by checking a delimiter in the content. @param {string} text File content. @returns {FrontMatterFormat} Determined format.
detectFrontMatterFormat
javascript
sveltia/sveltia-cms
src/lib/services/contents/file/parse.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/file/parse.js
MIT
export const formatTOML = (obj) => TOML.stringify(obj).trim();
Format the given object as a TOML document using a library. @param {any} obj Object to be formatted. @returns {string} Formatted document. @see https://github.com/squirrelchat/smol-toml
formatTOML
javascript
sveltia/sveltia-cms
src/lib/services/contents/file/format.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/file/format.js
MIT
export const formatEntryFile = async ({ content, _file }) => { const { format, fmDelimiters, yamlQuote = false } = _file; const customFormatter = customFileFormats[format]?.formatter; if (customFormatter) { return `${(await customFormatter(content)).trim()}\n`; } try { if (/^ya?ml$/.test(format)) { return `${formatYAML(content, undefined, { quote: yamlQuote })}\n`; } if (format === 'toml') { return `${formatTOML(content)}\n`; } if (format === 'json') { return `${formatJSON(content)}\n`; } } catch (/** @type {any} */ ex) { // eslint-disable-next-line no-console console.error(ex); return ''; } if (/^(?:(?:yaml|toml|json)-)?frontmatter$/.test(format)) { const [sd, ed] = fmDelimiters ?? ['---', '---']; const body = typeof content.body === 'string' ? content.body : ''; delete content.body; // Support Markdown without a front matter block, particularly for VitePress if (!Object.keys(content).length) { return `${body}\n`; } try { if (format === 'frontmatter' || format === 'yaml-frontmatter') { return `${sd}\n${formatYAML(content, undefined, { quote: yamlQuote })}\n${ed}\n${body}\n`; } if (format === 'toml-frontmatter') { return `${sd}\n${formatTOML(content)}\n${ed}\n${body}\n`; } if (format === 'json-frontmatter') { return `${sd}\n${formatJSON(content)}\n${ed}\n${body}\n`; } } catch (/** @type {any} */ ex) { // eslint-disable-next-line no-console console.error(ex); } } return ''; };
Format raw entry content. @param {object} entry File entry. @param {RawEntryContent | Record<InternalLocaleCode, RawEntryContent>} entry.content Content object. Note that this method may modify the `content` (the `body` property will be removed if exists) so it shouldn’t be a reference to an existing object. @param {FileConfig} entry._file Entry file configuration. @returns {Promise<string>} Formatted string.
formatEntryFile
javascript
sveltia/sveltia-cms
src/lib/services/contents/file/format.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/file/format.js
MIT
const detectFileExtension = ({ extension, format, path }) => { const customExtension = format ? customFileFormats[format]?.extension : undefined; if (customExtension) { return customExtension; } if (extension) { return extension; } if (path) { return getPathInfo(path).extension ?? 'md'; } if (format === 'yaml' || format === 'yml') { return 'yml'; } if (format === 'toml') { return 'toml'; } if (format === 'json') { return 'json'; } return 'md'; };
Detect a file extension from the given entry file configuration. @param {object} args Arguments. @param {FileExtension} [args.extension] Developer-defined file extension. @param {FileFormat} [args.format] Developer-defined file format. @param {string} [args.path] File path, e.g. `about.json`. @returns {FileExtension} Determined extension. @see https://decapcms.org/docs/configuration-options/#extension-and-format
detectFileExtension
javascript
sveltia/sveltia-cms
src/lib/services/contents/file/index.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/file/index.js
MIT
const detectFileFormat = ({ extension, format }) => { if (format) { return format; // supported or custom format } if (extension === 'yaml' || extension === 'yml') { return 'yaml'; } if (extension === 'toml') { return 'toml'; } if (extension === 'json') { return 'json'; } if (['md', 'mkd', 'mkdn', 'mdwn', 'mdown', 'markdown'].includes(extension)) { return 'frontmatter'; // auto detect } return 'yaml-frontmatter'; };
Detect a file format from the given entry file configuration. @param {object} args Arguments. @param {FileExtension} args.extension File extension. @param {FileFormat} [args.format] Developer-defined file format. @returns {FileFormat} Determined format. @see https://decapcms.org/docs/configuration-options/#extension-and-format
detectFileFormat
javascript
sveltia/sveltia-cms
src/lib/services/contents/file/index.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/file/index.js
MIT
const getEntryPathRegEx = ({ extension, format, basePath, subPath, _i18n }) => { const { i18nEnabled, structure, allLocales } = _i18n; const i18nMultiFile = i18nEnabled && structure === 'multiple_files'; const i18nMultiFolder = i18nEnabled && structure === 'multiple_folders'; const i18nRootMultiFolder = i18nEnabled && structure === 'multiple_folders_i18n_root'; /** * The path pattern in the middle, which should match the filename (without extension), * possibly with the parent directory. If the collection’s `path` is configured, use it to * generate a pattern, so that unrelated files are excluded. * @see https://decapcms.org/docs/collection-folder/#folder-collections-path */ const filePathMatcher = subPath ? `(?<subPath>${subPath.replace(/\//g, '\\/').replace(/{{.+?}}/g, '[^/]+')})` : '(?<subPath>.+)'; const localeMatcher = `(?<locale>${allLocales.join('|')})`; const pattern = [ '^', i18nRootMultiFolder ? `${localeMatcher}\\/` : '', basePath ? `${escapeRegExp(basePath)}\\/` : '', i18nMultiFolder ? `${localeMatcher}\\/` : '', filePathMatcher, i18nMultiFile ? `\\.${localeMatcher}` : '', '\\.', detectFileExtension({ format, extension }), '$', ].join(''); return new RegExp(pattern); };
Get a regular expression that matches the entry paths of the given entry collection, taking the i18n structure into account. @param {object} args Arguments. @param {FileExtension} args.extension File extension. @param {FileFormat} args.format File format. @param {string} args.basePath Normalized `folder` collection option. @param {string} [args.subPath] Normalized `path` collection option. @param {InternalI18nOptions} args._i18n I18n configuration. @returns {RegExp} Regular expression.
getEntryPathRegEx
javascript
sveltia/sveltia-cms
src/lib/services/contents/file/index.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/file/index.js
MIT
export const getFrontMatterDelimiters = ({ format, delimiter }) => { if (typeof delimiter === 'string' && delimiter.trim()) { return [delimiter, delimiter]; } if (Array.isArray(delimiter) && delimiter.length === 2) { return /** @type {[string, string]} */ (delimiter); } if (format === 'json-frontmatter') { return ['{', '}']; } if (format === 'toml-frontmatter') { return ['+++', '+++']; } if (format === 'yaml-frontmatter') { return ['---', '---']; } return undefined; };
Detect the front matter format’s delimiters from the given entry file configuration. @param {object} args Arguments. @param {FileFormat} args.format File format. @param {string | string[]} [args.delimiter] Configured delimiter. @returns {[string, string] | undefined} Start and end delimiters. If `undefined`, the parser automatically detects the delimiters, while the formatter uses the YAML delimiters. @see https://decapcms.org/docs/configuration-options/#frontmatter_delimiter
getFrontMatterDelimiters
javascript
sveltia/sveltia-cms
src/lib/services/contents/file/index.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/file/index.js
MIT
export const getDefaultValue = (fieldConfig) => { const { prefix, use_b32_encoding: useEncoding } = fieldConfig; const value = useEncoding ? generateRandomId() : generateUUID(); return prefix ? `${prefix}${value}` : value; };
Get the default value for a UUID field. @param {UuidField} fieldConfig Field configuration. @returns {string} Default value. @todo Write tests for this.
getDefaultValue
javascript
sveltia/sveltia-cms
src/lib/services/contents/widgets/uuid/helper.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/widgets/uuid/helper.js
MIT
export const getBooleanFieldDefaultValueMap = ({ fieldConfig, keyPath }) => { const { default: defaultValue } = fieldConfig; return { [keyPath]: typeof defaultValue === 'boolean' ? defaultValue : false }; };
Get the default value map for a Boolean field. @param {object} args Arguments. @param {BooleanField} args.fieldConfig Field configuration. @param {FieldKeyPath} args.keyPath Field key path. @returns {Record<string, boolean>} Default value map.
getBooleanFieldDefaultValueMap
javascript
sveltia/sveltia-cms
src/lib/services/contents/widgets/boolean/helper.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/widgets/boolean/helper.js
MIT
export const validateStringField = (fieldConfig, value) => { const { minlength, maxlength } = fieldConfig; const hasMin = Number.isInteger(minlength) && /** @type {number} */ (minlength) <= (maxlength ?? Infinity); const hasMax = Number.isInteger(maxlength) && (minlength ?? 0) <= /** @type {number} */ (maxlength); const count = value ? [...value.trim()].length : 0; const tooShort = hasMin && count < /** @type {number} */ (minlength); const tooLong = hasMax && count > /** @type {number} */ (maxlength); const invalid = tooShort || tooLong; return { count, hasMin, hasMax, tooShort, tooLong, invalid }; };
Validate a String/Text field value against the field configuration. @param {StringField | TextField} fieldConfig Field configuration. @param {string | undefined} value Current value. @returns {{ count: number, hasMin: boolean, hasMax: boolean, tooShort: boolean, tooLong: boolean, invalid: boolean }} Result.
validateStringField
javascript
sveltia/sveltia-cms
src/lib/services/contents/widgets/string/helper.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/widgets/string/helper.js
MIT
export const getSelectFieldDefaultValueMap = ({ fieldConfig, keyPath }) => { const { default: defaultValue, multiple = false } = fieldConfig; const isArray = Array.isArray(defaultValue) && !!defaultValue.length; /** @type {Record<string, any>} */ const content = {}; if (!multiple) { content[keyPath] = defaultValue !== undefined ? defaultValue : ''; } else if (isArray) { defaultValue.forEach((value, index) => { content[[keyPath, index].join('.')] = value; }); } else { content[keyPath] = []; } return content; };
Get the default value map for a Relation/Select field. @param {object} args Arguments. @param {RelationField | SelectField} args.fieldConfig Field configuration. @param {FieldKeyPath} args.keyPath Field key path. @returns {Record<string, any>} Default value map.
getSelectFieldDefaultValueMap
javascript
sveltia/sveltia-cms
src/lib/services/contents/widgets/select/helper.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/widgets/select/helper.js
MIT
const getLabel = (_value) => /** @type {{ label: string, value: string }[]} */ (options).find((o) => o.value === _value) ?.label || _value; if (multiple) { const values = Object.entries(valueMap) .filter(([key]) => key.match(`^${escapeRegExp(keyPath)}\\.\\d+$`)) .map(([, _value]) => _value); const labels = hasLabels ? values.map(getLabel) : values; labelCacheMap.set(cacheKey, labels); return labels; } const value = valueMap[keyPath]; const label = hasLabels ? getLabel(value) : value; labelCacheMap.set(cacheKey, label); return label; };
Get the label by value. @param {any} _value Stored value. @returns {string} Label.
getLabel
javascript
sveltia/sveltia-cms
src/lib/services/contents/widgets/select/helper.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/widgets/select/helper.js
MIT
const normalizeFieldName = (fieldName) => { if (/{{.+?}}/.test(fieldName)) { return fieldName; } if (fieldName === 'slug') { // Avoid confusion with `{{slug}}`, which is the entry slug, not the `slug` field return '{{fields.slug}}'; } return `{{${fieldName}}}`; };
Enclose the given field name in brackets if it doesn’t contain any brackets. @param {string} fieldName Field name e.g. `{{name.first}}` or `name.first`. @returns {string} Bracketed field name, e.g. `{{name.first}}`.
normalizeFieldName
javascript
sveltia/sveltia-cms
src/lib/services/contents/widgets/relation/helper.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/widgets/relation/helper.js
MIT
export const getReferencedOptionLabel = ({ fieldConfig, valueMap, keyPath, locale }) => { const { multiple, collection } = fieldConfig; const refEntries = getEntriesByCollection(collection); const refOptions = getOptions(locale, fieldConfig, refEntries); /** * Get the label by value. * @param {any} _value Stored value. * @returns {string} Label. */ const getLabel = (_value) => refOptions.find((o) => o.value === _value)?.label || _value; if (multiple) { const values = Object.entries(valueMap) .filter(([key]) => key.match(`^${escapeRegExp(keyPath)}\\.\\d+$`)) .map(([, _value]) => _value); return values.map(getLabel); } return getLabel(valueMap[keyPath]); };
Resolve the display value(s) for a relation field. @param {object} args Arguments. @param {RelationField} args.fieldConfig Field configuration. @param {FlattenedEntryContent} args.valueMap Object holding current entry values. @param {FieldKeyPath} args.keyPath Field key path, e.g. `author.name`. @param {InternalLocaleCode} args.locale Locale. @returns {any | any[]} Resolved field value(s). @todo Write tests for this.
getReferencedOptionLabel
javascript
sveltia/sveltia-cms
src/lib/services/contents/widgets/relation/helper.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/widgets/relation/helper.js
MIT
const getDefaultValue = (fieldConfig, locale) => { const { default: defaultValue } = fieldConfig; if (typeof defaultValue !== 'string') { return defaultValue; } return defaultValue.replaceAll(/{{(.+?)}}/g, (_match, tag) => { if (tag === 'locale') { return locale; } if (tag === 'datetime') { return new Date().toJSON().replace(/\d+\.\d+Z$/, '00.000Z'); } if (tag === 'uuid') { return generateUUID(); } if (tag === 'uuid_short') { return generateUUID('short'); } if (tag === 'uuid_shorter') { return generateUUID('shorter'); } return ''; }); };
Get the default value for a Hidden field. @param {HiddenField} fieldConfig Field configuration. @param {InternalLocaleCode} locale Locale code. @returns {any} Default value. @todo Write tests for this.
getDefaultValue
javascript
sveltia/sveltia-cms
src/lib/services/contents/widgets/hidden/helper.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/widgets/hidden/helper.js
MIT
const getDefaultValue = (fieldConfig) => { const { default: defaultValue, required = true } = fieldConfig; if (defaultValue && isObject(defaultValue)) { return defaultValue; } if (required) { return { '': '' }; } return {}; };
Get the default value for a KeyValue field. @param {KeyValueField} fieldConfig Field configuration. @returns {Record<string, string>} Default value.
getDefaultValue
javascript
sveltia/sveltia-cms
src/lib/services/contents/widgets/key-value/helper.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/widgets/key-value/helper.js
MIT
export const getKeyValueFieldDefaultValueMap = ({ fieldConfig, keyPath }) => { /** @type {Record<string, string>} */ const content = {}; Object.entries(getDefaultValue(fieldConfig)).forEach(([key, val]) => { content[`${keyPath}.${key}`] = String(val); }); return content; };
Get the default value map for a KeyValue field. @param {object} args Arguments. @param {KeyValueField} args.fieldConfig Field configuration. @param {FieldKeyPath} args.keyPath Field key path. @returns {Record<string, string>} Default value map.
getKeyValueFieldDefaultValueMap
javascript
sveltia/sveltia-cms
src/lib/services/contents/widgets/key-value/helper.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/widgets/key-value/helper.js
MIT
export const savePairs = ({ entryDraft, keyPath, locale, fieldConfig, pairs }) => { const { i18n } = fieldConfig; i18nAutoDupEnabled.set(false); entryDraft.update((draft) => { if (draft) { Object.entries(draft.currentValues).forEach(([_locale, content]) => { if (_locale === locale || i18n === 'duplicate') { // Clear pairs first Object.entries(content).forEach(([_keyPath]) => { if (_keyPath.startsWith(`${keyPath}.`)) { delete content[_keyPath]; } }); pairs.forEach(([key, value]) => { content[`${keyPath}.${key}`] = value; }); } }); } return draft; }); i18nAutoDupEnabled.set(true); };
Save the key-value pairs to the draft store. @param {object} args Arguments. @param {Writable<EntryDraft>} args.entryDraft Draft store. @param {KeyValueField} args.fieldConfig Field configuration. @param {FieldKeyPath} args.keyPath Field key path. @param {InternalLocaleCode} args.locale Current pane’s locale. @param {[string, string][]} args.pairs Key-value pairs.
savePairs
javascript
sveltia/sveltia-cms
src/lib/services/contents/widgets/key-value/helper.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/widgets/key-value/helper.js
MIT
export const getListFieldDefaultValueMap = ({ fieldConfig, keyPath }) => { const { default: defaultValue, fields, types } = fieldConfig; const isArray = Array.isArray(defaultValue) && !!defaultValue.length; /** @type {Record<string, any>} */ const content = {}; if (!isArray) { content[keyPath] = []; } else if (fields || types) { defaultValue.forEach((items, index) => { Object.entries(items).forEach(([key, val]) => { content[[keyPath, index, key].join('.')] = val; }); }); } else { defaultValue.forEach((val, index) => { content[[keyPath, index].join('.')] = val; }); } return content; };
Get the default value map for a List field. @param {object} args Arguments. @param {ListField} args.fieldConfig Field configuration. @param {FieldKeyPath} args.keyPath Field key path. @returns {Record<string, any>} Default value map.
getListFieldDefaultValueMap
javascript
sveltia/sveltia-cms
src/lib/services/contents/widgets/list/helper.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/widgets/list/helper.js
MIT
export const getCodeFieldDefaultValueMap = ({ fieldConfig, keyPath }) => { /** @type {Record<string, any>} */ const content = {}; const { default: defaultValue, output_code_only: outputCodeOnly = false, keys: outputKeys = { code: 'code', lang: 'lang' }, } = /** @type {CodeField} */ (fieldConfig); if (outputCodeOnly) { content[keyPath] = typeof defaultValue === 'string' ? defaultValue : ''; } else { const obj = isObject(defaultValue) ? /** @type {Record<string, any>} */ (defaultValue) : undefined; const code = obj ? obj[outputKeys.code] : /** @type {string | undefined} */ (defaultValue); const lang = obj ? obj[outputKeys.lang] : ''; content[keyPath] = {}; content[`${keyPath}.${outputKeys.code}`] = typeof code === 'string' ? code : ''; content[`${keyPath}.${outputKeys.lang}`] = typeof lang === 'string' ? lang : ''; } return content; };
Get the default value map for a Code field. @param {object} args Arguments. @param {CodeField} args.fieldConfig Field configuration. @param {FieldKeyPath} args.keyPath Field key path. @returns {Record<string, any>} Default value map. @todo Write tests for this.
getCodeFieldDefaultValueMap
javascript
sveltia/sveltia-cms
src/lib/services/contents/widgets/code/helper.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/widgets/code/helper.js
MIT
export const getCurrentDateTime = (fieldConfig) => { const { dateOnly, timeOnly, utc } = parseDateTimeConfig(fieldConfig); const { year, month, day, hour, minute } = getDateTimeParts({ timeZone: utc ? 'UTC' : undefined, }); const dateStr = `${year}-${month}-${day}`; const timeStr = `${hour}:${minute}`; if (dateOnly) { return dateStr; } if (timeOnly) { return timeStr; } if (utc) { return `${dateStr}T${timeStr}:00.000Z`; } return `${dateStr}T${timeStr}`; };
Get the current date/time. @param {DateTimeField} fieldConfig Field configuration. @returns {string} Current date/time in the ISO 8601 format.
getCurrentDateTime
javascript
sveltia/sveltia-cms
src/lib/services/contents/widgets/date-time/helper.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/widgets/date-time/helper.js
MIT
const getDefaultValue = (fieldConfig) => { const { default: defaultValue } = fieldConfig; if (typeof defaultValue !== 'string') { return ''; } // Decap CMS 3.3.0 changed the default value from the current date/time to blank, requiring // `{{now}}` to use the current date/time. // @see https://github.com/decaporg/decap-cms/releases/tag/decap-cms%403.3.0 // @see https://github.com/decaporg/decap-website/commit/01e54d8392e368e5d7b9fec307f50af584b12c91 if (defaultValue === '{{now}}') { return /** @type {string} */ ( getCurrentValue(getCurrentDateTime(fieldConfig), '', fieldConfig) ); } return defaultValue; };
Get the default value for a DateTime field. @param {DateTimeField} fieldConfig Field configuration. @returns {string} Default value. @todo Write tests for this.
getDefaultValue
javascript
sveltia/sveltia-cms
src/lib/services/contents/widgets/date-time/helper.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/widgets/date-time/helper.js
MIT
export const getInputValue = (currentValue, fieldConfig) => { const { dateOnly, timeOnly, utc } = parseDateTimeConfig(fieldConfig); // If the default value is an empty string, the input will be blank by default if (!currentValue) { return ''; } // If the current value is the standard format, return it as is const value = dateOnly ? currentValue?.match(/^(?<date>\d{4}-[01]\d-[0-3]\d)\b/)?.groups?.date : timeOnly ? currentValue?.match(/^(?<time>[0-2]\d:[0-5]\d)\b/)?.groups?.time : undefined; if (value) { return value; } try { const { year, month, day, hour, minute } = getDateTimeParts({ date: currentValue ? getDate(currentValue, fieldConfig) : new Date(), timeZone: utc ? 'UTC' : undefined, }); const dateStr = `${year}-${month}-${day}`; const timeStr = `${hour}:${minute}`; if (dateOnly) { return dateStr; } if (timeOnly) { return timeStr; } return `${dateStr}T${timeStr}`; } catch (/** @type {any} */ ex) { // eslint-disable-next-line no-console console.error(ex); return ''; } };
Get the input value given the current value. @param {string | undefined} currentValue Value in the entry draft datastore. @param {DateTimeField} fieldConfig Field configuration. @returns {string | undefined} New value. @todo Write tests for this.
getInputValue
javascript
sveltia/sveltia-cms
src/lib/services/contents/widgets/date-time/helper.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/contents/widgets/date-time/helper.js
MIT
export const applyTransformations = ({ fieldConfig, value, transformations }) => { transformations.forEach((transformation) => { value = applyTransformation({ fieldConfig, value, transformation }); }); return value; };
Apply string transformations to the value. @param {object} args Arguments. @param {Field} [args.fieldConfig] Field configuration. @param {any} args.value Original value. @param {string[]} args.transformations List of transformations. @returns {string} Transformed value.
applyTransformations
javascript
sveltia/sveltia-cms
src/lib/services/common/transformations.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/common/transformations.js
MIT
setValue: function setValue( val, suppressEllipsis ) { //if suppressEllipsis is undefined, check placards init settings if ( typeof suppressEllipsis === 'undefined' ) { suppressEllipsis = !this.options.applyEllipsis; } if ( this.isContentEditableDiv ) { this.$field.empty().append( val ); } else { this.$field.val( val ); } if ( !suppressEllipsis && !_isShown( this ) ) { this.applyEllipsis(); } return this.$field; },
setValue() sets the Placard triggering DOM element's display value @param {String} the value to be displayed @param {Boolean} If you want to explicitly suppress the application of ellipsis, pass `true`. This would typically only be done from internal functions (like `applyEllipsis`) that want to avoid circular logic. Otherwise, the value of the option applyEllipsis will be used. @return {Object} jQuery object representing the DOM element whose value was set
setValue ( val , suppressEllipsis )
javascript
ExactTarget/fuelux
dist/js/fuelux.js
https://github.com/ExactTarget/fuelux/blob/master/dist/js/fuelux.js
BSD-3-Clause
on() { activeEffectScope = this; }
This should only be called on non-detached scopes @internal
on ( )
javascript
jeremykenedy/laravel-auth
public/build/assets/app-e94a5d71.js
https://github.com/jeremykenedy/laravel-auth/blob/master/public/build/assets/app-e94a5d71.js
MIT
function here(callback) { this.on("presence:subscribed", function(members) { callback(members.map(function(m) { return m.user_info; }));
Register a callback to be called anytime the member list changes.
(anonymous) ( members )
javascript
jeremykenedy/laravel-auth
public/build/assets/app-e94a5d71.js
https://github.com/jeremykenedy/laravel-auth/blob/master/public/build/assets/app-e94a5d71.js
MIT
function Socket(type, reuseAddr) { if (reuseAddr === void 0) { reuseAddr = false; } var _this = _super.call(this) || this; _this._chromeSocketId = null; _this._firefoxSocket = null; _this._addressInfo = null; if (browserUDP === UDPBrowserTypes.ChromeSocketsUDP) { _this._onReceiveChrome = _this._onReceiveChrome.bind(_this); _this._onReceiveErrorChrome = _this._onReceiveErrorChrome.bind(_this); chrome.sockets.udp.onReceive.addListener(_this._onReceiveChrome); chrome.sockets.udp.onReceiveError.addListener(_this._onReceiveErrorChrome); chrome.sockets.udp.create({}, function (createInfo) { _this._chromeSocketId = createInfo.socketId; }); } return _this; }
Note that in Node's `dgram`, you're not supposed to ever do `new dgram.Socket()` (presumably for legacy compatibility reasons). Here we have no problem including a constructor.
Socket ( type , reuseAddr )
javascript
fuse-box/fuse-box
modules/dgram/Socket.js
https://github.com/fuse-box/fuse-box/blob/master/modules/dgram/Socket.js
MIT
Socket.prototype.close = function (callback) { var _this = this; if (browserUDP === UDPBrowserTypes.ChromeSocketsUDP) { if (!this._chromeSocketId) { throw new Error('Socket not created'); } chrome.sockets.udp.close(this._chromeSocketId, function () { if (callback) { _this.addListener('close', callback); } _this.emit('close'); }); return; } throw new NotInThisBrowserError(); };
Close the underlying socket and stop listening for data on it. If a callback is provided, it is added as a listener for the 'close' event.
Socket.prototype.close ( callback )
javascript
fuse-box/fuse-box
modules/dgram/Socket.js
https://github.com/fuse-box/fuse-box/blob/master/modules/dgram/Socket.js
MIT
Socket.prototype.address = function () { if (!this._addressInfo) { throw new Error('No address info is available'); } return this._addressInfo; };
Returns an object containing the address information for a socket. For UDP sockets, this object will contain address, family and port properties.
Socket.prototype.address ( )
javascript
fuse-box/fuse-box
modules/dgram/Socket.js
https://github.com/fuse-box/fuse-box/blob/master/modules/dgram/Socket.js
MIT
Socket.prototype.setBroadcast = function (flag) { if (!flag) { throw new Error('setBroadcast requires an argument'); } if (browserUDP === UDPBrowserTypes.ChromeSocketsUDP) { if (!this._chromeSocketId) throw new Error('Socket not created'); chrome.sockets.udp.setBroadcast(this._chromeSocketId, flag); return; } throw new NotInThisBrowserError(); };
When set to true, UDP packets may be sent to a local interface's broadcast address. @since Chrome 44
Socket.prototype.setBroadcast ( flag )
javascript
fuse-box/fuse-box
modules/dgram/Socket.js
https://github.com/fuse-box/fuse-box/blob/master/modules/dgram/Socket.js
MIT
Socket.prototype.setTTL = function (ttl) { if (!ttl) { throw new Error('setTTL requires an argument'); } if (ttl < 1 || ttl > 255) { throw new Error('ttl for setTTL should be between 1 and 255.'); } if (browserUDP === UDPBrowserTypes.ChromeSocketsUDP) { if (!this._chromeSocketId) throw new Error('Socket not created'); throw new Error('Method not implemented in Chrome.'); } throw new NotInThisBrowserError(); };
Sets the IP_TTL socket option. While TTL generally stands for "Time to Live", in this context it specifies the number of IP hops that a packet is allowed to travel through. Each router or gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. Changing TTL values is typically done for network probes or when multicasting. @param ttl A number of hops between 1 and 255. The default on most systems is 64 but can vary.
Socket.prototype.setTTL ( ttl )
javascript
fuse-box/fuse-box
modules/dgram/Socket.js
https://github.com/fuse-box/fuse-box/blob/master/modules/dgram/Socket.js
MIT
Socket.prototype.setMulticastTTL = function (ttl) { var _this = this; if (!ttl) { throw new Error('setMulticastTTL requires an argument'); } if (!ttl || ttl < 1 || ttl > 255) { throw new Error('ttl for setTTL should be between 1 and 255.'); } if (browserUDP === UDPBrowserTypes.ChromeSocketsUDP) { if (!this._chromeSocketId) throw new Error('Socket not created'); chrome.sockets.udp.setMulticastTimeToLive(this._chromeSocketId, ttl, function (result) { if (result < 0) { _this.emit('error', new Error('Bad network result code:' + result)); } }); return; } throw new NotInThisBrowserError(); };
Sets the IP_MULTICAST_TTL socket option. While TTL generally stands for "Time to Live", in this context it specifies the number of IP hops that a packet is allowed to travel through, specifically for multicast traffic. Each router or gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. The argument passed to to socket.setMulticastTTL() is a number of hops between 0 and 255. The default on most systems is 1 but can vary.
Socket.prototype.setMulticastTTL ( ttl )
javascript
fuse-box/fuse-box
modules/dgram/Socket.js
https://github.com/fuse-box/fuse-box/blob/master/modules/dgram/Socket.js
MIT
chrome.sockets.udp.setMulticastLoopbackMode(this._chromeSocketId, flag, function () { });
Note: the behavior of setMulticastLoopbackMode is slightly different between Windows and Unix-like systems. The inconsistency happens only when there is more than one application on the same host joined to the same multicast group while having different settings on multicast loopback mode. On Windows, the applications with loopback off will not RECEIVE the loopback packets; while on Unix-like systems, the applications with loopback off will not SEND the loopback packets to other applications on the same host. See MSDN: http://goo.gl/6vqbj
(anonymous) ( )
javascript
fuse-box/fuse-box
modules/dgram/Socket.js
https://github.com/fuse-box/fuse-box/blob/master/modules/dgram/Socket.js
MIT
Socket.prototype.setMulticastLoopback = function (flag) { if (!flag) { throw new Error('setMulticastLoopback requires an argument'); } if (browserUDP === UDPBrowserTypes.ChromeSocketsUDP) { if (!this._chromeSocketId) throw new Error('Socket not created'); /** * Note: the behavior of setMulticastLoopbackMode is slightly different * between Windows and Unix-like systems. The inconsistency happens only * when there is more than one application on the same host joined to the * same multicast group while having different settings on multicast * loopback mode. On Windows, the applications with loopback off will not * RECEIVE the loopback packets; while on Unix-like systems, the * applications with loopback off will not SEND the loopback packets to * other applications on the same host. See MSDN: http://goo.gl/6vqbj */ chrome.sockets.udp.setMulticastLoopbackMode(this._chromeSocketId, flag, function () { }); return; } throw new NotInThisBrowserError(); };
Sets or clears the IP_MULTICAST_LOOP socket option. When set to true, multicast packets will also be received on the local interface.
Socket.prototype.setMulticastLoopback ( flag )
javascript
fuse-box/fuse-box
modules/dgram/Socket.js
https://github.com/fuse-box/fuse-box/blob/master/modules/dgram/Socket.js
MIT
Socket.prototype.addMembership = function (multicastAddress, multicastInterface) { var _this = this; if (!multicastAddress) { throw new Error('An address must be provided'); } if (browserUDP === UDPBrowserTypes.ChromeSocketsUDP) { if (!this._chromeSocketId) throw new Error('Socket not created'); chrome.sockets.udp.joinGroup(this._chromeSocketId, multicastAddress, function (result) { if (result < 0) { _this.emit('error', new Error('Bad network result code:' + result)); } }); return; } throw new NotInThisBrowserError(); };
Join a multicast group. @param multicastInterface Included for interface compatibility, but does nothing.
Socket.prototype.addMembership ( multicastAddress , multicastInterface )
javascript
fuse-box/fuse-box
modules/dgram/Socket.js
https://github.com/fuse-box/fuse-box/blob/master/modules/dgram/Socket.js
MIT
Socket.prototype.dropMembership = function (multicastAddress, multicastInterface) { var _this = this; if (!multicastAddress) { throw new Error('An address must be provided'); } if (browserUDP === UDPBrowserTypes.FirefoxUDP) { throw new Error('Method not implemented in Firefox.'); } if (browserUDP === UDPBrowserTypes.ChromeSocketsUDP) { if (!this._chromeSocketId) throw new Error('Socket not created'); chrome.sockets.udp.leaveGroup(this._chromeSocketId, multicastAddress, function (result) { if (result < 0) { _this.emit('error', new Error('Bad network result code:' + result)); } }); return; } throw new NotInThisBrowserError(); };
Leave a multicast group. This happens automatically when the socket is closed, so it's only needed when reusing sockets. @param multicastInterface Included for interface compatibility, but does nothing.
Socket.prototype.dropMembership ( multicastAddress , multicastInterface )
javascript
fuse-box/fuse-box
modules/dgram/Socket.js
https://github.com/fuse-box/fuse-box/blob/master/modules/dgram/Socket.js
MIT
export function toAscii(string) { if (string === null) { return ''; } var outStr = ''; for (var i = 0; i < string.length; i++) { var letter = string.charAt(i); var upper = false; if (letter === letter.toUpperCase() && letter !== letter.toLowerCase()) upper = true; i = i || 0; var code = string.toLowerCase().charCodeAt(i); var hi, low; if (0xd800 <= code && code <= 0xdbff) { hi = code; low = string.toLowerCase().charCodeAt(i + 1); if (isNaN(low)) { throw 'High surrogate not followed by low surrogate in fixedCharCodeAt()'; } return (hi - 0xd800) * 0x400 + (low - 0xdc00) + 0x10000; } if (0xdc00 <= code && code <= 0xdfff) { /* * Low surrogate: We return false to allow loops to skip this * iteration since should have already handled high surrogate above * in the previous iteration */ return false; } var charCode = code; if (charCode) { if (charCode < 128) { // character is latin -> keep it outStr += upper ? String.fromCharCode(charCode).toUpperCase() : String.fromCharCode(charCode); } else { var replacement; // change character switch (charCode) { case 0x101: // ā [LATIN SMALL LETTER A WITH MACRON] case 0x103: // ă [LATIN SMALL LETTER A WITH BREVE] case 0x105: // ą [LATIN SMALL LETTER A WITH OGONEK] case 0x1ce: // ǎ [LATIN SMALL LETTER A WITH CARON] case 0x1d8f: // ᶏ [LATIN SMALL LETTER A WITH RETROFLEX HOOK] case 0x1d95: // ᶕ [LATIN SMALL LETTER SCHWA WITH RETROFLEX HOOK] case 0x1df: // ǟ [LATIN SMALL LETTER A WITH DIAERESIS AND MACRON] case 0x1e01: // ạ [LATIN SMALL LETTER A WITH RING BELOW] case 0x1e1: // ǡ [LATIN SMALL LETTER A WITH DOT ABOVE AND MACRON] case 0x1e9a: // ả [LATIN SMALL LETTER A WITH RIGHT HALF RING] case 0x1ea1: // ạ [LATIN SMALL LETTER A WITH DOT BELOW] case 0x1ea3: // ả [LATIN SMALL LETTER A WITH HOOK ABOVE] case 0x1ea5: // ấ [LATIN SMALL LETTER A WITH CIRCUMFLEX AND ACUTE] case 0x1ea7: // ầ [LATIN SMALL LETTER A WITH CIRCUMFLEX AND GRAVE] case 0x1ea9: // ẩ [LATIN SMALL LETTER A WITH CIRCUMFLEX AND HOOK ABOVE] case 0x1eab: // ẫ [LATIN SMALL LETTER A WITH CIRCUMFLEX AND TILDE] case 0x1ead: // ậ [LATIN SMALL LETTER A WITH CIRCUMFLEX AND DOT BELOW] case 0x1eaf: // ắ [LATIN SMALL LETTER A WITH BREVE AND ACUTE] case 0x1eb1: // ằ [LATIN SMALL LETTER A WITH BREVE AND GRAVE] case 0x1eb3: // ẳ [LATIN SMALL LETTER A WITH BREVE AND HOOK ABOVE] case 0x1eb5: // ẵ [LATIN SMALL LETTER A WITH BREVE AND TILDE] case 0x1eb7: // ặ [LATIN SMALL LETTER A WITH BREVE AND DOT BELOW] case 0x1fb: // ǻ [LATIN SMALL LETTER A WITH RING ABOVE AND ACUTE] case 0x201: // ȁ [LATIN SMALL LETTER A WITH DOUBLE GRAVE] case 0x203: // ȃ [LATIN SMALL LETTER A WITH INVERTED BREVE] case 0x2090: // ₐ [LATIN SUBSCRIPT SMALL LETTER A] case 0x2094: // ₔ [LATIN SUBSCRIPT SMALL LETTER SCHWA] case 0x227: // ȧ [LATIN SMALL LETTER A WITH DOT ABOVE] case 0x24d0: // ⓐ [CIRCLED LATIN SMALL LETTER A] case 0x250: // ɐ [LATIN SMALL LETTER TURNED A] case 0x259: // ə [LATIN SMALL LETTER SCHWA] case 0x25a: // ɚ [LATIN SMALL LETTER SCHWA WITH HOOK] case 0x2c65: // ⱥ [LATIN SMALL LETTER A WITH STROKE] case 0x2c6f: // Ɐ [LATIN CAPITAL LETTER TURNED A] case 0xe0: // à [LATIN SMALL LETTER A WITH GRAVE] case 0xe1: // á [LATIN SMALL LETTER A WITH ACUTE] case 0xe2: // â [LATIN SMALL LETTER A WITH CIRCUMFLEX] case 0xe3: // ã [LATIN SMALL LETTER A WITH TILDE] case 0xe4: // ä [LATIN SMALL LETTER A WITH DIAERESIS] case 0xe5: // å [LATIN SMALL LETTER A WITH RING ABOVE] case 0xff41: // a [FULLWIDTH LATIN SMALL LETTER A] replacement = 'a'; break; case 0x107: // ć [LATIN SMALL LETTER C WITH ACUTE] case 0x109: // ĉ [LATIN SMALL LETTER C WITH CIRCUMFLEX] case 0x10b: // ċ [LATIN SMALL LETTER C WITH DOT ABOVE] case 0x10d: // č [LATIN SMALL LETTER C WITH CARON] case 0x188: // ƈ [LATIN SMALL LETTER C WITH HOOK] case 0x1e09: // ḉ [LATIN SMALL LETTER C WITH CEDILLA AND ACUTE] case 0x2184: // ↄ [LATIN SMALL LETTER REVERSED C] case 0x23c: // ȼ [LATIN SMALL LETTER C WITH STROKE] case 0x24d2: // ⓒ [CIRCLED LATIN SMALL LETTER C] case 0x255: // ɕ [LATIN SMALL LETTER C WITH CURL] case 0xa73e: // Ꜿ [LATIN CAPITAL LETTER REVERSED C WITH DOT] case 0xa73f: // ꜿ [LATIN SMALL LETTER REVERSED C WITH DOT] case 0xe7: // ç [LATIN SMALL LETTER C WITH CEDILLA] case 0xff43: // c [FULLWIDTH LATIN SMALL LETTER C] replacement = 'c'; break; case 0x10f: // ď [LATIN SMALL LETTER D WITH CARON] case 0x111: // đ [LATIN SMALL LETTER D WITH STROKE] case 0x18c: // ƌ [LATIN SMALL LETTER D WITH TOPBAR] case 0x1d6d: // ᵭ [LATIN SMALL LETTER D WITH MIDDLE TILDE] case 0x1d81: // ᶁ [LATIN SMALL LETTER D WITH PALATAL HOOK] case 0x1d91: // ᶑ [LATIN SMALL LETTER D WITH HOOK AND TAIL] case 0x1e0b: // ḋ [LATIN SMALL LETTER D WITH DOT ABOVE] case 0x1e0d: // ḍ [LATIN SMALL LETTER D WITH DOT BELOW] case 0x1e0f: // ḏ [LATIN SMALL LETTER D WITH LINE BELOW] case 0x1e11: // ḑ [LATIN SMALL LETTER D WITH CEDILLA] case 0x1e13: // ḓ [LATIN SMALL LETTER D WITH CIRCUMFLEX BELOW] case 0x221: // ȡ [LATIN SMALL LETTER D WITH CURL] case 0x24d3: // ⓓ [CIRCLED LATIN SMALL LETTER D] case 0x256: // ɖ [LATIN SMALL LETTER D WITH TAIL] case 0x257: // ɗ [LATIN SMALL LETTER D WITH HOOK] case 0xa77a: // ꝺ [LATIN SMALL LETTER INSULAR D] case 0xf0: // ð [LATIN SMALL LETTER ETH] case 0xff44: // d [FULLWIDTH LATIN SMALL LETTER D] replacement = 'd'; break; case 0x113: // ē [LATIN SMALL LETTER E WITH MACRON] case 0x115: // ĕ [LATIN SMALL LETTER E WITH BREVE] case 0x117: // ė [LATIN SMALL LETTER E WITH DOT ABOVE] case 0x119: // ę [LATIN SMALL LETTER E WITH OGONEK] case 0x11b: // ě [LATIN SMALL LETTER E WITH CARON] case 0x1d08: // ᴈ [LATIN SMALL LETTER TURNED OPEN E] case 0x1d92: // ᶒ [LATIN SMALL LETTER E WITH RETROFLEX HOOK] case 0x1d93: // ᶓ [LATIN SMALL LETTER OPEN E WITH RETROFLEX HOOK] case 0x1d94: // ᶔ [LATIN SMALL LETTER REVERSED OPEN E WITH RETROFLEX HOOK] case 0x1dd: // ǝ [LATIN SMALL LETTER TURNED E] case 0x1e15: // ḕ [LATIN SMALL LETTER E WITH MACRON AND GRAVE] case 0x1e17: // ḗ [LATIN SMALL LETTER E WITH MACRON AND ACUTE] case 0x1e19: // ḙ [LATIN SMALL LETTER E WITH CIRCUMFLEX BELOW] case 0x1e1b: // ḛ [LATIN SMALL LETTER E WITH TILDE BELOW] case 0x1e1d: // ḝ [LATIN SMALL LETTER E WITH CEDILLA AND BREVE] case 0x1eb9: // ẹ [LATIN SMALL LETTER E WITH DOT BELOW] case 0x1ebb: // ẻ [LATIN SMALL LETTER E WITH HOOK ABOVE] case 0x1ebd: // ẽ [LATIN SMALL LETTER E WITH TILDE] case 0x1ebf: // ế [LATIN SMALL LETTER E WITH CIRCUMFLEX AND ACUTE] case 0x1ec1: // ề [LATIN SMALL LETTER E WITH CIRCUMFLEX AND GRAVE] case 0x1ec3: // ể [LATIN SMALL LETTER E WITH CIRCUMFLEX AND HOOK ABOVE] case 0x1ec5: // ễ [LATIN SMALL LETTER E WITH CIRCUMFLEX AND TILDE] case 0x1ec7: // ệ [LATIN SMALL LETTER E WITH CIRCUMFLEX AND DOT BELOW] case 0x205: // ȅ [LATIN SMALL LETTER E WITH DOUBLE GRAVE] case 0x207: // ȇ [LATIN SMALL LETTER E WITH INVERTED BREVE] case 0x2091: // ₑ [LATIN SUBSCRIPT SMALL LETTER E] case 0x229: // ȩ [LATIN SMALL LETTER E WITH CEDILLA] case 0x247: // ɇ [LATIN SMALL LETTER E WITH STROKE] case 0x24d4: // ⓔ [CIRCLED LATIN SMALL LETTER E] case 0x258: // ɘ [LATIN SMALL LETTER REVERSED E] case 0x25b: // ɛ [LATIN SMALL LETTER OPEN E] case 0x25c: // ɜ [LATIN SMALL LETTER REVERSED OPEN E] case 0x25d: // ɝ [LATIN SMALL LETTER REVERSED OPEN E WITH HOOK] case 0x25e: // ɞ [LATIN SMALL LETTER CLOSED REVERSED OPEN E] case 0x29a: // ʚ [LATIN SMALL LETTER CLOSED OPEN E] case 0x2c78: // ⱸ [LATIN SMALL LETTER E WITH NOTCH] case 0xe8: // è [LATIN SMALL LETTER E WITH GRAVE] case 0xe9: // é [LATIN SMALL LETTER E WITH ACUTE] case 0xea: // ê [LATIN SMALL LETTER E WITH CIRCUMFLEX] case 0xeb: // ë [LATIN SMALL LETTER E WITH DIAERESIS] case 0xff45: // e [FULLWIDTH LATIN SMALL LETTER E] replacement = 'e'; break; case 0x11d: // ĝ [LATIN SMALL LETTER G WITH CIRCUMFLEX] case 0x11f: // ğ [LATIN SMALL LETTER G WITH BREVE] case 0x121: // ġ [LATIN SMALL LETTER G WITH DOT ABOVE] case 0x123: // ģ [LATIN SMALL LETTER G WITH CEDILLA] case 0x1d77: // ᵷ [LATIN SMALL LETTER TURNED G] case 0x1d79: // ᵹ [LATIN SMALL LETTER INSULAR G] case 0x1d83: // ᶃ [LATIN SMALL LETTER G WITH PALATAL HOOK] case 0x1e21: // ḡ [LATIN SMALL LETTER G WITH MACRON] case 0x1f5: // ǵ [LATIN SMALL LETTER G WITH ACUTE] case 0x24d6: // ⓖ [CIRCLED LATIN SMALL LETTER G] case 0x260: // ɠ [LATIN SMALL LETTER G WITH HOOK] case 0x261: // ɡ [LATIN SMALL LETTER SCRIPT G] case 0xa77f: // ꝿ [LATIN SMALL LETTER TURNED INSULAR G] case 0xff47: // g [FULLWIDTH LATIN SMALL LETTER G] replacement = 'g'; break; case 0x125: // ĥ [LATIN SMALL LETTER H WITH CIRCUMFLEX] case 0x127: // ħ [LATIN SMALL LETTER H WITH STROKE] case 0x1e23: // ḣ [LATIN SMALL LETTER H WITH DOT ABOVE] case 0x1e25: // ḥ [LATIN SMALL LETTER H WITH DOT BELOW] case 0x1e27: // ḧ [LATIN SMALL LETTER H WITH DIAERESIS] case 0x1e29: // ḩ [LATIN SMALL LETTER H WITH CEDILLA] case 0x1e2b: // ḫ [LATIN SMALL LETTER H WITH BREVE BELOW] case 0x1e96: // ẖ [LATIN SMALL LETTER H WITH LINE BELOW] case 0x21f: // ȟ [LATIN SMALL LETTER H WITH CARON] case 0x24d7: // ⓗ [CIRCLED LATIN SMALL LETTER H] case 0x265: // ɥ [LATIN SMALL LETTER TURNED H] case 0x266: // ɦ [LATIN SMALL LETTER H WITH HOOK] case 0x2ae: // ʮ [LATIN SMALL LETTER TURNED H WITH FISHHOOK] case 0x2af: // ʯ [LATIN SMALL LETTER TURNED H WITH FISHHOOK AND TAIL] case 0x2c68: // ⱨ [LATIN SMALL LETTER H WITH DESCENDER] case 0x2c76: // ⱶ [LATIN SMALL LETTER HALF H] case 0xff48: // h [FULLWIDTH LATIN SMALL LETTER H] replacement = 'h'; break; case 0x129: // ĩ [LATIN SMALL LETTER I WITH TILDE] case 0x12b: // ī [LATIN SMALL LETTER I WITH MACRON] case 0x12d: // ĭ [LATIN SMALL LETTER I WITH BREVE] case 0x12f: // į [LATIN SMALL LETTER I WITH OGONEK] case 0x131: // ı [LATIN SMALL LETTER DOTLESS I] case 0x1d0: // ǐ [LATIN SMALL LETTER I WITH CARON] case 0x1d09: // ᴉ [LATIN SMALL LETTER TURNED I] case 0x1d62: // ᵢ [LATIN SUBSCRIPT SMALL LETTER I] case 0x1d7c: // ᵼ [LATIN SMALL LETTER IOTA WITH STROKE] case 0x1d96: // ᶖ [LATIN SMALL LETTER I WITH RETROFLEX HOOK] case 0x1e2d: // ḭ [LATIN SMALL LETTER I WITH TILDE BELOW] case 0x1e2f: // ḯ [LATIN SMALL LETTER I WITH DIAERESIS AND ACUTE] case 0x1ec9: // ỉ [LATIN SMALL LETTER I WITH HOOK ABOVE] case 0x1ecb: // ị [LATIN SMALL LETTER I WITH DOT BELOW] case 0x2071: // ⁱ [SUPERSCRIPT LATIN SMALL LETTER I] case 0x209: // ȉ [LATIN SMALL LETTER I WITH DOUBLE GRAVE] case 0x20b: // ȋ [LATIN SMALL LETTER I WITH INVERTED BREVE] case 0x24d8: // ⓘ [CIRCLED LATIN SMALL LETTER I] case 0x268: // ɨ [LATIN SMALL LETTER I WITH STROKE] case 0xec: // ì [LATIN SMALL LETTER I WITH GRAVE] case 0xed: // í [LATIN SMALL LETTER I WITH ACUTE] case 0xee: // î [LATIN SMALL LETTER I WITH CIRCUMFLEX] case 0xef: // ï [LATIN SMALL LETTER I WITH DIAERESIS] case 0xff49: // i [FULLWIDTH LATIN SMALL LETTER I] replacement = 'i'; break; case 0x135: // ĵ [LATIN SMALL LETTER J WITH CIRCUMFLEX] case 0x1f0: // ǰ [LATIN SMALL LETTER J WITH CARON] case 0x237: // ȷ [LATIN SMALL LETTER DOTLESS J] case 0x249: // ɉ [LATIN SMALL LETTER J WITH STROKE] case 0x24d9: // ⓙ [CIRCLED LATIN SMALL LETTER J] case 0x25f: // ɟ [LATIN SMALL LETTER DOTLESS J WITH STROKE] case 0x284: // ʄ [LATIN SMALL LETTER DOTLESS J WITH STROKE AND HOOK] case 0x29d: // ʝ [LATIN SMALL LETTER J WITH CROSSED-TAIL] case 0x2c7c: // ⱼ [LATIN SUBSCRIPT SMALL LETTER J] case 0xff4a: // j [FULLWIDTH LATIN SMALL LETTER J] replacement = 'j'; break; case 0x137: // ķ [LATIN SMALL LETTER K WITH CEDILLA] case 0x199: // ƙ [LATIN SMALL LETTER K WITH HOOK] case 0x1d84: // ᶄ [LATIN SMALL LETTER K WITH PALATAL HOOK] case 0x1e31: // ḱ [LATIN SMALL LETTER K WITH ACUTE] case 0x1e33: // ḳ [LATIN SMALL LETTER K WITH DOT BELOW] case 0x1e35: // ḵ [LATIN SMALL LETTER K WITH LINE BELOW] case 0x1e9: // ǩ [LATIN SMALL LETTER K WITH CARON] case 0x24da: // ⓚ [CIRCLED LATIN SMALL LETTER K] case 0x29e: // ʞ [LATIN SMALL LETTER TURNED K] case 0x2c6a: // ⱪ [LATIN SMALL LETTER K WITH DESCENDER] case 0xa741: // ꝁ [LATIN SMALL LETTER K WITH STROKE] case 0xa743: // ꝃ [LATIN SMALL LETTER K WITH DIAGONAL STROKE] case 0xa745: // ꝅ [LATIN SMALL LETTER K WITH STROKE AND DIAGONAL STROKE] case 0xff4b: // k [FULLWIDTH LATIN SMALL LETTER K] replacement = 'k'; break; case 0x13a: // ĺ [LATIN SMALL LETTER L WITH ACUTE] case 0x13c: // ļ [LATIN SMALL LETTER L WITH CEDILLA] case 0x13e: // ľ [LATIN SMALL LETTER L WITH CARON] case 0x140: // ŀ [LATIN SMALL LETTER L WITH MIDDLE DOT] case 0x142: // ł [LATIN SMALL LETTER L WITH STROKE] case 0x19a: // ƚ [LATIN SMALL LETTER L WITH BAR] case 0x1d85: // ᶅ [LATIN SMALL LETTER L WITH PALATAL HOOK] case 0x1e37: // ḷ [LATIN SMALL LETTER L WITH DOT BELOW] case 0x1e39: // ḹ [LATIN SMALL LETTER L WITH DOT BELOW AND MACRON] case 0x1e3b: // ḻ [LATIN SMALL LETTER L WITH LINE BELOW] case 0x1e3d: // ḽ [LATIN SMALL LETTER L WITH CIRCUMFLEX BELOW] case 0x234: // ȴ [LATIN SMALL LETTER L WITH CURL] case 0x24db: // ⓛ [CIRCLED LATIN SMALL LETTER L] case 0x26b: // ɫ [LATIN SMALL LETTER L WITH MIDDLE TILDE] case 0x26c: // ɬ [LATIN SMALL LETTER L WITH BELT] case 0x26d: // ɭ [LATIN SMALL LETTER L WITH RETROFLEX HOOK] case 0x2c61: // ⱡ [LATIN SMALL LETTER L WITH DOUBLE BAR] case 0xa747: // ꝇ [LATIN SMALL LETTER BROKEN L] case 0xa749: // ꝉ [LATIN SMALL LETTER L WITH HIGH STROKE] case 0xa781: // ꞁ [LATIN SMALL LETTER TURNED L] case 0xff4c: // l [FULLWIDTH LATIN SMALL LETTER L] replacement = 'l'; break; case 0x144: // ń [LATIN SMALL LETTER N WITH ACUTE] case 0x146: // ņ [LATIN SMALL LETTER N WITH CEDILLA] case 0x148: // ň [LATIN SMALL LETTER N WITH CARON] case 0x149: // ʼn [LATIN SMALL LETTER N PRECEDED BY APOSTROPHE] case 0x14b: // ŋ http;//en.wikipedia.org/wiki/Eng_(letter) [LATIN SMALL LETTER ENG] case 0x19e: // ƞ [LATIN SMALL LETTER N WITH LONG RIGHT LEG] case 0x1d70: // ᵰ [LATIN SMALL LETTER N WITH MIDDLE TILDE] case 0x1d87: // ᶇ [LATIN SMALL LETTER N WITH PALATAL HOOK] case 0x1e45: // ṅ [LATIN SMALL LETTER N WITH DOT ABOVE] case 0x1e47: // ṇ [LATIN SMALL LETTER N WITH DOT BELOW] case 0x1e49: // ṉ [LATIN SMALL LETTER N WITH LINE BELOW] case 0x1e4b: // ṋ [LATIN SMALL LETTER N WITH CIRCUMFLEX BELOW] case 0x1f9: // ǹ [LATIN SMALL LETTER N WITH GRAVE] case 0x207f: // ⁿ [SUPERSCRIPT LATIN SMALL LETTER N] case 0x235: // ȵ [LATIN SMALL LETTER N WITH CURL] case 0x24dd: // ⓝ [CIRCLED LATIN SMALL LETTER N] case 0x272: // ɲ [LATIN SMALL LETTER N WITH LEFT HOOK] case 0x273: // ɳ [LATIN SMALL LETTER N WITH RETROFLEX HOOK] case 0xf1: // ñ [LATIN SMALL LETTER N WITH TILDE] case 0xff4e: // n [FULLWIDTH LATIN SMALL LETTER N] replacement = 'n'; break; case 0x14d: // ō [LATIN SMALL LETTER O WITH MACRON] case 0x14f: // ŏ [LATIN SMALL LETTER O WITH BREVE] case 0x151: // ő [LATIN SMALL LETTER O WITH DOUBLE ACUTE] case 0x1a1: // ơ [LATIN SMALL LETTER O WITH HORN] case 0x1d16: // ᴖ [LATIN SMALL LETTER TOP HALF O] case 0x1d17: // ᴗ [LATIN SMALL LETTER BOTTOM HALF O] case 0x1d2: // ǒ [LATIN SMALL LETTER O WITH CARON] case 0x1d97: // ᶗ [LATIN SMALL LETTER OPEN O WITH RETROFLEX HOOK] case 0x1e4d: // ṍ [LATIN SMALL LETTER O WITH TILDE AND ACUTE] case 0x1e4f: // ṏ [LATIN SMALL LETTER O WITH TILDE AND DIAERESIS] case 0x1e51: // ṑ [LATIN SMALL LETTER O WITH MACRON AND GRAVE] case 0x1e53: // ṓ [LATIN SMALL LETTER O WITH MACRON AND ACUTE] case 0x1eb: // ǫ [LATIN SMALL LETTER O WITH OGONEK] case 0x1ecd: // ọ [LATIN SMALL LETTER O WITH DOT BELOW] case 0x1ecf: // ỏ [LATIN SMALL LETTER O WITH HOOK ABOVE] case 0x1ed: // ǭ [LATIN SMALL LETTER O WITH OGONEK AND MACRON] case 0x1ed1: // ố [LATIN SMALL LETTER O WITH CIRCUMFLEX AND ACUTE] case 0x1ed3: // ồ [LATIN SMALL LETTER O WITH CIRCUMFLEX AND GRAVE] case 0x1ed5: // ổ [LATIN SMALL LETTER O WITH CIRCUMFLEX AND HOOK ABOVE] case 0x1ed7: // ỗ [LATIN SMALL LETTER O WITH CIRCUMFLEX AND TILDE] case 0x1ed9: // ộ [LATIN SMALL LETTER O WITH CIRCUMFLEX AND DOT BELOW] case 0x1edb: // ớ [LATIN SMALL LETTER O WITH HORN AND ACUTE] case 0x1edd: // ờ [LATIN SMALL LETTER O WITH HORN AND GRAVE] case 0x1edf: // ở [LATIN SMALL LETTER O WITH HORN AND HOOK ABOVE] case 0x1ee1: // ỡ [LATIN SMALL LETTER O WITH HORN AND TILDE] case 0x1ee3: // ợ [LATIN SMALL LETTER O WITH HORN AND DOT BELOW] case 0x1ff: // ǿ [LATIN SMALL LETTER O WITH STROKE AND ACUTE] case 0x2092: // ₒ [LATIN SUBSCRIPT SMALL LETTER O] case 0x20d: // ȍ [LATIN SMALL LETTER O WITH DOUBLE GRAVE] case 0x20f: // ȏ [LATIN SMALL LETTER O WITH INVERTED BREVE] case 0x22b: // ȫ [LATIN SMALL LETTER O WITH DIAERESIS AND MACRON] case 0x22d: // ȭ [LATIN SMALL LETTER O WITH TILDE AND MACRON] case 0x22f: // ȯ [LATIN SMALL LETTER O WITH DOT ABOVE] case 0x231: // ȱ [LATIN SMALL LETTER O WITH DOT ABOVE AND MACRON] case 0x24de: // ⓞ [CIRCLED LATIN SMALL LETTER O] case 0x254: // ɔ [LATIN SMALL LETTER OPEN O] case 0x275: // ɵ [LATIN SMALL LETTER BARRED O] case 0x2c7a: // ⱺ [LATIN SMALL LETTER O WITH LOW RING INSIDE] case 0xa74b: // ꝋ [LATIN SMALL LETTER O WITH LONG STROKE OVERLAY] case 0xa74d: // ꝍ [LATIN SMALL LETTER O WITH LOOP] case 0xf2: // ò [LATIN SMALL LETTER O WITH GRAVE] case 0xf3: // ó [LATIN SMALL LETTER O WITH ACUTE] case 0xf4: // ô [LATIN SMALL LETTER O WITH CIRCUMFLEX] case 0xf5: // õ [LATIN SMALL LETTER O WITH TILDE] case 0xf6: // ö [LATIN SMALL LETTER O WITH DIAERESIS] case 0xf8: // ø [LATIN SMALL LETTER O WITH STROKE] case 0xff4f: // o [FULLWIDTH LATIN SMALL LETTER O] replacement = 'o'; break; case 0x155: // ŕ [LATIN SMALL LETTER R WITH ACUTE] case 0x157: // ŗ [LATIN SMALL LETTER R WITH CEDILLA] case 0x159: // ř [LATIN SMALL LETTER R WITH CARON] case 0x1d63: // ᵣ [LATIN SUBSCRIPT SMALL LETTER R] case 0x1d72: // ᵲ [LATIN SMALL LETTER R WITH MIDDLE TILDE] case 0x1d73: // ᵳ [LATIN SMALL LETTER R WITH FISHHOOK AND MIDDLE TILDE] case 0x1d89: // ᶉ [LATIN SMALL LETTER R WITH PALATAL HOOK] case 0x1e59: // ṙ [LATIN SMALL LETTER R WITH DOT ABOVE] case 0x1e5b: // ṛ [LATIN SMALL LETTER R WITH DOT BELOW] case 0x1e5d: // ṝ [LATIN SMALL LETTER R WITH DOT BELOW AND MACRON] case 0x1e5f: // ṟ [LATIN SMALL LETTER R WITH LINE BELOW] case 0x211: // ȑ [LATIN SMALL LETTER R WITH DOUBLE GRAVE] case 0x213: // ȓ [LATIN SMALL LETTER R WITH INVERTED BREVE] case 0x24d: // ɍ [LATIN SMALL LETTER R WITH STROKE] case 0x24e1: // ⓡ [CIRCLED LATIN SMALL LETTER R] case 0x27c: // ɼ [LATIN SMALL LETTER R WITH LONG LEG] case 0x27d: // ɽ [LATIN SMALL LETTER R WITH TAIL] case 0x27e: // ɾ [LATIN SMALL LETTER R WITH FISHHOOK] case 0x27f: // ɿ [LATIN SMALL LETTER REVERSED R WITH FISHHOOK] case 0xa75b: // ꝛ [LATIN SMALL LETTER R ROTUNDA] case 0xa783: // ꞃ [LATIN SMALL LETTER INSULAR R] case 0xff52: // r [FULLWIDTH LATIN SMALL LETTER R] replacement = 'r'; break; case 0x15b: // ś [LATIN SMALL LETTER S WITH ACUTE] case 0x15d: // ŝ [LATIN SMALL LETTER S WITH CIRCUMFLEX] case 0x15f: // ş [LATIN SMALL LETTER S WITH CEDILLA] case 0x161: // š [LATIN SMALL LETTER S WITH CARON] case 0x17f: // ſ http;//en.wikipedia.org/wiki/Long_S [LATIN SMALL LETTER LONG S] case 0x1d74: // ᵴ [LATIN SMALL LETTER S WITH MIDDLE TILDE] case 0x1d8a: // ᶊ [LATIN SMALL LETTER S WITH PALATAL HOOK] case 0x1e61: // ṡ [LATIN SMALL LETTER S WITH DOT ABOVE] case 0x1e63: // ṣ [LATIN SMALL LETTER S WITH DOT BELOW] case 0x1e65: // ṥ [LATIN SMALL LETTER S WITH ACUTE AND DOT ABOVE] case 0x1e67: // ṧ [LATIN SMALL LETTER S WITH CARON AND DOT ABOVE] case 0x1e69: // ṩ [LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE] case 0x1e9c: // ẜ [LATIN SMALL LETTER LONG S WITH DIAGONAL STROKE] case 0x1e9d: // ẝ [LATIN SMALL LETTER LONG S WITH HIGH STROKE] case 0x219: // ș [LATIN SMALL LETTER S WITH COMMA BELOW] case 0x23f: // ȿ [LATIN SMALL LETTER S WITH SWASH TAIL] case 0x24e2: // ⓢ [CIRCLED LATIN SMALL LETTER S] case 0x282: // ʂ [LATIN SMALL LETTER S WITH HOOK] case 0xa784: // Ꞅ [LATIN CAPITAL LETTER INSULAR S] case 0xff53: // s [FULLWIDTH LATIN SMALL LETTER S] replacement = 's'; break; case 0x163: // ţ [LATIN SMALL LETTER T WITH CEDILLA] case 0x165: // ť [LATIN SMALL LETTER T WITH CARON] case 0x167: // ŧ [LATIN SMALL LETTER T WITH STROKE] case 0x1ab: // ƫ [LATIN SMALL LETTER T WITH PALATAL HOOK] case 0x1ad: // ƭ [LATIN SMALL LETTER T WITH HOOK] case 0x1d75: // ᵵ [LATIN SMALL LETTER T WITH MIDDLE TILDE] case 0x1e6b: // ṫ [LATIN SMALL LETTER T WITH DOT ABOVE] case 0x1e6d: // ṭ [LATIN SMALL LETTER T WITH DOT BELOW] case 0x1e6f: // ṯ [LATIN SMALL LETTER T WITH LINE BELOW] case 0x1e71: // ṱ [LATIN SMALL LETTER T WITH CIRCUMFLEX BELOW] case 0x1e97: // ẗ [LATIN SMALL LETTER T WITH DIAERESIS] case 0x21b: // ț [LATIN SMALL LETTER T WITH COMMA BELOW] case 0x236: // ȶ [LATIN SMALL LETTER T WITH CURL] case 0x24e3: // ⓣ [CIRCLED LATIN SMALL LETTER T] case 0x287: // ʇ [LATIN SMALL LETTER TURNED T] case 0x288: // ʈ [LATIN SMALL LETTER T WITH RETROFLEX HOOK] case 0x2c66: // ⱦ [LATIN SMALL LETTER T WITH DIAGONAL STROKE] case 0xff54: // t [FULLWIDTH LATIN SMALL LETTER T] replacement = 't'; break; case 0x169: // ũ [LATIN SMALL LETTER U WITH TILDE] case 0x16b: // ū [LATIN SMALL LETTER U WITH MACRON] case 0x16d: // ŭ [LATIN SMALL LETTER U WITH BREVE] case 0x16f: // ů [LATIN SMALL LETTER U WITH RING ABOVE] case 0x171: // ű [LATIN SMALL LETTER U WITH DOUBLE ACUTE] case 0x173: // ų [LATIN SMALL LETTER U WITH OGONEK] case 0x1b0: // ư [LATIN SMALL LETTER U WITH HORN] case 0x1d4: // ǔ [LATIN SMALL LETTER U WITH CARON] case 0x1d6: // ǖ [LATIN SMALL LETTER U WITH DIAERESIS AND MACRON] case 0x1d64: // ᵤ [LATIN SUBSCRIPT SMALL LETTER U] case 0x1d8: // ǘ [LATIN SMALL LETTER U WITH DIAERESIS AND ACUTE] case 0x1d99: // ᶙ [LATIN SMALL LETTER U WITH RETROFLEX HOOK] case 0x1da: // ǚ [LATIN SMALL LETTER U WITH DIAERESIS AND CARON] case 0x1dc: // ǜ [LATIN SMALL LETTER U WITH DIAERESIS AND GRAVE] case 0x1e73: // ṳ [LATIN SMALL LETTER U WITH DIAERESIS BELOW] case 0x1e75: // ṵ [LATIN SMALL LETTER U WITH TILDE BELOW] case 0x1e77: // ṷ [LATIN SMALL LETTER U WITH CIRCUMFLEX BELOW] case 0x1e79: // ṹ [LATIN SMALL LETTER U WITH TILDE AND ACUTE] case 0x1e7b: // ṻ [LATIN SMALL LETTER U WITH MACRON AND DIAERESIS] case 0x1ee5: // ụ [LATIN SMALL LETTER U WITH DOT BELOW] case 0x1ee7: // ủ [LATIN SMALL LETTER U WITH HOOK ABOVE] case 0x1ee9: // ứ [LATIN SMALL LETTER U WITH HORN AND ACUTE] case 0x1eeb: // ừ [LATIN SMALL LETTER U WITH HORN AND GRAVE] case 0x1eed: // ử [LATIN SMALL LETTER U WITH HORN AND HOOK ABOVE] case 0x1eef: // ữ [LATIN SMALL LETTER U WITH HORN AND TILDE] case 0x1ef1: // ự [LATIN SMALL LETTER U WITH HORN AND DOT BELOW] case 0x215: // ȕ [LATIN SMALL LETTER U WITH DOUBLE GRAVE] case 0x217: // ȗ [LATIN SMALL LETTER U WITH INVERTED BREVE] case 0x24e4: // ⓤ [CIRCLED LATIN SMALL LETTER U] case 0x289: // ʉ [LATIN SMALL LETTER U BAR] case 0xf9: // ù [LATIN SMALL LETTER U WITH GRAVE] case 0xfa: // ú [LATIN SMALL LETTER U WITH ACUTE] case 0xfb: // û [LATIN SMALL LETTER U WITH CIRCUMFLEX] case 0xfc: // ü [LATIN SMALL LETTER U WITH DIAERESIS] case 0xff55: // u [FULLWIDTH LATIN SMALL LETTER U] replacement = 'u'; break; case 0x175: // ŵ [LATIN SMALL LETTER W WITH CIRCUMFLEX] case 0x1bf: // ƿ http;//en.wikipedia.org/wiki/Wynn [LATIN LETTER WYNN] case 0x1e81: // ẁ [LATIN SMALL LETTER W WITH GRAVE] case 0x1e83: // ẃ [LATIN SMALL LETTER W WITH ACUTE] case 0x1e85: // ẅ [LATIN SMALL LETTER W WITH DIAERESIS] case 0x1e87: // ẇ [LATIN SMALL LETTER W WITH DOT ABOVE] case 0x1e89: // ẉ [LATIN SMALL LETTER W WITH DOT BELOW] case 0x1e98: // ẘ [LATIN SMALL LETTER W WITH RING ABOVE] case 0x24e6: // ⓦ [CIRCLED LATIN SMALL LETTER W] case 0x28d: // ʍ [LATIN SMALL LETTER TURNED W] case 0x2c73: // ⱳ [LATIN SMALL LETTER W WITH HOOK] case 0xff57: // w [FULLWIDTH LATIN SMALL LETTER W] replacement = 'w'; break; case 0x177: // ŷ [LATIN SMALL LETTER Y WITH CIRCUMFLEX] case 0x1b4: // ƴ [LATIN SMALL LETTER Y WITH HOOK] case 0x1e8f: // ẏ [LATIN SMALL LETTER Y WITH DOT ABOVE] case 0x1e99: // ẙ [LATIN SMALL LETTER Y WITH RING ABOVE] case 0x1ef3: // ỳ [LATIN SMALL LETTER Y WITH GRAVE] case 0x1ef5: // ỵ [LATIN SMALL LETTER Y WITH DOT BELOW] case 0x1ef7: // ỷ [LATIN SMALL LETTER Y WITH HOOK ABOVE] case 0x1ef9: // ỹ [LATIN SMALL LETTER Y WITH TILDE] case 0x1eff: // ỿ [LATIN SMALL LETTER Y WITH LOOP] case 0x233: // ȳ [LATIN SMALL LETTER Y WITH MACRON] case 0x24e8: // ⓨ [CIRCLED LATIN SMALL LETTER Y] case 0x24f: // ɏ [LATIN SMALL LETTER Y WITH STROKE] case 0x28e: // ʎ [LATIN SMALL LETTER TURNED Y] case 0xfd: // ý [LATIN SMALL LETTER Y WITH ACUTE] case 0xff: // ÿ [LATIN SMALL LETTER Y WITH DIAERESIS] case 0xff59: // y [FULLWIDTH LATIN SMALL LETTER Y] replacement = 'y'; break; case 0x17a: // ź [LATIN SMALL LETTER Z WITH ACUTE] case 0x17c: // ż [LATIN SMALL LETTER Z WITH DOT ABOVE] case 0x17e: // ž [LATIN SMALL LETTER Z WITH CARON] case 0x1b6: // ƶ [LATIN SMALL LETTER Z WITH STROKE] case 0x1d76: // ᵶ [LATIN SMALL LETTER Z WITH MIDDLE TILDE] case 0x1d8e: // ᶎ [LATIN SMALL LETTER Z WITH PALATAL HOOK] case 0x1e91: // ẑ [LATIN SMALL LETTER Z WITH CIRCUMFLEX] case 0x1e93: // ẓ [LATIN SMALL LETTER Z WITH DOT BELOW] case 0x1e95: // ẕ [LATIN SMALL LETTER Z WITH LINE BELOW] case 0x21d: // ȝ http;//en.wikipedia.org/wiki/Yogh [LATIN SMALL LETTER YOGH] case 0x225: // ȥ [LATIN SMALL LETTER Z WITH HOOK] case 0x240: // ɀ [LATIN SMALL LETTER Z WITH SWASH TAIL] case 0x24e9: // ⓩ [CIRCLED LATIN SMALL LETTER Z] case 0x290: // ʐ [LATIN SMALL LETTER Z WITH RETROFLEX HOOK] case 0x291: // ʑ [LATIN SMALL LETTER Z WITH CURL] case 0x2c6c: // ⱬ [LATIN SMALL LETTER Z WITH DESCENDER] case 0xa763: // ꝣ [LATIN SMALL LETTER VISIGOTHIC Z] case 0xff5a: // z [FULLWIDTH LATIN SMALL LETTER Z] replacement = 'z'; break; case 0x180: // ƀ [LATIN SMALL LETTER B WITH STROKE] case 0x183: // ƃ [LATIN SMALL LETTER B WITH TOPBAR] case 0x1d6c: // ᵬ [LATIN SMALL LETTER B WITH MIDDLE TILDE] case 0x1d80: // ᶀ [LATIN SMALL LETTER B WITH PALATAL HOOK] case 0x1e03: // ḃ [LATIN SMALL LETTER B WITH DOT ABOVE] case 0x1e05: // ḅ [LATIN SMALL LETTER B WITH DOT BELOW] case 0x1e07: // ḇ [LATIN SMALL LETTER B WITH LINE BELOW] case 0x24d1: // ⓑ [CIRCLED LATIN SMALL LETTER B] case 0x253: // ɓ [LATIN SMALL LETTER B WITH HOOK] case 0xff42: // b [FULLWIDTH LATIN SMALL LETTER B] replacement = 'b'; break; case 0x192: // ƒ [LATIN SMALL LETTER F WITH HOOK] case 0x1d6e: // ᵮ [LATIN SMALL LETTER F WITH MIDDLE TILDE] case 0x1d82: // ᶂ [LATIN SMALL LETTER F WITH PALATAL HOOK] case 0x1e1f: // ḟ [LATIN SMALL LETTER F WITH DOT ABOVE] case 0x1e9b: // ẛ [LATIN SMALL LETTER LONG S WITH DOT ABOVE] case 0x24d5: // ⓕ [CIRCLED LATIN SMALL LETTER F] case 0xa77c: // ꝼ [LATIN SMALL LETTER INSULAR F] case 0xff46: // f [FULLWIDTH LATIN SMALL LETTER F] replacement = 'f'; break; case 0x1a5: // ƥ [LATIN SMALL LETTER P WITH HOOK] case 0x1d71: // ᵱ [LATIN SMALL LETTER P WITH MIDDLE TILDE] case 0x1d7d: // ᵽ [LATIN SMALL LETTER P WITH STROKE] case 0x1d88: // ᶈ [LATIN SMALL LETTER P WITH PALATAL HOOK] case 0x1e55: // ṕ [LATIN SMALL LETTER P WITH ACUTE] case 0x1e57: // ṗ [LATIN SMALL LETTER P WITH DOT ABOVE] case 0x24df: // ⓟ [CIRCLED LATIN SMALL LETTER P] case 0xa751: // ꝑ [LATIN SMALL LETTER P WITH STROKE THROUGH DESCENDER] case 0xa753: // ꝓ [LATIN SMALL LETTER P WITH FLOURISH] case 0xa755: // ꝕ [LATIN SMALL LETTER P WITH SQUIRREL TAIL] case 0xa7fc: // ꟼ [LATIN EPIGRAPHIC LETTER REVERSED P] case 0xff50: // p [FULLWIDTH LATIN SMALL LETTER P] replacement = 'p'; break; case 0x1c6: // dž [LATIN SMALL LETTER DZ WITH CARON] case 0x1f3: // dz [LATIN SMALL LETTER DZ] case 0x2a3: // ʣ [LATIN SMALL LETTER DZ DIGRAPH] case 0x2a5: // ʥ [LATIN SMALL LETTER DZ DIGRAPH WITH CURL] replacement = 'dz'; break; case 0x1d65: // ᵥ [LATIN SUBSCRIPT SMALL LETTER V] case 0x1d8c: // ᶌ [LATIN SMALL LETTER V WITH PALATAL HOOK] case 0x1e7d: // ṽ [LATIN SMALL LETTER V WITH TILDE] case 0x1e7f: // ṿ [LATIN SMALL LETTER V WITH DOT BELOW] case 0x24e5: // ⓥ [CIRCLED LATIN SMALL LETTER V] case 0x28b: // ʋ [LATIN SMALL LETTER V WITH HOOK] case 0x28c: // ʌ [LATIN SMALL LETTER TURNED V] case 0x2c71: // ⱱ [LATIN SMALL LETTER V WITH RIGHT HOOK] case 0x2c74: // ⱴ [LATIN SMALL LETTER V WITH CURL] case 0xa75f: // ꝟ [LATIN SMALL LETTER V WITH DIAGONAL STROKE] case 0xff56: // v [FULLWIDTH LATIN SMALL LETTER V] replacement = 'v'; break; case 0x1d6f: // ᵯ [LATIN SMALL LETTER M WITH MIDDLE TILDE] case 0x1d86: // ᶆ [LATIN SMALL LETTER M WITH PALATAL HOOK] case 0x1e3f: // ḿ [LATIN SMALL LETTER M WITH ACUTE] case 0x1e41: // ṁ [LATIN SMALL LETTER M WITH DOT ABOVE] case 0x1e43: // ṃ [LATIN SMALL LETTER M WITH DOT BELOW] case 0x24dc: // ⓜ [CIRCLED LATIN SMALL LETTER M] case 0x26f: // ɯ [LATIN SMALL LETTER TURNED M] case 0x270: // ɰ [LATIN SMALL LETTER TURNED M WITH LONG LEG] case 0x271: // ɱ [LATIN SMALL LETTER M WITH HOOK] case 0xff4d: // m [FULLWIDTH LATIN SMALL LETTER M] replacement = 'm'; break; case 0x1d8d: // ᶍ [LATIN SMALL LETTER X WITH PALATAL HOOK] case 0x1e8b: // ẋ [LATIN SMALL LETTER X WITH DOT ABOVE] case 0x1e8d: // ẍ [LATIN SMALL LETTER X WITH DIAERESIS] case 0x2093: // ₓ [LATIN SUBSCRIPT SMALL LETTER X] case 0x24e7: // ⓧ [CIRCLED LATIN SMALL LETTER X] case 0xff58: // x [FULLWIDTH LATIN SMALL LETTER X] replacement = 'x'; break; default: // we assume character is not a letter so we pass it on replacement = this.charAt(i); break; } // add it to string outStr += upper ? replacement.toUpperCase() : replacement; } } } return outStr; }
// MODIFICATION https://github.com/galerija/toascii-js This is a modification of fold-to-ascii.js (https://github.com/mplatt/fold-to-ascii-js). Original (fold-to-ascii) functions were combined into a new string method. Beside that characters database was limited to lowercase characters only and lower/uppercase transformation is used instead. All credit goes to the original author. // USAGE Use as any other function: toAscii(string); // ORIGINAL LICENSE AND INFO fold-to-ascii.js https://github.com/mplatt/fold-to-ascii-js This is a JavaScript port of the Apache Lucene ASCII Folding Filter. The Apache Lucene ASCII Folding Filter is licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. This port uses an example from the Mozilla Developer Network published prior to August 20, 2010 fixedCharCodeAt is licencesed under the MIT License (MIT) Copyright (c) 2013 Mozilla Developer Network and individual contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
toAscii ( string )
javascript
fuse-box/fuse-box
modules/url/toAscii.js
https://github.com/fuse-box/fuse-box/blob/master/modules/url/toAscii.js
MIT
var cssHandler = function(__filename, contents) { var styleId = __filename.replace(/[\.\/]+/g, '-'); if (styleId.charAt(0) === '-') styleId = styleId.substring(1); var exists = document.getElementById(styleId); if (!exists) { //<link href="//fonts.googleapis.com/css?family=Covered+By+Your+Grace" rel="stylesheet" type="text/css"> var s = document.createElement(contents ? 'style' : 'link'); s.id = styleId; s.type = 'text/css'; if (contents) { s.innerHTML = contents; } else { s.rel = 'stylesheet'; s.href = __filename; } document.getElementsByTagName('head')[0].appendChild(s); } else { if (contents) exists.innerHTML = contents; } }; module.exports = cssHandler;
Listens to 'async' requets and if the name is a css file wires it to `__fsbx_css`
cssHandler ( __filename , contents )
javascript
fuse-box/fuse-box
modules/fuse-box-css/index.js
https://github.com/fuse-box/fuse-box/blob/master/modules/fuse-box-css/index.js
MIT
var warningWithoutStack = function() {};
Similar to invariant but only logs a warning if the condition is not met. This can be used to log issues in development environments in critical paths. Removing the logging code for production environments will keep the same logic and follow the same code paths.
warningWithoutStack ( )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
function executeDispatch(event, listener, inst) { var type = event.type || 'unknown-event'; event.currentTarget = getNodeFromInstance(inst); invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event); event.currentTarget = null; }
Dispatch the event to the listener. @param {SyntheticEvent} event SyntheticEvent to handle @param {function} listener Application-level callback @param {*} inst Internal component instance
executeDispatch ( event , listener , inst )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
function forEachAccumulated(arr, cb, scope) { if (Array.isArray(arr)) { arr.forEach(cb, scope); } else if (arr) { cb.call(scope, arr); } }
@param {array} arr an "accumulation" of items which is either an Array or a single item. Useful when paired with the `accumulate` module. This is a simple utility that allows us to reason about a collection of items, but handling the case when there is exactly one item (and we do not need to allocate an array). @param {function} cb Callback invoked with each element or a collection. @param {?} [scope] Scope used as `this` in a callback.
forEachAccumulated ( arr , cb , scope )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
var executeDispatchesAndRelease = function(event) { if (event) { executeDispatchesInOrder(event); if (!event.isPersistent()) { event.constructor.release(event); } } };
Dispatches an event and releases it back into the pool, unless persistent. @param {?object} event Synthetic event to be dispatched. @private
executeDispatchesAndRelease ( event )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
function extractPluginEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) { var events = null; for (var i = 0; i < plugins.length; i++) { // Not every plugin in the ordering may be loaded at runtime. var possiblePlugin = plugins[i]; if (possiblePlugin) { var extractedEvents = possiblePlugin.extractEvents( topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, ); if (extractedEvents) { events = accumulateInto(events, extractedEvents); } } } return events; }
Allows registered plugins an opportunity to extract events from top-level native browser events. @return {*} An accumulation of synthetic events. @internal
extractPluginEvents ( topLevelType , targetInst , nativeEvent , nativeEventTarget , eventSystemFlags )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT