svelte/store#get TypeScript Examples

The following examples show how to use svelte/store#get. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
private autoSyncInterval(): void {
    new Setting(this.containerEl)
    .setName('Auto sync in interval (minutes)')
    .setDesc('Sync every X minutes. To disable auto sync, specify negative value or zero (default)')
    .addText((text) => {
      text
        .setPlaceholder(String(0))
        .setValue(String(get(settingsStore).autoSyncInterval))
        .onChange(async (value) => {
          if (!isNaN(Number(value))) {
            const minutes = Number(value);
            await settingsStore.actions.setAutoSyncInterval(minutes);
            const autoSyncInterval = get(settingsStore).autoSyncInterval;
            console.log(autoSyncInterval);
            if (autoSyncInterval > 0) {
              this.plugin.clearAutoSync();
              this.plugin.startAutoSync(minutes);
              console.log(
                  `Auto sync enabled! Every ${minutes} minutes.`
              );
            } else if (autoSyncInterval <= 0) {
              this.plugin.clearAutoSync() && console.log("Auto sync disabled!");
            }
          }
        });
    });
  }
Example #2
Source File: validatorsAction.ts    From svelte-use-form with MIT License 6 votes vote down vote up
/**
 * Add validators to form control
 * ``` svelte
 * <input name="nameOfInput" use:validators={[required, minLength(5), maxLength(20)]} />
 * ```
 */
export function validators(node: FormMember, validators: Validator[]) {
  setupValidation();

  async function setupValidation() {
    const formElement = node.form;
    await tick();
    const formReference = get(formReferences).find(
      (form) => form.node === formElement
    );

    const formControl = formReference.form[node.name];
    formControl.validators.push(...validators);
    formControl.validate();
    formReference.notifyListeners();
  }
}
Example #3
Source File: fileManager.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
articleFolderPath = (article: Article): string => {
  const settings = get(settingsStore);
  if (settings.useDomainFolders) {
    // "metadata.author" is equal to the article domain at the moment
    return `${settings.highlightsFolder}/${article.metadata.author}`;
  }

  return settings.highlightsFolder;
}
Example #4
Source File: main.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
async startAutoSync(minutes?: number): Promise<void> {
		const minutesToSync = minutes ?? Number(get(settingsStore).autoSyncInterval);
		if (minutesToSync > 0) {
			this.timeoutIDAutoSync = window.setTimeout(
				() => {
					this.startSync();
					this.startAutoSync();
				},
				minutesToSync * 60000
			);
		}
		console.log(`StartAutoSync: this.timeoutIDAutoSync ${this.timeoutIDAutoSync} with ${minutesToSync} minutes`);
	}
Example #5
Source File: manageGroupsModal.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
async onOpen() {
        super.onOpen()
        const groups = get(settingsStore).groups;

        this.titleEl.innerText = "Hypothes.is: Manage groups to be synced";

        this.modalContent = new ManageGroupsModalContent({
            target: this.contentEl,
            props: {
                groups: groups,
                onSubmit: async (value: { selectedGroups }) => {
                    this.setGroupsSettings(value.selectedGroups);
                    this.close();
                },
            },
        });

    }
Example #6
Source File: manageGroupsModal.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
async setGroupsSettings(selectedGroups) {

        const groups = get(settingsStore).groups;

        groups.forEach(group => {
            group.selected = selectedGroups.some((selectedGroup) => selectedGroup.id === group.id);
        })

        await settingsStore.actions.setGroups(groups);

    }
Example #7
Source File: resyncDelFileModal.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
async retrieveDeletedFiles(): Promise<SyncedFile[]> {
        const token = get(settingsStore).token;
        const userid = get(settingsStore).user;
        const apiManager = new ApiManager(token, userid);

        // Fetch all annotated articles that *should* be present
        const allAnnotations = await apiManager.getHighlights()
        const allArticles: [] = Object.values(await parseSyncResponse(allAnnotations));

        // Check which files are actually present
        const deletedArticles = await Promise.all(allArticles.filter(async article => !(await this.fileManager.isArticleSaved(article))));
        return deletedArticles.map((article: Article) => 
            ({ uri: article.metadata.url, filename: this.fileManager.getNewArticleFilePath(article)})
        );
    }
Example #8
Source File: renderer.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
render(entry: Article, isNew = true): string {
    const { metadata , highlights, page_notes } = entry;

    const context: RenderTemplate = {
       is_new_article: isNew,
       ...metadata,
       highlights,
       page_notes,
    };

    const template = get(settingsStore).template;
    const content = nunjucks.renderString(template, context);
    return content;
  }
