repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
brisa
github_2023
brisa-build
typescript
manageContextProviderCompletion
const manageContextProviderCompletion = () => { if (isWebComponentSelector && webComponentSymbol) { clearProvidersByWCSymbol(webComponentSymbol, request); return controller.setCurrentWebComponentSymbol(); } if (!isSlottedContent || !slottedContentProviders?.length) return; for (c...
// Manage context provider completion to wait for more slots (pause) or
https://github.com/brisa-build/brisa/blob/92fb8fe4766c6e2cd026adf1d07be0ccad1f64b9/packages/brisa/src/utils/render-to-readable-stream/index.ts#L230-L239
92fb8fe4766c6e2cd026adf1d07be0ccad1f64b9
brisa
github_2023
brisa-build
typescript
rpc
async function rpc( actionId: string, isFormData = false, indicator: string | null, dataSet: DOMStringMap, ...args: unknown[] ) { const errorIndicator = 'e' + indicator; const elementsWithIndicator = []; const store = $window._s; const promise = loadRPCResolver(); // Add the "brisa-request" class t...
/** * RPC (Remote Procedure Call) * * This function is used to call an action on the server. */
https://github.com/brisa-build/brisa/blob/92fb8fe4766c6e2cd026adf1d07be0ccad1f64b9/packages/brisa/src/utils/rpc/rpc.ts#L45-L98
92fb8fe4766c6e2cd026adf1d07be0ccad1f64b9
brisa
github_2023
brisa-build
typescript
registerDeclarationsAndImports
function registerDeclarationsAndImports(this: any, key: string, value: any) { if (value?.type === 'VariableDeclarator' && value?.init) { declarations.set(value.id.name, value.init); } else if ( value?.type === 'AssignmentExpression' && value?.left?.type === 'Identifier' ) { declarati...
/** * The first traversal is to locate all variable declarations and store * them in a Map along with the identifier name, along with the value. * * This data will be useful in the second traversal, when using props * in the component with the spreadOperator, we will have to look * (as long as they a...
https://github.com/brisa-build/brisa/blob/92fb8fe4766c6e2cd026adf1d07be0ccad1f64b9/packages/brisa/src/utils/server-component-plugin/index.ts#L71-L91
92fb8fe4766c6e2cd026adf1d07be0ccad1f64b9
brisa
github_2023
brisa-build
typescript
traverseB2A
function traverseB2A(this: any, key: string, value: any) { const isJSX = value?.type === 'CallExpression' && isJSXIdentifier(value?.callee?.name); const isActionsFlag = isServerOutput && value?._hasActions; const isComponent = isUpperCaseChar(value?.arguments?.[0]?.name); // Register declarations...
/** * The second traversal is useful to add the data-action field with 2 goals: * * - Client (runtime): To let the RPC know that there is a server action * in the HTML. * - Build time: After this initial compilation, an extra compilation is done * to generate the action files, where they start fro...
https://github.com/brisa-build/brisa/blob/92fb8fe4766c6e2cd026adf1d07be0ccad1f64b9/packages/brisa/src/utils/server-component-plugin/index.ts#L103-L462
92fb8fe4766c6e2cd026adf1d07be0ccad1f64b9
brisa
github_2023
brisa-build
typescript
transformActionIdentifierAttributeToArrow
function transformActionIdentifierAttributeToArrow(attribute: any) { return { type: 'Property', key: { type: 'Identifier', name: attribute.key.name, }, value: { type: 'ArrowFunctionExpression', params: [ { type: 'RestElement', argument: { ...
// For elements, we need to create an arrow function to enable the `renderComponent` to
https://github.com/brisa-build/brisa/blob/92fb8fe4766c6e2cd026adf1d07be0ccad1f64b9/packages/brisa/src/utils/server-component-plugin/index.ts#L639-L681
92fb8fe4766c6e2cd026adf1d07be0ccad1f64b9
brisa
github_2023
brisa-build
typescript
indicate
function indicate(key: string): IndicatorSignal { const id = INDICATE_PREFIX + key; const indicator = derived(() => !!store.get(id)) as IndicatorSignal; indicator.id = id; indicator.error = derived(() => store.get('e' + id)); return indicator; }
// generate a server action indicator signal
https://github.com/brisa-build/brisa/blob/92fb8fe4766c6e2cd026adf1d07be0ccad1f64b9/packages/brisa/src/utils/signals/index.ts#L211-L219
92fb8fe4766c6e2cd026adf1d07be0ccad1f64b9
brisa
github_2023
brisa-build
typescript
getDicValue
function getDicValue( dic: I18nDictionary, key = '', config: I18nConfig, options: { returnObjects?: boolean; fallback?: string | string[] } = { returnObjects: false, }, ): unknown | undefined { const { keySeparator = '.' } = config || {}; const keyParts = keySeparator ? key.split(keySeparator) : [key]...
/** * Get value from key (allow nested keys as parent.children) */
https://github.com/brisa-build/brisa/blob/92fb8fe4766c6e2cd026adf1d07be0ccad1f64b9/packages/brisa/src/utils/translate-core/index.ts#L106-L139
92fb8fe4766c6e2cd026adf1d07be0ccad1f64b9
brisa
github_2023
brisa-build
typescript
plural
function plural( pluralRules: Intl.PluralRules, dic: I18nDictionary, key: string, config: I18nConfig, query?: TranslationQuery | null, ): string { if (!query || typeof query.count !== 'number') return key; const numKey = `${key}_${query.count}`; if (getDicValue(dic, numKey, config) !== undefined) retur...
/** * Control plural keys depending the {{count}} variable */
https://github.com/brisa-build/brisa/blob/92fb8fe4766c6e2cd026adf1d07be0ccad1f64b9/packages/brisa/src/utils/translate-core/index.ts#L144-L168
92fb8fe4766c6e2cd026adf1d07be0ccad1f64b9
brisa
github_2023
brisa-build
typescript
interpolation
function interpolation({ text, query, config, locale, }: { text?: string; query?: TranslationQuery | null; config: I18nConfig; locale: string; }): string { if (!text || !query) return text || ''; const escapeRegex = (str: string) => str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); const { f...
/** * Replace {{variables}} to query values */
https://github.com/brisa-build/brisa/blob/92fb8fe4766c6e2cd026adf1d07be0ccad1f64b9/packages/brisa/src/utils/translate-core/index.ts#L173-L210
92fb8fe4766c6e2cd026adf1d07be0ccad1f64b9
gpt-home
github_2023
judahpaul16
typescript
setStatus
const setStatus = (name: string, status: boolean) => { setIntegrations(prevIntegrations => ({ ...prevIntegrations, [name]: { ...prevIntegrations[name as keyof typeof prevIntegrations], status } })); };
// Set status of integration
https://github.com/judahpaul16/gpt-home/blob/e82cf8d0b9f873c37435c1dd91fbef13a781dab2/src/frontend/src/App.tsx#L90-L98
e82cf8d0b9f873c37435c1dd91fbef13a781dab2
gpt-home
github_2023
judahpaul16
typescript
toggleStatus
const toggleStatus = (name: string) => { if (name in integrations) { setIntegrations({ ...integrations, [name]: { ...integrations[name as keyof typeof integrations], status: !integrations[name as keyof typeof integrations].status } }); } };
// Toggle status of integration
https://github.com/judahpaul16/gpt-home/blob/e82cf8d0b9f873c37435c1dd91fbef13a781dab2/src/frontend/src/App.tsx#L101-L111
e82cf8d0b9f873c37435c1dd91fbef13a781dab2
gcopy
github_2023
llaoj
typescript
onFocus
const onFocus = () => setFocused(true);
// Focus for additional renders
https://github.com/llaoj/gcopy/blob/b886596d2f172980ea4443da4eacf88c3ad4848c/frontend/lib/window-focus.ts#L11-L11
b886596d2f172980ea4443da4eacf88c3ad4848c
zotero-plugins
github_2023
zotero-chinese
typescript
parseInstallRef
function parseInstallRef(zip: AdmZip) { const fileData = zip.getEntry('install.rdf')!.getData().toString('utf8') // 从 install.rdf 中获取 id const id = (fileData.match(/em:id="(.*?)"/) ?? fileData.match(/<em:id>(.*?)<\/em:id>/) ?? [ '', 'NO id', ])[1] // 从 install.rdf 中获取 description const descr...
// 临时恢复 Zotero 6 插件解析
https://github.com/zotero-chinese/zotero-plugins/blob/3527e345bf1d3d29c1c4983e0d6bf37857e5102d/src/handler/plugins-data.ts#L149-L181
3527e345bf1d3d29c1c4983e0d6bf37857e5102d
tsslint
github_2023
johnsoncodehk
typescript
foo
function foo(bool?: boolean) { if (bool) { bar(); } }
// nullable booleans are considered unsafe by default
https://github.com/johnsoncodehk/tsslint/blob/a164ff719def41ce69256fd7260e9e0fb1017e48/fixtures/convert-a-tslint-rule/fixture.ts#L15-L19
a164ff719def41ce69256fd7260e9e0fb1017e48
tsslint
github_2023
johnsoncodehk
typescript
foo
const foo = <T>(arg: T) => (arg ? 1 : 0);
// `any`, unconstrained generics and unions of more than one primitive type are disallowed
https://github.com/johnsoncodehk/tsslint/blob/a164ff719def41ce69256fd7260e9e0fb1017e48/fixtures/convert-a-tslint-rule/fixture.ts#L22-L22
a164ff719def41ce69256fd7260e9e0fb1017e48
tsslint
github_2023
johnsoncodehk
typescript
head
function head<T>(items: T[]) { // items can never be nullable, so this is unnecessary if (items) { return items[0].toUpperCase(); } }
// @ts-nocheck
https://github.com/johnsoncodehk/tsslint/blob/a164ff719def41ce69256fd7260e9e0fb1017e48/fixtures/convert-eslint-rules/cases/no-unnecessary-condition.ts#L2-L7
a164ff719def41ce69256fd7260e9e0fb1017e48
tsslint
github_2023
johnsoncodehk
typescript
invalidInTryCatch1
async function invalidInTryCatch1() { try { return Promise.reject('try'); } catch (e) { // Doesn't execute due to missing await. } }
// @ts-nocheck
https://github.com/johnsoncodehk/tsslint/blob/a164ff719def41ce69256fd7260e9e0fb1017e48/fixtures/convert-eslint-rules/cases/return-await.ts#L3-L9
a164ff719def41ce69256fd7260e9e0fb1017e48
tsslint
github_2023
johnsoncodehk
typescript
invalidInTryCatch3
async function invalidInTryCatch3() { async function doAsyncWork(): Promise<void> { console.log('starting async work'); await new Promise(resolve => setTimeout(resolve, 1000)); console.log('async work done'); } try { throw new Error('error'); } catch (e) { // Missing await. return doAsyncWork(); } fin...
// Prints 'starting async work', 'cleanup', 'async work done'.
https://github.com/johnsoncodehk/tsslint/blob/a164ff719def41ce69256fd7260e9e0fb1017e48/fixtures/convert-eslint-rules/cases/return-await.ts#L21-L36
a164ff719def41ce69256fd7260e9e0fb1017e48
tsslint
github_2023
johnsoncodehk
typescript
foo
function foo(bool?: boolean) { if (bool) { bar(); } }
// nullable booleans are considered unsafe by default
https://github.com/johnsoncodehk/tsslint/blob/a164ff719def41ce69256fd7260e9e0fb1017e48/fixtures/convert-eslint-rules/cases/strict-boolean-expressions.ts#L15-L19
a164ff719def41ce69256fd7260e9e0fb1017e48
tsslint
github_2023
johnsoncodehk
typescript
foo
const foo = <T>(arg: T) => (arg ? 1 : 0);
// `any`, unconstrained generics and unions of more than one primitive type are disallowed
https://github.com/johnsoncodehk/tsslint/blob/a164ff719def41ce69256fd7260e9e0fb1017e48/fixtures/convert-eslint-rules/cases/strict-boolean-expressions.ts#L22-L22
a164ff719def41ce69256fd7260e9e0fb1017e48
tsslint
github_2023
johnsoncodehk
typescript
AnotherComponent
const AnotherComponent = () => vine`<div>Hello World</div>`
// This is also valid
https://github.com/johnsoncodehk/tsslint/blob/a164ff719def41ce69256fd7260e9e0fb1017e48/fixtures/meta-frameworks-support/fixture.vine.ts#L6-L6
a164ff719def41ce69256fd7260e9e0fb1017e48
tsslint
github_2023
johnsoncodehk
typescript
tsColor
const tsColor = (s: string) => '\x1b[34m' + s + _reset;
// https://talyian.github.io/ansicolors/
https://github.com/johnsoncodehk/tsslint/blob/a164ff719def41ce69256fd7260e9e0fb1017e48/packages/cli/index.ts#L22-L22
a164ff719def41ce69256fd7260e9e0fb1017e48
kviklet
github_2023
kviklet
typescript
djb2
const djb2 = (str: string) => { let hash = 5381; for (let i = 0; i < str.length; i++) { const char = str.charCodeAt(i); hash = (hash << 5) + hash + char; /* hash * 33 + char */ } return hash; };
// hash the label text to get a color inside the tailwindcss color palette
https://github.com/kviklet/kviklet/blob/388a3534d2d6bc9d1f24a500e5ae428bf3cb0efe/frontend/src/components/ColorfulLabel.tsx#L11-L18
388a3534d2d6bc9d1f24a500e5ae428bf3cb0efe
kviklet
github_2023
kviklet
typescript
handleStreamSQLDump
const handleStreamSQLDump = async ( executionRequestId: string, connectionId: string, ) => { try { const fileHandle = await fileHandler(connectionId); const responseStream = await streamDump(executionRequestId); const reader = responseStream.getReader(); const writableStream = awa...
// Function to handle streaming the SQL dump and saving it to a file
https://github.com/kviklet/kviklet/blob/388a3534d2d6bc9d1f24a500e5ae428bf3cb0efe/frontend/src/routes/Review/DatasourceRequestBox.tsx#L137-L179
388a3534d2d6bc9d1f24a500e5ae428bf3cb0efe
kviklet
github_2023
kviklet
typescript
pump
const pump = async () => { let done = false; while (!done) { const result = await reader.read(); done = result.done; const value = result.value; if (value !== undefined) { await writableStream.write(value); } } await writableS...
// Handle reading from the readable stream and writing to the writable stream
https://github.com/kviklet/kviklet/blob/388a3534d2d6bc9d1f24a500e5ae428bf3cb0efe/frontend/src/routes/Review/DatasourceRequestBox.tsx#L149-L160
388a3534d2d6bc9d1f24a500e5ae428bf3cb0efe
ui.tailus.io
github_2023
Tailus-UI
typescript
useToastState
const useToastState = () => { const [open, setOpen] = React.useState(false); const eventDateRef = React.useRef(new Date()); const timerRef = React.useRef(0); React.useEffect(() => { const timer = timerRef.current; return () => clearTimeout(timer); }, []); return {open, setOpen, eventDateRef, time...
// Custom hooks for managing state and effects
https://github.com/Tailus-UI/ui.tailus.io/blob/d384d45101388e811b41a37dcd736a4e871cb022/src/components/toast/Toast.stories.tsx#L8-L20
d384d45101388e811b41a37dcd736a4e871cb022
obsidian-modal-form
github_2023
danielo515
typescript
API.constructor
constructor( private app: App, private plugin: ModalFormPlugin, ) { this.builder = makeBuilder((title, message) => log_notice(message, title)); }
/** * Constructor for the API class * @param {App} app - The application instance * @param {typeof ModalFormPlugin} plugin - The plugin instance */
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/API.ts#L57-L62
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
API.openModalForm
openModalForm(formDefinition: FormDefinition, options?: FormOptions): Promise<FormResult> { return new Promise((resolve) => { new FormModal(this.app, formDefinition, resolve, options).open(); }); }
/** * Opens a modal form with the provided form definition * @param {FormDefinition} formDefinition - The form definition to use * @returns {Promise<FormResult>} - A promise that resolves with the form result */
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/API.ts#L69-L73
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
API.namedForm
public namedForm(name: string, options?: FormOptions): Promise<FormResult> { const formDefinition = this.getFormByName(name); if (formDefinition) { return this.openModalForm(formDefinition, options); } else { const error = new ModalFormError(`Form definition ${name} not f...
/** * Opens a named form * @param {string} name - The name of the form to open * @returns {Promise<FormResult>} - A promise that resolves with the form result * @throws {ModalFormError} - Throws an error if the form definition is not found */
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/API.ts#L99-L108
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
API.limitedForm
public limitedForm( name: string, limitOpts: limitOptions, formOpts?: FormOptions, ): Promise<FormResult> { const formDefinition = this.getFormByName(name); let newFormDefinition: FormDefinition; if (formDefinition) { if (isOmitOption(limitOpts)) { ...
/** * Opens a named form, limiting/filtering the fields included * @param {string} name - The name of the form to open * @param {limitOptions} limitOpts - The options to apply when filtering fields * @param {FormOptions} formOpts - Form options to use when opening the form once filtered * @retu...
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/API.ts#L118-L151
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
API.openForm
public openForm( formReference: string | FormDefinition, options?: FormOptions, ): Promise<FormResult> { if (typeof formReference === "string") { return this.namedForm(formReference, options); } else { return this.openModalForm(formReference, options); ...
/** * Opens a form with the provided form reference * @param {string | FormDefinition} formReference - The form reference, either a form name of an existing form or an inline form definition * @returns {Promise<FormResult>} - A promise that resolves with the form result * @throws {ModalFormError} - ...
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/API.ts#L159-L168
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
ModalFormPlugin.editForm
async editForm(formName: string) { // By reading settings from the disk we get a copy of the form // effectively preventing any unexpected side effects to the running configuration // For example, mutating a form, cancelling the edit but the form is already mutated, // then if you save a...
/** * Opens the form in the editor. * @returns */
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/main.ts#L80-L96
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
ModalFormPlugin.getSettings
async getSettings(): Promise<ModalFormSettings> { const data = await this.loadData(); const [migrationIsNeeded, settings] = pipe( parseSettings(data), E.map((settings): [boolean, ModalFormSettings] => { const migrationIsNeeded = settings.formDefinitions.some(formN...
// TODO: collect actual migration events to decide if we need to migrate or not rather than this naive approach
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/main.ts#L159-L183
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
ModalFormPlugin.getUniqueNoteName
getUniqueNoteName(name: string, destinationFolder?: string): string { const defaultNotesFolder = this.app.fileManager.getNewFileParent("", "note.md"); function makePath(name: string, folder?: string, suffix?: number) { return `${folder || defaultNotesFolder.path}/${name}${suffix ? "-" + suff...
/** * Finds a unique name for a note, given a name. * It just adds a number at the end of the name if the name is already taken. * @param name the name of the note, without the extension * @returns a unique name for the note, full path including the extension */
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/main.ts#L329-L341
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
ModalFormPlugin.createNoteFromForm
createNoteFromForm() { const formsWithTemplates = this.getFormsWithTemplates(); const onFormSelected = async ( form: FormWithTemplate, noteName: string, destinationFolder: string, ) => { const formData = await this.api.openForm(form); c...
/** * Checks if there are forms with templates, and presents a prompt * to select a form, then opens the forms, and creates a new note * with the template and the form values */
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/main.ts#L413-L434
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
createTestBuilder
const createTestBuilder = () => { const mockReporter = jest.fn(); return { builder: makeBuilder(mockReporter), mockReporter, }; };
// Pure function to create a test builder instance
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/core/FormBuilder.test.ts#L5-L11
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
FormResult.asFrontmatterString
asFrontmatterString(options?: unknown) { const data = objectSelect(this.data, options); return stringifyYaml(data); }
/** * Transform the current data into a frontmatter string, which is expected * to be enclosed in `---` when used in a markdown file. * This method does not add the enclosing `---` to the string, * so you can put it anywhere inside the frontmatter. * @param {Object} [options] an options object...
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/core/FormResult.ts#L47-L50
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
FormResult.asDataviewProperties
asDataviewProperties(options?: unknown): string { const data = objectSelect(this.data, options); return Object.entries(data) .map( ([key, value]) => `${key}:: ${ Array.isArray(value) ? value.map((v) => JSON.stringify(v)) : value ...
/** * Return the current data as a block of dataview properties * @param {Object} [options] an options object describing what options to pick or omit * @param {string[]} [options.pick] an array of key names to pick from the data * @param {string[]} [options.omit] an array of key names to omit from t...
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/core/FormResult.ts#L59-L69
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
FormResult.getData
getData() { return { ...this.data }; }
/** Returns a copy of the data contained on this result. */
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/core/FormResult.ts#L73-L75
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
FormResult.asString
asString(template: string): string { let result = template; for (const [key, value] of Object.entries(this.data)) { result = result.replace(new RegExp(`{{${key}}}`, "g"), value + ""); } return result; }
/** * Returns the data formatted as a string matching the provided * template. */
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/core/FormResult.ts#L80-L86
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
FormResult.get
get(key: string, mapFn?: (value: Val) => Val): Val { const value = this.data[key]; if (value === undefined) { return ""; } if (mapFn) { return mapFn(value); } if (typeof value === "object") { return JSON.stringify(value); } ...
/** * Gets a single value from the data. * It takes an optiional mapping function thatt can be used to transform the value. * The function will only be called if the value exists. * @param {string} key the key to get the value from * @param {function} [mapFn] a function to transform the value ...
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/core/FormResult.ts#L95-L107
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
ResultValue.toString
toString() { switch (typeof this.value) { case "string": return this.value; case "number": case "boolean": return this.value.toString(); case "object": if (Array.isArray(this.value)) { return this...
/** * Returns the value as a string. * If the value is an array, it will be joined with a comma. * If the value is an object, it will be stringified. * This is convenient because it is the default method called automatically * when the value needs to be rendered as a string, so you can just dro...
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/core/ResultValue.ts#L58-L73
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
ResultValue.toBulletList
toBulletList() { switch (typeof this.value) { case "boolean": case "number": case "string": return `- ${this.value}`; case "object": { const value = this.value; // if the value is null or undefined, return an empty s...
/** * Returns the value as a bullet list. * If the value is empty or undefined, it will return an empty string. * If the value is a single value, it will return as a single item bullet list. * If the value is an array, it will return a bullet list with each item in the array. * If the value is ...
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/core/ResultValue.ts#L82-L107
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
ResultValue.toDataview
toDataview() { const value = this.value; if (value === undefined) return ""; if (Array.isArray(value)) { return `[${this.name}:: ${JSON.stringify(value).slice(1, -1)}]`; } return `[${this.name}:: ${this.toString()}]`; }
/** * Converts the value to a dataview property using the field name as the key. * If the value is empty or undefined, it will return an empty string and not render anything. */
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/core/ResultValue.ts#L112-L119
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
ResultValue.map
map<U>(fn: (value: T) => U): ResultValue<T | U> { const safeFn = E.tryCatchK(fn, ensureError); const unchanged = () => this as ResultValue<T | U>; return pipe( this.value, O.fromNullable, O.map(safeFn), O.fold(unchanged, (v) => pipe...
/** * Transforms the contained value using the provided function. * If the value is undefined or null the function will not be called * and the result will be the same as the original. * This is useful if you want to apply somme modifications to the value * before rendering it, for example if n...
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/core/ResultValue.ts#L129-L150
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
ResultValue.bullets
get bullets() { return this.toBulletList(); }
/** * Convenient getter to get the value as bullets, so you don't need to call `toBulletList` manually. * example: * ```ts * result.getValue("myField").bullets; * ``` */
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/core/ResultValue.ts#L162-L164
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
ResultValue.upper
get upper(): ResultValue<unknown> { if (this.value instanceof FileProxy) { return new ResultValue(this.value.name.toLocaleUpperCase(), this.name, this.notify); } return this.map((v) => deepMap(v, (it) => (typeof it === "string" ? it.toLocaleUpperCase() : it)), ); ...
/** * getter that returns all the string values uppercased. * If the value is an array, it will return an array with all the strings uppercased. * The usage of map is important for safety and method chaining. */
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/core/ResultValue.ts#L171-L178
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
ResultValue.lower
get lower(): ResultValue<unknown> { if (this.value instanceof FileProxy) { return new ResultValue(this.value.name.toLocaleLowerCase(), this.name, this.notify); } return this.map((v) => deepMap(v, (it) => (typeof it === "string" ? it.toLocaleLowerCase() : it)), ); ...
/** * getter that returns all the string values lowercased. * If the value is an array, it will return an array with all the strings lowercased. * If the value is an object, it will return an object with all the string values lowercased. * The usage of map is important for safety and method chaining...
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/core/ResultValue.ts#L186-L193
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
ResultValue.trimmed
get trimmed(): ResultValue<unknown> { if (this.value instanceof FileProxy) { return new ResultValue(this.value.name.trim(), this.name, this.notify); } return this.map((v) => deepMap(v, (it) => (typeof it === "string" ? it.trim() : it))); }
/** * getter that returns all the string values trimmed. * */
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/core/ResultValue.ts#L197-L202
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
ResultValue.link
get link() { switch (true) { case typeof this.value === "string": return `[[${this.value}]]`; case this.value instanceof FileProxy: return `![[${this.value.path}]]`; default: return ""; } }
/** * renders the value as a markdown link. * If the value is a string, it will be rendered as a markdown link. * If the value is a FileProxy (right now just used for images), it will be rendered as an embedded link. * Any other type of value will be rendered as an empty string. */
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/core/ResultValue.ts#L210-L219
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
MigrationError.toJSON
toJSON() { return this.form; }
// This is required so we don't lose the form, even if it is invalid
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/core/formDefinitionSchema.ts#L106-L108
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
fromV0toV1
function fromV0toV1(data: FormDefinitionBasic): MigrationError | FormDefinitionV1 { return pipe( parse(FormDefinitionV1Schema, { ...data, version: "1" }), E.getOrElseW((error) => new MigrationError(data, error)), ); }
//=========== Migration logic
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/core/formDefinitionSchema.ts#L130-L135
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
FileProxy.constructor
constructor(private file: T) {}
/** * Creates a new FileProxy instance. * @param file - The TFile instance to wrap */
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/core/files/FileProxy.ts#L41-L41
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
FileProxy.path
get path(): string { return this.file.path; }
/** * Gets the full path of the file, including filename and extension. */
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/core/files/FileProxy.ts#L46-L48
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
FileProxy.name
get name(): string { return this.file.name; }
/** * Gets the complete filename with extension. */
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/core/files/FileProxy.ts#L53-L55
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
FileProxy.basename
get basename(): string { return this.file.basename; }
/** * Gets the filename without extension. */
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/core/files/FileProxy.ts#L60-L62
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
FileProxy.extension
get extension(): string { return this.file.extension; }
/** * Gets the file extension without the leading dot. */
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/core/files/FileProxy.ts#L67-L69
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
FileProxy.toJSON
toJSON(): SerializableFileData { return { path: this.path, name: this.name, basename: this.basename, extension: this.extension, }; }
/** * Converts the FileProxy instance to a plain object suitable for serialization. * This method is automatically called by JSON.stringify(). * * @returns A plain object containing the serializable file data */
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/core/files/FileProxy.ts#L81-L88
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
getFunctionBody
function getFunctionBody(fn: Function) { return fn .toString() .replace(/^[^{]*{/, "") .replace(/}[^}]*$/, "") .trim(); }
// eslint-disable-next-line @typescript-eslint/ban-types
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/core/templater/builder.ts#L11-L17
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
get_value
function get_value() { result.get("__key__") }
/** * This is just a dummy function to get type-checking * in the template strings we are generating. */
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/core/templater/builder.ts#L24-L26
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
requiredRule
function requiredRule(fieldName: string, message?: string): Rule { return { tag: "required", message: message ?? `'${fieldName}' is required` }; }
//| { tag: 'minLength', length: number, message: string } | { tag: 'maxLength', length: number, message: string } | { tag: 'pattern', pattern: RegExp, message: string };
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/store/formEngine.ts#L22-L24
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
parseField
function parseField<T extends FieldValue>(field: Field<T>): E.Either<FieldFailed<T>, Field<T>> { if (!field.rules) return E.right(field); const rule = field.rules; switch (rule.tag) { case "required": return pipe( field.value, O.chain(nonEmptyValue), ...
/** * * Validates a field based on the rules that are present on the field. * If the field meets the requirements, the field is returned as is in a right. * If the field does not meet the requirements, the field is returned with the errors in a left. */
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/store/formEngine.ts#L102-L118
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
parseForm
function parseForm<T extends FieldValue>( fields: Record<string, Field<T>>, ): E.Either<Field<T>[], Record<string, T>> { const { right: ok, left: failed } = pipe( fields, Object.values, A.map(parseField<T>), A.separate, ); if (failed.length > 0) return E.left(failed); ...
/** * Transforms a the fields of a form into a validated record of results, * or returns a list of fields that failed validation. */
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/store/formEngine.ts#L124-L147
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
setFormField
function setFormField({ name, input }: FieldDefinition) { /** * Initializes a field in the form store with the provided errors, rules * and default values (read from the defaultValues object passed to the form engine) */ function initField(errors = [], rules?: Rule) { ...
/** Creates helper functions to modify the store immutably*/
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/store/formEngine.ts#L166-L199
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
initField
function initField(errors = [], rules?: Rule) { formStore.update((form) => { return { ...form, fields: { ...form.fields, [name]: { value: O.fromNullable(defaultValues[name]), name, errors, rules }, ...
/** * Initializes a field in the form store with the provided errors, rules * and default values (read from the defaultValues object passed to the form engine) */
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/store/formEngine.ts#L171-L181
83e98e2dde1616cc074bf02271d6f49028c032d6
obsidian-modal-form
github_2023
danielo515
typescript
FileSuggest.renderSuggestion
renderSuggestion(file: TFile, el: HTMLElement): void { const text = this.strategy.renderSuggestion(file); el.addClasses(["mod-complex"]); const title = el.createDiv({ cls: "suggestion-title", text: text }); const subtitle = el.createDiv({ cls: "suggestion-note modal-form-sugg...
/* This is an example structure of how a obsidian suggestion looks like in the dom <div class="suggestion"> <div class="suggestion-item mod-complex is-selected"> <div class="suggestion-content"> <div class="suggestion-title"> <span class="s...
https://github.com/danielo515/obsidian-modal-form/blob/83e98e2dde1616cc074bf02271d6f49028c032d6/src/suggesters/suggestFile.ts#L73-L88
83e98e2dde1616cc074bf02271d6f49028c032d6
usemods
github_2023
littlefoxcompany
typescript
ensureCriteria
const ensureCriteria = (regex: RegExp, chars: string, count: number) => { while ((password.match(regex) || []).length < count) { const randomIndex = generateRandomIndex(password.length) password = password.substring(0, randomIndex) + chars.charAt(Math.floor(generateRandomIndex(chars.length))) + password...
// Ensure the password meets the criteria
https://github.com/littlefoxcompany/usemods/blob/a5ffc1d07a45049597b65da91d5c74e8477423ce/src/generators.ts#L70-L75
a5ffc1d07a45049597b65da91d5c74e8477423ce
usemods
github_2023
littlefoxcompany
typescript
stripTags
const stripTags = (str: string) => { return str .split('<') .map((part, index) => { if (index === 0) return part const closingBracket = part.indexOf('>') return closingBracket >= 0 ? part.slice(closingBracket + 1) : part }) .join('') }
// SSR Fallback (server-side)
https://github.com/littlefoxcompany/usemods/blob/a5ffc1d07a45049597b65da91d5c74e8477423ce/src/modifiers.ts#L143-L152
a5ffc1d07a45049597b65da91d5c74e8477423ce
spacetime-maps
github_2023
vvolhejn
typescript
getMercatorScaleFactor
const getMercatorScaleFactor = (lat: number) => { return 1 / Math.cos((lat * Math.PI) / 180); };
/** See backend for explanation */
https://github.com/vvolhejn/spacetime-maps/blob/df0431f20e467ab708d63ed42968cb04f2fe86a3/frontend/src/mesh.ts#L23-L25
df0431f20e467ab708d63ed42968cb04f2fe86a3
spacetime-maps
github_2023
vvolhejn
typescript
toRadians
const toRadians = (angle: number) => (angle * Math.PI) / 180;
// Convert latitude and longitude from degrees to radians
https://github.com/vvolhejn/spacetime-maps/blob/df0431f20e467ab708d63ed42968cb04f2fe86a3/frontend/src/springs.ts#L216-L216
df0431f20e467ab708d63ed42968cb04f2fe86a3
spacetime-maps
github_2023
vvolhejn
typescript
createMeshTriangles
const createMeshTriangles = ( vertexPositions: VertexPosition[], triangles: Float32Array[], flatUvs: Float32Array, mapSizePx: number, city: City ) => { let meshTriangles = triangles.map((triangle, i) => { const curVertices = new Float32Array([ vertexPositions[triangle[0]].x * mapSizePx, vert...
/** * Create a mesh of triangles from individual <SimpleMesh>es. * Originally, I had everything in one big <SimpleMesh>, but I ran into a bug where this * would break for larger mesh sizes: https://github.com/pixijs/pixijs/issues/9646 */
https://github.com/vvolhejn/spacetime-maps/blob/df0431f20e467ab708d63ed42968cb04f2fe86a3/frontend/src/components/SpacetimeMap.tsx#L19-L59
df0431f20e467ab708d63ed42968cb04f2fe86a3
TickTickSync
github_2023
thesamim
typescript
traverseDOMBackwards
function traverseDOMBackwards(element, callback) { while (element) { callback(element); element = element.previousElementSibling; } }
//This is here to try and find nested checkboxes, which I put on hold for now.
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/main.ts#L173-L179
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
TickTickSync.initializePlugin
async initializePlugin() { //initialize TickTick restapi this.tickTickRestAPI = new TickTickRestAPI(this.app, this, null); await this.tickTickRestAPI.initializeAPI(); //initialize data read and write object this.cacheOperation = new CacheOperation(this.app, this); let isProjectsSaved = false; if (this....
// return true of false
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/main.ts#L402-L491
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
TickTickSync.checkModuleClass
checkModuleClass() { if (this.settings.apiInitialized === true) { if (this.tickTickRestAPI === undefined || this.tickTickSyncAPI === undefined || this.cacheOperation === undefined || this.fileOperation === undefined || this.tickTickSync === undefined || this.taskParser === undefined) { this.initializeModuleCla...
//return true
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/main.ts#L636-L648
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
CacheOperation.removeTaskItem
async removeTaskItem(fileMetaData: FileMetadata, taskId: string, taskItemIds: string[]) { if (fileMetaData) { const taskIndex = fileMetaData.TickTickTasks.findIndex(task => task.taskId === taskId); if (taskIndex !== -1) { const updatedMetaDataTask = fileMetaData.TickTickT...
//assumes file metadata has been looked up.
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/cacheOperation.ts#L66-L90
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
CacheOperation.deleteFilepathFromMetadata
async deleteFilepathFromMetadata(filepath: string): Promise<FileMetadata> { const fileMetaData: FileMetadata = this.plugin.settings.fileMetadata; const newFileMetadata: FileMetadata = {}; for (const filename in fileMetaData) { if (filename !== filepath) { newFileMetadata[filename] = fileMetaData[filename]...
//delete filepath from filemetadata
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/cacheOperation.ts#L188-L203
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
CacheOperation.checkForDuplicates
checkForDuplicates(fileMetadata: FileMetadata) { let taskIds = {}; let duplicates = {}; if (!fileMetadata) { return; } for (const file in fileMetadata) { fileMetadata[file].TickTickTasks.forEach(task => { if (taskIds[task.taskId]) { if (!duplicates[task.taskId]) { duplicates[task.taskId]...
//Check for duplicates
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/cacheOperation.ts#L207-L228
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
CacheOperation.checkFileMetadata
async checkFileMetadata(): Promise<number> { const metadatas = await this.getFileMetadatas() // console.log("md: ", metadatas) for (const key in metadatas) { let filepath = key const value = metadatas[key]; // console.log("File: ", value) let file...
//Check errors in filemata where the filepath is incorrect.
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/cacheOperation.ts#L231-L280
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
CacheOperation.loadTasksFromCache
async loadTasksFromCache() { try { const savedTasks = this.plugin.settings.TickTickTasksData.tasks return savedTasks; } catch (error) { console.error(`Error loading tasks from Cache: ${error}`); return []; } }
//Read all tasks from Cache
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/cacheOperation.ts#L359-L367
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
CacheOperation.saveTasksToCache
async saveTasksToCache(newTasks) { try { this.plugin.settings.TickTickTasksData.tasks = newTasks } catch (error) { console.error(`Error saving tasks to Cache: ${error}`); return false; } }
// Overwrite and save all tasks to cache
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/cacheOperation.ts#L371-L379
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
CacheOperation.appendTaskToCache
async appendTaskToCache(task: ITask, filePath: string) { try { if (task === null) { return } const savedTasks = this.plugin.settings.TickTickTasksData.tasks if (!savedTasks) { this.plugin.settings.TickTickTasksData.tasks = []; ...
//Append to Cache file
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/cacheOperation.ts#L383-L402
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
CacheOperation.loadTaskFromCacheID
async loadTaskFromCacheID(taskId: string) : Promise<ITask|null> { // console.log("loadTaskFromCacheID") try { const savedTasks = this.plugin.settings.TickTickTasksData.tasks const savedTask = savedTasks.find((task: ITask) => task.id === taskId); return (savedTask) ...
//Read the task with the specified id
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/cacheOperation.ts#L405-L416
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
CacheOperation.getTaskTitles
async getTaskTitles(taskIds: string []): Promise<string []> { const savedTasks = this.plugin.settings.TickTickTasksData.tasks; let titles = savedTasks.filter(task => taskIds.includes(task.id)).map(task => task.title); titles = titles.map((task: string ) => { return this.plugin.taskParser?.stripOBSUrl(task); ...
//get Task titles
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/cacheOperation.ts#L419-L429
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
CacheOperation.updateTaskToCache
async updateTaskToCache(task: ITask, movedPath: string | null) { try { let filePath: string | null = "" if (!movedPath) { filePath = await this.getFilepathForTask(task.id) if (!filePath) { filePath = await this.getFilepathForProjectId(task.projectId); } if (!filePath) { //we're n...
//Overwrite the task with the specified id in update
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/cacheOperation.ts#L433-L459
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
CacheOperation.reopenTaskToCacheByID
async reopenTaskToCacheByID(taskId: string): Promise<string> { let projectId = null; try { const savedTasks = this.plugin.settings.TickTickTasksData.tasks const taskIndex = savedTasks.findIndex((task) => task.id === taskId); if (taskIndex > -1 ) { sa...
//open a task status
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/cacheOperation.ts#L517-L536
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
CacheOperation.closeTaskToCacheByID
async closeTaskToCacheByID(taskId: string): Promise<string> { let projectId = null; try { const savedTasks = this.plugin.settings.TickTickTasksData.tasks const taskIndex = savedTasks.findIndex((task) => task.id === taskId); if (taskIndex > -1) { save...
//close a task status
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/cacheOperation.ts#L541-L559
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
CacheOperation.deleteTaskFromCache
async deleteTaskFromCache(taskId: string) { try { const savedTasks = this.plugin.settings.TickTickTasksData.tasks const newSavedTasks = savedTasks.filter((t) => t.id !== taskId); this.plugin.settings.TickTickTasksData.tasks = newSavedTasks //Also clean up meta dat...
//Delete task by ID
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/cacheOperation.ts#L563-L573
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
CacheOperation.deleteTaskFromCacheByIDs
async deleteTaskFromCacheByIDs(deletedTaskIds: string[]) { try { const savedTasks = this.plugin.settings.TickTickTasksData.tasks const newSavedTasks = savedTasks.filter((t) => !deletedTaskIds.includes(t.id)) this.plugin.settings.TickTickTasksData.tasks = newSavedTasks ...
//Delete task through ID array
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/cacheOperation.ts#L577-L591
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
CacheOperation.getProjectIdByNameFromCache
async getProjectIdByNameFromCache(projectName: string) { try { const savedProjects = this.plugin.settings.TickTickTasksData.projects const targetProject = savedProjects.find((obj: IProject) => obj.name.toLowerCase() === projectName.toLowerCase()); const projectId = targetProj...
//Find project id by name
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/cacheOperation.ts#L595-L605
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
CacheOperation.saveProjectsToCache
async saveProjectsToCache() { try { //get projects // console.log(`Save Projects to cache with ${this.plugin.tickTickRestAPI}`) //const projectGroups = await this.plugin.tickTickRestAPI?.GetProjectGroups(); const projects: IProject[] = await this.plugin.tickTickRestAPI?.G...
//save projects data to json file
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/cacheOperation.ts#L624-L713
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
CacheOperation.findTaskInMetada
findTaskInMetada(taskId: string, filePath: string) { const fileMetadata = this.plugin.settings.fileMetadata; for (const file in fileMetadata) { console.log("in file: :", file) if (file == filePath) { console.log("breaking") continue; } const tasks = fileMetadata[file].TickTickTasks; for (cons...
// TODO: why did I think I needed this?
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/cacheOperation.ts#L745-L763
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
DateMan.parseDates
parseDates(inString: string): date_holder_type { // console.log('parseDates: ', inString); let myDateHolder = this.getEmptydateHolder(); //look for times at the beginning of the line and save them. const times_regex = '\\[\\s*(\\d{1,2}:\\d{2})(?:\\s*-\\s*(\\d{1,2}:\\d{2}))?\\s*\\]'; const regEx = new RegExp...
/* input: a task string output: a dateholer struct Called when a task is being examined for changes, or ready for update. (Called from convertLineToTask.) */
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/dateMan.ts#L61-L120
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
DateMan.addDatesToLine
addDatesToLine(inString: string, task: ITask, direction: string | null): string { // console.log('TRACETHIS Direction: ', direction, 'addDatesToLine - in :', inString, 'and the task DH is: ', task.dateHolder); let dateStrings: string[] = []; let startDatetimeString: string = ''; let dueDatetimeString: string = ...
//Assume that dateholder is populated by the time we get here.
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/dateMan.ts#L130-L195
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
DateMan.stripDatesFromLine
stripDatesFromLine(inString: string): string | null { let retString; // console.log('stripDatesFromLine - in :', inString); let datesRegEx = /[➕⏳🛫📅✅❌]\s(\d{4}-\d{2}-\d{2})(\s\d{1,}:\d{2})?/gus; retString = inString.replace(datesRegEx, ''); // console.log('stripDatesFromLine - dates :', retString); const t...
// and also get the times right.
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/dateMan.ts#L199-L209
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
DateMan.areDatesChanged
areDatesChanged(lineTask: ITask, TickTickTask: ITask): boolean { //we're going to be bold and assume that both tasks have dateHolders. const editedTaskDates = lineTask.dateHolder; const cachedTaskDates = TickTickTask.dateHolder; if (!editedTaskDates) { // console.error('TRACETHIS edited Task has no dateholde...
//Check all Dates
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/dateMan.ts#L261-L328
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
DateMan.formatDateToISO
formatDateToISO(dateTime: Date) { // Check if the input is a valid date if (isNaN(dateTime.getTime())) { return 'Invalid Date'; } const tzoffset = dateTime.getTimezoneOffset(); const convertedDate = new Date(dateTime.getTime()); return convertedDate.toISOString().replace(/Z$/, '+0000'); }
//Format date to TickTick Accepted date.
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/dateMan.ts#L331-L339
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
FileOperation.completeTaskInTheFile
async completeTaskInTheFile(taskId: string) { // Get the task file path const currentTask = await this.plugin.cacheOperation?.loadTaskFromCacheID(taskId) const filepath = await this.plugin.cacheOperation?.getFilepathForTask(taskId) // Get the file object and update the content c...
//Complete a task and mark it as completed
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/fileOperation.ts#L22-L48
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
FileOperation.uncompleteTaskInTheFile
async uncompleteTaskInTheFile(taskId: string) { // Get the task file path const currentTask = await this.plugin.cacheOperation?.loadTaskFromCacheID(taskId) const filepath = await this.plugin.cacheOperation?.getFilepathForTask(taskId) // Get the file object and update the content ...
// uncheck completed tasks,
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/fileOperation.ts#L51-L77
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
FileOperation.addTickTickTagToFile
async addTickTickTagToFile(filepath: string) { // console.log("addTickTickTagToFile") // Get the file object and update the content const file = this.app.vault.getAbstractFileByPath(filepath) if ((file) && (file instanceof TFolder)) { //leave folders alone. return; } const con...
//add #TickTick at the end of task line, if full vault sync enabled
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/fileOperation.ts#L80-L125
a094e6542e42ecf8a6a48e537ac94928648a282a
TickTickSync
github_2023
thesamim
typescript
FileOperation.addTickTickLinkToFile
async addTickTickLinkToFile(filepath: string) { // Get the file object and update the content const file = this.app.vault.getAbstractFileByPath(filepath) if ((file) && (file instanceof TFolder)) { //leave folders alone. return; } const content = await this.app.vault.read(file) ...
//add TickTick at the line
https://github.com/thesamim/TickTickSync/blob/a094e6542e42ecf8a6a48e537ac94928648a282a/src/fileOperation.ts#L130-L170
a094e6542e42ecf8a6a48e537ac94928648a282a