A fully open source & end-to-end encrypted note taking alternative to Evernote.
TypeScript asp-net-coredotnet-coreelectronfosshacktoberfestnote-managmentnote-takingnote-taking-appnotebooknotesnotes-appopen-sourceopensourceprivacyproductivityreactreact-nativereactjsself-hosted
feat: improve word count
thecodrr9e5f8b3ee4d0
diff --git a/apps/web/src/components/editor/context.ts b/apps/web/src/components/editor/context.tsindex 1e0b17ca0..c06789963 100644--- a/apps/web/src/components/editor/context.ts+++ b/apps/web/src/components/editor/context.ts@@ -1,5 +1,5 @@import { useCallback } from "react";-import { IEditor } from "./types";+import { IEditor, NoteStatistics } from "./types";import createStore from "../../common/store";import BaseStore from "../../stores";import { UseStore } from "zustand";@@ -12,13 +12,20 @@ type EditorSubState = {canRedo?: boolean;searching?: boolean;toolbarConfig?: ToolbarDefinition;+ statistics?: NoteStatistics;};class EditorContext extends BaseStore {subState: EditorSubState = {};- configure = (partial: Partial<EditorSubState>) => {+ configure = (+ partial:+ | Partial<EditorSubState>+ | ((oldState: EditorSubState) => Partial<EditorSubState>)+ ) => {this.set((state: EditorContext) => {- state.subState = { ...state.subState, ...partial };+ const newPartialState =+ typeof partial === "function" ? partial(state.subState) : partial;+ state.subState = { ...state.subState, ...newPartialState };});};}@@ -70,3 +77,12 @@ export function useToolbarConfig() {);return { toolbarConfig, setToolbarConfig };}++export function useNoteStatistics(): NoteStatistics {+ return useEditorContext(+ (store) =>+ store.subState.statistics || {+ words: { total: 0 },+ }+ );+}diff --git a/apps/web/src/components/editor/footer.js b/apps/web/src/components/editor/footer.jsindex b7b075233..d0644b829 100644--- a/apps/web/src/components/editor/footer.js+++ b/apps/web/src/components/editor/footer.js@@ -1,9 +1,8 @@import { formatDate } from "notes-core/utils/date";-import { useEffect, useState } from "react";import { Flex, Text } from "rebass";-import { AppEventManager, AppEvents } from "../../common/app-events";import { useStore } from "../../stores/editor-store";import { Loading, Saved, NotSaved } from "../icons";+import { useNoteStatistics } from "./context";const SAVE_STATE_ICON_MAP = {"-1": NotSaved,@@ -12,23 +11,13 @@ const SAVE_STATE_ICON_MAP = {};function EditorFooter() {- const [totalWords, setTotalWords] = useState(0);+ const { words } = useNoteStatistics();const dateEdited = useStore((store) => store.session.dateEdited);const id = useStore((store) => store.session.id);const SaveStateIcon = useStore((store) => SAVE_STATE_ICON_MAP[store.session.saveState]);- useEffect(() => {- const updateWordCountEvent = AppEventManager.subscribe(- AppEvents.UPDATE_WORD_COUNT,- (count) => setTotalWords(count)- );- return () => {- updateWordCountEvent.unsubscribe();- };- }, []);-if (!id) return null;return (<Flex alignItems="center">@@ -39,7 +28,8 @@ function EditorFooter() {color="bgSecondaryText"mr={2}>- {totalWords + " words"}+ {words.total + " words"}+ {words.selected ? ` (${words.selected} selected)` : ""}</Text><TextclassName="selectable"diff --git a/apps/web/src/components/editor/index.tsx b/apps/web/src/components/editor/index.tsxindex a49180967..725674b46 100644--- a/apps/web/src/components/editor/index.tsx+++ b/apps/web/src/components/editor/index.tsx@@ -216,10 +216,9 @@ export function Editor(props: EditorProps) {readonly={readonly}toolbarContainerId={headless ? undefined : "editorToolbar"}content={content}- onChange={(content, counter) => {+ onChange={(content) => {const { id, sessionId } = editorstore.get().session;debouncedOnEditorChange(sessionId, id, sessionId, content);- if (counter) debouncedUpdateWordCount(counter);}}onDownloadAttachment={(attachment) =>downloadAttachment(attachment.hash)diff --git a/apps/web/src/components/editor/tiptap.tsx b/apps/web/src/components/editor/tiptap.tsxindex bef4cc440..1d8bc5ee0 100644--- a/apps/web/src/components/editor/tiptap.tsx+++ b/apps/web/src/components/editor/tiptap.tsx@@ -15,7 +15,7 @@ import { Box, Flex } from "rebass";import { PropsWithChildren, useEffect, useRef, useState } from "react";import useMobile from "../../utils/use-mobile";import { Attachment } from "./picker";-import { CharacterCounter, IEditor } from "./types";+import { IEditor } from "./types";import { useConfigureEditor, useSearch, useToolbarConfig } from "./context";import { createPortal } from "react-dom";import { getCurrentPreset } from "../../common/toolbar-config";@@ -24,7 +24,7 @@ import { showBuyDialog } from "../../common/dialog-controller";type TipTapProps = {editorContainer: HTMLElement;- onChange?: (content: string, counter?: CharacterCounter) => void;+ onChange?: (content: string) => void;onInsertAttachment?: (type: AttachmentType) => void;onDownloadAttachment?: (attachment: Attachment) => void;onFocus?: () => void;@@ -50,7 +50,6 @@ function TipTap(props: TipTapProps) {const theme: Theme = useTheme();const isUserPremium = useIsUserPremium();const isMobile = useMobile();- const counter = useRef<CharacterCounter>();const configure = useConfigureEditor();const { toolbarConfig } = useToolbarConfig();const { isSearching, toggleSearch } = useSearch();@@ -73,17 +72,29 @@ function TipTap(props: TipTapProps) {autofocus: "start",onFocus,onCreate: ({ editor }) => {- counter.current = editor.storage.characterCount as CharacterCounter;configure({editor: toIEditor(editor as Editor),canRedo: editor.can().redo(),canUndo: editor.can().undo(),toolbarConfig: getCurrentPreset().tools,+ statistics: {+ words: {+ total: getTotalWords(editor as Editor),+ selected: 0,+ },+ },});},onUpdate: ({ editor }) => {- if (onChange && editor.isEditable)- onChange(editor.getHTML(), counter.current);+ if (onChange && editor.isEditable) onChange(editor.getHTML());+ configure({+ statistics: {+ words: {+ total: getTotalWords(editor as Editor),+ selected: 0,+ },+ },+ });},onDestroy: () => {configure({@@ -91,6 +102,7 @@ function TipTap(props: TipTapProps) {canRedo: false,canUndo: false,searching: false,+ statistics: undefined,});},onTransaction: ({ editor }) => {@@ -99,6 +111,20 @@ function TipTap(props: TipTapProps) {canUndo: editor.can().undo(),});},+ onSelectionUpdate: ({ editor, transaction }) => {+ configure((old) => ({+ statistics: {+ words: {+ total:+ old.statistics?.words.total || getTotalWords(editor as Editor),+ selected: getSelectedWords(+ editor as Editor,+ transaction.selection+ ),+ },+ },+ }));+ },theme,onOpenAttachmentPicker: (_editor, type) => {onInsertAttachment?.(type);@@ -196,3 +222,50 @@ function toIEditor(editor: Editor): IEditor {}),};}++function getTotalWords(editor: Editor): number {+ const documentText = editor.state.doc.textBetween(+ 0,+ editor.state.doc.content.size,+ "\n",+ " "+ );+ return countWords(documentText);+}++function getSelectedWords(+ editor: Editor,+ selection: { from: number; to: number; empty: boolean }+): number {+ const selectedText = selection.empty+ ? ""+ : editor.state.doc.textBetween(selection.from, selection.to, "\n", " ");+ return countWords(selectedText);+}++function countWords(str: string) {+ let count = 0;+ let shouldCount = false;++ for (var i = 0; i < str.length; ++i) {+ const s = str[i];++ if (+ s === " " ||+ s === "\r" ||+ s === "\n" ||+ s === "*" ||+ s === "/" ||+ s === "&"+ ) {+ if (!shouldCount) continue;+ ++count;+ shouldCount = false;+ } else {+ shouldCount = true;+ }+ }++ if (shouldCount) ++count;+ return count;+}diff --git a/apps/web/src/components/editor/types.ts b/apps/web/src/components/editor/types.tsindex 94969c8e2..3df958cdf 100644--- a/apps/web/src/components/editor/types.ts+++ b/apps/web/src/components/editor/types.ts@@ -1,8 +1,10 @@import { Attachment } from "./picker";-export type CharacterCounter = {- words: () => number;- characters: () => number;+export type NoteStatistics = {+ words: {+ total: number;+ selected?: number;+ };};export interface IEditor {