Example #9
Source File: index.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
public async display(): Promise<void> {
    const { containerEl } = this;

    containerEl.empty();

    if (get(settingsStore).isConnected) {
      this.disconnect();
    } else {
      this.connect();
    }
    this.autoSyncInterval();
    this.highlightsFolder();
    this.folderPath();
    this.syncOnBoot();
    this.dateFormat();
    this.template();
    this.manageGroups();
    this.resetSyncHistory();
  }
Example #10
Source File: index.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
private disconnect(): void {
    const syncMessage = get(settingsStore).lastSyncDate
      ? `Last sync ${moment(get(settingsStore).lastSyncDate).fromNow()}`
      : 'Sync has never run';

    const descFragment = document.createRange().createContextualFragment(`
      ${get(settingsStore).history.totalArticles} article(s) & ${get(settingsStore).history.totalHighlights} highlight(s) synced<br/>
      ${syncMessage}
    `);

    new Setting(this.containerEl)
      .setName(`Connected to Hypothes.is as ${(get(settingsStore).user).match(/([^:]+)@/)[1]}`)
      .setDesc(descFragment)
      .addButton((button) => {
        return button
          .setButtonText('Disconnect')
          .setCta()
          .onClick(async () => {
            button
              .removeCta()
              .setButtonText('Removing API token...')
              .setDisabled(true);

            await settingsStore.actions.disconnect();

            this.display(); // rerender
          });
      });
  }
Example #11
Source File: hash-router.ts    From svelte-router with MIT License 6 votes vote down vote up
replaceParams(to: LocationInput, params?: Record<string, string>) {
    const newTo = { ...to }
    const routeParams = params ?? get(this.currentRoute).params

    if (newTo.path) {
      newTo.path = replacePathParams(newTo.path, routeParams)
    }

    if (newTo.hash) {
      newTo.hash = replacePathParams(newTo.hash, routeParams)
    }

    return newTo
  }
Example #12
Source File: index.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
private highlightsFolder(): void {
    new Setting(this.containerEl)
      .setName('Highlights folder location')
      .setDesc('Vault folder to use for writing hypothesis highlights')
      .addDropdown((dropdown) => {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const files = (this.app.vault.adapter as any).files;
        const folders = pickBy(files, (val) => {
          return val.type === 'folder';
        });

        Object.keys(folders).forEach((val) => {
          dropdown.addOption(val, val);
        });
        return dropdown
          .setValue(get(settingsStore).highlightsFolder)
          .onChange(async (value) => {
            await settingsStore.actions.setHighlightsFolder(value);
          });
      });
  }
Example #13
Source File: index.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
private template(): void {

    const descFragment = document
      .createRange()
      .createContextualFragment(templateInstructions);

    new Setting(this.containerEl)
      .setName('Highlights template')
      .setDesc(descFragment)
      .addTextArea((text) => {
        text.inputEl.style.width = '100%';
        text.inputEl.style.height = '450px';
        text.inputEl.style.fontSize = '0.8em';
        text
          .setValue(get(settingsStore).template)
          .onChange(async (value) => {
            const isValid = this.renderer.validate(value);

            if (isValid) {
              await settingsStore.actions.setTemplate(value);
            }

            text.inputEl.style.border = isValid ? '' : '1px solid red';
          });
        return text;
      });
  }
Example #14
Source File: index.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
private folderPath(): void {
    new Setting(this.containerEl)
    .setName('Use domain folders')
    .setDesc('Group generated files into folders based on the domain of the annotated URL')
    .addToggle((toggle) =>
      toggle
        .setValue(get(settingsStore).useDomainFolders)
        .onChange(async (value) => {
          await settingsStore.actions.setUseDomainFolder(value);
        })
    );
  }
Example #15
Source File: index.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
private syncOnBoot(): void {
    new Setting(this.containerEl)
      .setName('Sync on Startup')
      .setDesc(
        'Automatically sync new highlights when Obsidian starts'
      )
      .addToggle((toggle) =>
        toggle
          .setValue(get(settingsStore).syncOnBoot)
          .onChange(async (value) => {
            await settingsStore.actions.setSyncOnBoot(value);
          })
      );
  }
Example #16
Source File: index.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
private resetSyncHistory(): void {
    new Setting(this.containerEl)
      .setName('Reset sync')
      .setDesc('Wipe sync history to allow for resync')
      .addButton((button) => {
        return button
          .setButtonText('Reset')
          .setDisabled(!get(settingsStore).isConnected)
          .setWarning()
          .onClick(async () => {
            await settingsStore.actions.resetSyncHistory();
            this.display(); // rerender
          });
      });
  }
Example #17
Source File: index.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
private dateFormat(): void {
    const descFragment = document
      .createRange()
      .createContextualFragment(datetimeInstructions);

    new Setting(this.containerEl)
      .setName('Date & time format')
      .setDesc(descFragment)
      .addText((text) => {
        text
          .setPlaceholder('YYYY-MM-DD HH:mm:ss')
          .setValue(get(settingsStore).dateTimeFormat)
          .onChange(async (value) => {
            await settingsStore.actions.setDateTimeFormat(value);
          });
      });
  }
Example #18
Source File: index.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
private async manageGroups(): Promise<void> {
    const descFragment = document.createRange().createContextualFragment(`Add/remove group(s) to be synced.<br/>
      ${(get(settingsStore).groups).length} group(s) synced from Hypothesis<br/>`);

    new Setting(this.containerEl)
      .setName('Groups')
      .setDesc(descFragment)
      .addExtraButton((button) => {
        return button
          .setIcon('switch')
          .setTooltip('Reset group selections')
          .setDisabled(!get(settingsStore).isConnected)
          .onClick(async () => {
            await settingsStore.actions.resetGroups();
            await this.syncGroup.startSync();
            this.display(); // rerender
          });
      })
      .addButton((button) => {
        return button
          .setButtonText('Manage')
          .setCta()
          .setDisabled(!get(settingsStore).isConnected)
          .onClick(async () => {
            const manageGroupsModal = new ManageGroupsModal(this.app);
            await manageGroupsModal.waitForClose;
            this.display(); // rerender
          });
      });
  }
Example #19
Source File: syncGroup.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
async startSync() {

        const token = await get(settingsStore).token;
        const userid = await get(settingsStore).user;

        const apiManager = new ApiManager(token, userid);

        const responseBody: [] = await apiManager.getGroups();

        const fetchedGroups = await parseGroupsResponse(responseBody);

        const currentGroups = await get(settingsStore).groups;

        const mergedGroups = [...currentGroups, ...fetchedGroups];
        const set = new Set();

        const unionGroups = mergedGroups.filter(item => {
            if (!set.has(item.id)) {
                set.add(item.id);
                return true;
            }
            return false;
        }, set);

        await settingsStore.actions.setGroups(unionGroups);
    }
Example #20
Source File: syncHypothesis.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
async startSync(uri?: string) {
        this.syncState = { newArticlesSynced: 0, newHighlightsSynced: 0 };

        const token = await get(settingsStore).token;
        const userid = await get(settingsStore).user;

        const apiManager = new ApiManager(token, userid);

        syncSessionStore.actions.startSync();

        //fetch groups
        await this.syncGroup.startSync();

        //fetch highlights
        const responseBody: [] = (!uri) ? await apiManager.getHighlights(get(settingsStore).lastSyncDate) : await apiManager.getHighlightWithUri(uri);
        const articles = await parseSyncResponse(responseBody);

        syncSessionStore.actions.setJobs(articles);

        if (articles.length > 0) {
            await this.syncArticles(articles);
        }

        syncSessionStore.actions.completeSync({
            newArticlesCount: this.syncState.newArticlesSynced,
            newHighlightsCount: this.syncState.newHighlightsSynced,
            updatedArticlesCount: 0,
            updatedHighlightsCount: 0,
        });
    }
Example #21
Source File: tasks.ts    From obsidian-calendar-plugin with MIT License 6 votes vote down vote up
tasksSource: ICalendarSource = {
  getDailyMetadata: async (date: Moment): Promise<IDayMetadata> => {
    const file = getDailyNote(date, get(dailyNotes));
    const dots = await getDotsForDailyNote(file);
    return {
      dots,
    };
  },

  getWeeklyMetadata: async (date: Moment): Promise<IDayMetadata> => {
    const file = getWeeklyNote(date, get(weeklyNotes));
    const dots = await getDotsForDailyNote(file);

    return {
      dots,
    };
  },
}
Example #22
Source File: pre-init-usage.spec.ts    From svelte-router with MIT License 6 votes vote down vote up
describe('API access before router initialization', function () {
  it('should have a default route store value', function () {
    const $route = get(route)
    expect(typeof $route === 'object').toBe(true)
  })

  it('should throw error if navigate', function () {
    expect(() => navigate(0)).toThrow()
  })

  it('should throw error if createLink', function () {
    expect(() => createLink({})).toThrow()
  })
})
Example #23
Source File: path-router.ts    From svelte-router with MIT License 6 votes vote down vote up
replaceParams(to: LocationInput, params?: Record<string, string>) {
    const newTo = { ...to }
    const routeParams = params ?? get(this.currentRoute).params

    if (newTo.path) {
      newTo.path = replacePathParams(newTo.path, routeParams)
    }

    return newTo
  }
Example #24
Source File: streak.ts    From obsidian-calendar-plugin with MIT License 6 votes vote down vote up
streakSource: ICalendarSource = {
  getDailyMetadata: async (date: Moment): Promise<IDayMetadata> => {
    const file = getDailyNote(date, get(dailyNotes));
    return {
      classes: getStreakClasses(file),
      dots: [],
    };
  },

  getWeeklyMetadata: async (date: Moment): Promise<IDayMetadata> => {
    const file = getWeeklyNote(date, get(weeklyNotes));
    return {
      classes: getStreakClasses(file),
      dots: [],
    };
  },
}
Example #25
Source File: tags.ts    From obsidian-calendar-plugin with MIT License 6 votes vote down vote up
customTagsSource: ICalendarSource = {
  getDailyMetadata: async (date: Moment): Promise<IDayMetadata> => {
    const file = getDailyNote(date, get(dailyNotes));
    return {
      dataAttributes: getFormattedTagAttributes(file),
      dots: [],
    };
  },
  getWeeklyMetadata: async (date: Moment): Promise<IDayMetadata> => {
    const file = getWeeklyNote(date, get(weeklyNotes));
    return {
      dataAttributes: getFormattedTagAttributes(file),
      dots: [],
    };
  },
}
Example #26
Source File: view.ts    From obsidian-calendar-plugin with MIT License 6 votes vote down vote up
async openOrCreateDailyNote(
    date: Moment,
    inNewSplit: boolean
  ): Promise<void> {
    const { workspace } = this.app;
    const existingFile = getDailyNote(date, get(dailyNotes));
    if (!existingFile) {
      // File doesn't exist
      tryToCreateDailyNote(
        date,
        inNewSplit,
        this.settings,
        (dailyNote: TFile) => {
          activeFile.setFile(dailyNote);
        }
      );
      return;
    }

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const mode = (this.app.vault as any).getConfig("defaultViewMode");
    const leaf = inNewSplit
      ? workspace.splitActiveLeaf()
      : workspace.getUnpinnedLeaf();
    await leaf.openFile(existingFile, { active : true, mode });

    activeFile.setFile(existingFile);
  }
Example #27
Source File: wordCount.ts    From obsidian-calendar-plugin with MIT License 6 votes vote down vote up
export async function getWordLengthAsDots(note: TFile): Promise<number> {
  const { wordsPerDot = DEFAULT_WORDS_PER_DOT } = get(settings);
  if (!note || wordsPerDot <= 0) {
    return 0;
  }
  const fileContents = await window.app.vault.cachedRead(note);

  const wordCount = getWordCount(fileContents);
  const numDots = wordCount / wordsPerDot;
  return clamp(Math.floor(numDots), 1, NUM_MAX_DOTS);
}
Example #28
Source File: wordCount.ts    From obsidian-calendar-plugin with MIT License 6 votes vote down vote up
wordCountSource: ICalendarSource = {
  getDailyMetadata: async (date: Moment): Promise<IDayMetadata> => {
    const file = getDailyNote(date, get(dailyNotes));
    const dots = await getDotsForDailyNote(file);
    return {
      dots,
    };
  },

  getWeeklyMetadata: async (date: Moment): Promise<IDayMetadata> => {
    const file = getWeeklyNote(date, get(weeklyNotes));
    const dots = await getDotsForDailyNote(file);

    return {
      dots,
    };
  },
}
Example #29
Source File: view.ts    From obsidian-calendar-plugin with MIT License 6 votes vote down vote up
onHoverDay(
    date: Moment,
    targetEl: EventTarget,
    isMetaPressed: boolean
  ): void {
    if (!isMetaPressed) {
      return;
    }
    const { format } = getDailyNoteSettings();
    const note = getDailyNote(date, get(dailyNotes));
    this.app.workspace.trigger(
      "link-hover",
      this,
      targetEl,
      date.format(format),
      note?.path
    );
  }