Просмотр исходного кода

Merge remote-tracking branch 'origin/master' into dev/5.0.x

Yuki Takei 4 лет назад
Родитель
Сommit
5a11e31b4c
28 измененных файлов с 1083 добавлено и 876 удалено
  1. 4 4
      packages/app/package.json
  2. 4 0
      packages/app/src/client/app.jsx
  3. 3 0
      packages/app/src/client/interfaces/focusable.ts
  4. 13 0
      packages/app/src/client/interfaces/react-bootstrap-typeahead.ts
  5. 12 6
      packages/app/src/client/services/ContextExtractor.tsx
  6. 1 0
      packages/app/src/client/services/PageContainer.js
  7. 47 0
      packages/app/src/client/util/codemirror/drawio-fold.ext.js
  8. 16 1
      packages/app/src/client/util/interceptor/drawio-interceptor.js
  9. 25 3
      packages/app/src/components/Navbar/AuthorInfo.jsx
  10. 0 108
      packages/app/src/components/Navbar/GlobalSearch.jsx
  11. 97 0
      packages/app/src/components/Navbar/GlobalSearch.tsx
  12. 4 3
      packages/app/src/components/Navbar/GrowiSubNavigation.jsx
  13. 3 1
      packages/app/src/components/Page/TrashPageAlert.jsx
  14. 7 2
      packages/app/src/components/PageContentFooter.jsx
  15. 27 1
      packages/app/src/components/PageEditor/CodeMirrorEditor.jsx
  16. 16 0
      packages/app/src/components/PageEditor/MarkdownDrawioUtil.js
  17. 36 0
      packages/app/src/components/PageEditor/OptionsSelector.jsx
  18. 0 178
      packages/app/src/components/SearchForm.jsx
  19. 141 0
      packages/app/src/components/SearchForm.tsx
  20. 4 0
      packages/app/src/components/SearchPage/SearchPageForm.jsx
  21. 0 274
      packages/app/src/components/SearchTypeahead.jsx
  22. 250 0
      packages/app/src/components/SearchTypeahead.tsx
  23. 12 0
      packages/app/src/interfaces/search.ts
  24. 4 16
      packages/app/src/server/service/search.ts
  25. 2 2
      packages/app/src/server/views/widget/page_content.html
  26. 4 4
      packages/app/src/stores/context.tsx
  27. 2 1
      packages/app/src/styles/_sidebar.scss
  28. 349 272
      yarn.lock

+ 4 - 4
packages/app/package.json

@@ -103,7 +103,7 @@
     "http-errors": "~1.8.0",
     "i18next": "^20.3.2",
     "i18next-express-middleware": "^2.0.0",
-    "i18next-node-fs-backend": "^2.1.0",
+    "i18next-node-fs-backend": "^2.1.3",
     "i18next-sprintf-postprocessor": "^0.2.2",
     "is-iso-date": "^0.0.1",
     "lucene-query-parser": "^1.2.0",
@@ -156,7 +156,7 @@
     "ts-loader": "v9 is not compatible with webpack@5"
   },
   "devDependencies": {
-    "@alienfast/i18next-loader": "^1.0.16",
+    "@alienfast/i18next-loader": "^1.1.4",
     "@growi/ui": "^5.0.0-RC.0",
     "@handsontable/react": "=2.1.0",
     "@types/compression": "^1.7.0",
@@ -176,7 +176,7 @@
     "css-loader": "^3.0.0",
     "csv-to-markdown-table": "^1.0.1",
     "diff2html": "^3.1.2",
-    "eazy-logger": "^3.0.2",
+    "eazy-logger": "^3.1.0",
     "file-loader": "^5.0.2",
     "handsontable": "=6.2.2",
     "hard-source-webpack-plugin": "^0.13.1",
@@ -244,7 +244,7 @@
     "unstated": "^2.1.1",
     "webpack": "^4.39.3",
     "webpack-assets-manifest": "^3.1.1",
-    "webpack-bundle-analyzer": "^3.0.2",
+    "webpack-bundle-analyzer": "^3.9.0",
     "webpack-cli": "^3.3.7",
     "webpack-merge": "^4.2.2"
   }

+ 4 - 0
packages/app/src/client/app.jsx

@@ -96,6 +96,10 @@ Object.assign(componentMappings, {
   'trash-page-list': <TrashPageList />,
 
   'not-found-page': <NotFoundPage />,
+  'not-found-alert': <NotFoundAlert
+    isGuestUserMode={appContainer.isGuestUser}
+    isHidden={pageContainer.state.pageId != null ? (pageContainer.state.isNotCreatable ?? pageContainer.state.isTrashPage) : false} // !!DO NOT MOVE THIS!! https://github.com/weseek/growi/pull/4899
+  />,
 
   'forbidden-page': <ForbiddenPage />,
 

+ 3 - 0
packages/app/src/client/interfaces/focusable.ts

@@ -0,0 +1,3 @@
+export interface IFocusable {
+  focus: () => void,
+}

+ 13 - 0
packages/app/src/client/interfaces/react-bootstrap-typeahead.ts

@@ -0,0 +1,13 @@
+// https://github.com/ericgio/react-bootstrap-typeahead/blob/3.x/docs/Props.md
+export type TypeaheadProps = {
+  dropup?: boolean,
+  emptyLabel?: string,
+  placeholder?: string,
+  autoFocus?: boolean,
+
+  onChange?: (data: unknown[]) => void,
+  onBlur?: () => void,
+  onFocus?: () => void,
+  onInputChange?: (text: string) => void,
+  onKeyDown?: (input: string) => void,
+};

+ 12 - 6
packages/app/src/client/services/ContextExtractor.tsx

@@ -2,10 +2,10 @@ import React, { FC, useEffect, useState } from 'react';
 import { pagePathUtils } from '@growi/core';
 
 import {
-  useCreatedAt, useDeleteUsername, useDeletedAt, useHasChildren, useHasDraftOnHackmd, useIsAbleToDeleteCompletely,
+  useCurrentCreatedAt, useDeleteUsername, useDeletedAt, useHasChildren, useHasDraftOnHackmd, useIsAbleToDeleteCompletely,
   useIsDeletable, useIsDeleted, useIsNotCreatable, useIsPageExist, useIsTrashPage, useIsUserPage, useLastUpdateUsername,
   useCurrentPageId, usePageIdOnHackmd, usePageUser, useCurrentPagePath, useRevisionCreatedAt, useRevisionId, useRevisionIdHackmdSynced,
-  useShareLinkId, useShareLinksNumber, useTemplateTagData, useUpdatedAt, useCreator, useRevisionAuthor, useCurrentUser, useTargetAndAncestors,
+  useShareLinkId, useShareLinksNumber, useTemplateTagData, useCurrentUpdatedAt, useCreator, useRevisionAuthor, useCurrentUser, useTargetAndAncestors,
   useSlackChannels, useNotFoundTargetPathOrId, useIsSearchPage,
 } from '../../stores/context';
 import {
@@ -40,8 +40,14 @@ const ContextExtractorOnce: FC = () => {
   const path = decodeURI(mainContent?.getAttribute('data-path') || '');
   const pageId = mainContent?.getAttribute('data-page-id') || null;
   const revisionCreatedAt = +(mainContent?.getAttribute('data-page-revision-created') || '');
-  const createdAt = mainContent?.getAttribute('data-page-created-at');
-  const updatedAt = mainContent?.getAttribute('data-page-updated-at');
+
+  // createdAt
+  const createdAtAttribute = mainContent?.getAttribute('data-page-created-at');
+  const createdAt: Date | null = (createdAtAttribute != null) ? new Date(createdAtAttribute) : null;
+  // updatedAt
+  const updatedAtAttribute = mainContent?.getAttribute('data-page-updated-at');
+  const updatedAt: Date | null = (updatedAtAttribute != null) ? new Date(updatedAtAttribute) : null;
+
   const deletedAt = mainContent?.getAttribute('data-page-deleted-at') || null;
   const isUserPage = JSON.parse(mainContent?.getAttribute('data-page-user') || jsonNull);
   const isTrashPage = _isTrashPage(path);
@@ -81,7 +87,7 @@ const ContextExtractorOnce: FC = () => {
   useCurrentProductNavWidth(userUISettings?.currentProductNavWidth);
 
   // Page
-  useCreatedAt(createdAt);
+  useCurrentCreatedAt(createdAt);
   useDeleteUsername(deleteUsername);
   useDeletedAt(deletedAt);
   useHasChildren(hasChildren);
@@ -104,7 +110,7 @@ const ContextExtractorOnce: FC = () => {
   useShareLinkId(shareLinkId);
   useShareLinksNumber(shareLinksNumber);
   useTemplateTagData(templateTagData);
-  useUpdatedAt(updatedAt);
+  useCurrentUpdatedAt(updatedAt);
   useCreator(creator);
   useRevisionAuthor(revisionAuthor);
   useTargetAndAncestors(targetAndAncestors);

+ 1 - 0
packages/app/src/client/services/PageContainer.js

@@ -65,6 +65,7 @@ export default class PageContainer extends Container {
       sumOfLikers: 0,
 
       createdAt: mainContent.getAttribute('data-page-created-at'),
+      // please use useCurrentUpdatedAt instead
       updatedAt: mainContent.getAttribute('data-page-updated-at'),
       deletedAt: mainContent.getAttribute('data-page-deleted-at') || null,
 

+ 47 - 0
packages/app/src/client/util/codemirror/drawio-fold.ext.js

@@ -0,0 +1,47 @@
+/* eslint-disable */
+
+import mdu from '../../../components/PageEditor/MarkdownDrawioUtil.js';
+
+(function(mod) {
+  mod(require("codemirror"));
+})(function(CodeMirror) {
+  "use strict"
+
+  CodeMirror.registerGlobalHelper('fold', 'drawio', function (mode, cm) {
+    return true;
+  }, function(cm, start) {
+    function isBeginningOfDrawio(lineNo) {
+      let line = cm.getLine(lineNo);
+      let match = mdu.lineBeginPartOfDrawioRE.exec(line);
+      if (match) {
+        return true;
+      }
+      return false;
+    }
+    function isEndOfDrawio(lineNo) {
+      let line = cm.getLine(lineNo);
+      let match = mdu.lineEndPartOfDrawioRE.exec(line);
+      if (match) {
+        return true;
+      }
+      return false;
+    }
+
+    let drawio = isBeginningOfDrawio(start.line);
+    if (drawio === false) { return; }
+
+    let lastLine = cm.lastLine();
+    let end = start.line;
+    while(end < lastLine) {
+      end += 1;
+      if (isEndOfDrawio(end)) {
+        break;
+      }
+    }
+
+    return {
+      from: CodeMirror.Pos(start.line, cm.getLine(start.line).length),
+      to: CodeMirror.Pos(end, cm.getLine(end).length)
+    };
+  });
+});

+ 16 - 1
packages/app/src/client/util/interceptor/drawio-interceptor.js

@@ -103,11 +103,18 @@ export class DrawioInterceptor extends BasicInterceptor {
    */
   drawioPostRender(contextName, context) {
     const isPreview = (contextName === 'postRenderPreviewHtml');
+    const editorContainer = this.appContainer.getContainer('EditorContainer');
+    const renderDrawioInRealtime = editorContainer.state.previewOptions.renderDrawioInRealtime;
 
     Object.keys(context.DrawioMap).forEach((domId) => {
       const elem = document.getElementById(domId);
       if (elem) {
-        this.renderReactDOM(context.DrawioMap[domId], elem, isPreview);
+        if (isPreview && !renderDrawioInRealtime) {
+          this.renderDisabledDrawioReactDOM(context.DrawioMap[domId], elem, isPreview);
+        }
+        else {
+          this.renderReactDOM(context.DrawioMap[domId], elem, isPreview);
+        }
       }
     });
   }
@@ -129,6 +136,14 @@ export class DrawioInterceptor extends BasicInterceptor {
     );
   }
 
+  renderDisabledDrawioReactDOM(drawioMapEntry, elem, isPreview) {
+    ReactDOM.render(
+      // eslint-disable-next-line react/jsx-filename-extension
+      <div className="alert alert-light text-dark">Rendering of draw.io is disabled.</div>,
+      elem,
+    );
+  }
+
   /**
    * @inheritdoc
    */

+ 25 - 3
packages/app/src/components/Navbar/AuthorInfo.jsx

@@ -16,6 +16,9 @@ const AuthorInfo = (props) => {
   const infoLabelForSubNav = mode === 'create'
     ? 'Created by'
     : 'Updated by';
+  const nullinfoLabelForFooter = mode === 'create'
+    ? 'Created by'
+    : 'Updated by';
   const infoLabelForFooter = mode === 'create'
     ? 'Created at'
     : 'Last revision posted at';
@@ -24,9 +27,26 @@ const AuthorInfo = (props) => {
     : <i>Unknown</i>;
 
   if (locate === 'footer') {
-    return <p>{infoLabelForFooter} {format(new Date(date), formatType)} by <UserPicture user={user} size="sm" /> {userLabel}</p>;
+    try {
+      return <p>{infoLabelForFooter} {format(new Date(date), formatType)} by <UserPicture user={user} size="sm" /> {userLabel}</p>;
+    }
+    catch (err) {
+      if (err instanceof RangeError) {
+        return <p>{nullinfoLabelForFooter} <UserPicture user={user} size="sm" /> {userLabel}</p>;
+      }
+      return;
+    }
   }
 
+  const renderParsedDate = () => {
+    try {
+      return format(new Date(date), formatType);
+    }
+    catch (err) {
+      return '';
+    }
+  };
+
   return (
     <div className="d-flex align-items-center">
       <div className="mr-2">
@@ -34,14 +54,16 @@ const AuthorInfo = (props) => {
       </div>
       <div>
         <div>{infoLabelForSubNav} {userLabel}</div>
-        <div className="text-muted text-date">{format(new Date(date), formatType)}</div>
+        <div className="text-muted text-date">
+          {renderParsedDate()}
+        </div>
       </div>
     </div>
   );
 };
 
 AuthorInfo.propTypes = {
-  date: PropTypes.string.isRequired,
+  date: PropTypes.instanceOf(Date),
   user: PropTypes.object,
   mode: PropTypes.oneOf(['create', 'update']),
   locate: PropTypes.oneOf(['subnav', 'footer']),

+ 0 - 108
packages/app/src/components/Navbar/GlobalSearch.jsx

@@ -1,108 +0,0 @@
-import React from 'react';
-import PropTypes from 'prop-types';
-import { withTranslation } from 'react-i18next';
-
-import { withUnstatedContainers } from '../UnstatedUtils';
-import AppContainer from '~/client/services/AppContainer';
-
-import SearchForm from '../SearchForm';
-
-
-class GlobalSearch extends React.Component {
-
-  constructor(props) {
-    super(props);
-
-    const isSearchScopeChildrenAsDefault = this.props.appContainer.getConfig().isSearchScopeChildrenAsDefault;
-
-    this.state = {
-      text: '',
-      isScopeChildren: isSearchScopeChildrenAsDefault,
-    };
-
-    this.onInputChange = this.onInputChange.bind(this);
-    this.onClickAllPages = this.onClickAllPages.bind(this);
-    this.onClickChildren = this.onClickChildren.bind(this);
-    this.search = this.search.bind(this);
-  }
-
-  onInputChange(text) {
-    this.setState({ text });
-  }
-
-  onClickAllPages() {
-    this.setState({ isScopeChildren: false });
-  }
-
-  onClickChildren() {
-    this.setState({ isScopeChildren: true });
-  }
-
-  search() {
-    const url = new URL(window.location.href);
-    url.pathname = '/_search';
-
-    // construct search query
-    let q = this.state.text;
-    if (this.state.isScopeChildren) {
-      q += ` prefix:${window.location.pathname}`;
-    }
-    url.searchParams.append('q', q);
-
-    window.location.href = url.href;
-  }
-
-  render() {
-    const { t, appContainer, dropup } = this.props;
-    const scopeLabel = this.state.isScopeChildren
-      ? t('header_search_box.label.This tree')
-      : t('header_search_box.label.All pages');
-
-    const config = appContainer.getConfig();
-    const isReachable = config.isSearchServiceReachable;
-
-    return (
-      <div className={`form-group mb-0 d-print-none ${isReachable ? '' : 'has-error'}`}>
-        <div className="input-group flex-nowrap">
-          <div className={`input-group-prepend ${dropup ? 'dropup' : ''}`}>
-            <button className="btn btn-secondary dropdown-toggle py-0" type="button" data-toggle="dropdown" aria-haspopup="true">
-              {scopeLabel}
-            </button>
-            <div className="dropdown-menu">
-              <button className="dropdown-item" type="button" onClick={this.onClickAllPages}>{ t('header_search_box.item_label.All pages') }</button>
-              <button className="dropdown-item" type="button" onClick={this.onClickChildren}>{ t('header_search_box.item_label.This tree') }</button>
-            </div>
-          </div>
-          <SearchForm
-            t={this.props.t}
-            crowi={this.props.appContainer}
-            onInputChange={this.onInputChange}
-            onSubmit={this.search}
-            placeholder="Search ..."
-            dropup={dropup}
-          />
-          <div className="btn-group-submit-search">
-            <span role="button" className="btn-link text-decoration-none" onClick={this.search}>
-              <i className="icon-magnifier"></i>
-            </span>
-          </div>
-        </div>
-      </div>
-    );
-  }
-
-}
-
-GlobalSearch.propTypes = {
-  t: PropTypes.func.isRequired, // i18next
-  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
-
-  dropup: PropTypes.bool,
-};
-
-/**
- * Wrapper component for using unstated
- */
-const GlobalSearchWrapper = withUnstatedContainers(GlobalSearch, [AppContainer]);
-
-export default withTranslation()(GlobalSearchWrapper);

+ 97 - 0
packages/app/src/components/Navbar/GlobalSearch.tsx

@@ -0,0 +1,97 @@
+import React, {
+  FC, useState, useCallback,
+} from 'react';
+import { useTranslation } from 'react-i18next';
+import assert from 'assert';
+
+import AppContainer from '~/client/services/AppContainer';
+import { IPageSearchResultData } from '~/interfaces/search';
+
+import { withUnstatedContainers } from '../UnstatedUtils';
+
+import SearchForm from '../SearchForm';
+
+
+type Props = {
+  appContainer: AppContainer,
+
+  dropup?: boolean,
+}
+
+const GlobalSearch: FC<Props> = (props: Props) => {
+  const { appContainer, dropup } = props;
+  const { t } = useTranslation();
+
+  const [text, setText] = useState('');
+  const [isScopeChildren, setScopeChildren] = useState<boolean>(appContainer.getConfig().isSearchScopeChildrenAsDefault);
+
+  const gotoPage = useCallback((data: IPageSearchResultData[]) => {
+    assert(data.length > 0);
+
+    const page = data[0].pageData; // should be single page selected
+
+    // navigate to page
+    if (page != null) {
+      window.location.href = page._id;
+    }
+  }, []);
+
+  const search = useCallback(() => {
+    const url = new URL(window.location.href);
+    url.pathname = '/_search';
+
+    // construct search query
+    let q = text;
+    if (isScopeChildren) {
+      q += ` prefix:${window.location.pathname}`;
+    }
+    url.searchParams.append('q', q);
+
+    window.location.href = url.href;
+  }, [isScopeChildren, text]);
+
+  const scopeLabel = isScopeChildren
+    ? t('header_search_box.label.This tree')
+    : t('header_search_box.label.All pages');
+
+  const isSearchServiceReachable = appContainer.getConfig().isSearchServiceReachable;
+
+  return (
+    <div className={`form-group mb-0 d-print-none ${isSearchServiceReachable ? '' : 'has-error'}`}>
+      <div className="input-group flex-nowrap">
+        <div className={`input-group-prepend ${dropup ? 'dropup' : ''}`}>
+          <button className="btn btn-secondary dropdown-toggle py-0" type="button" data-toggle="dropdown" aria-haspopup="true">
+            {scopeLabel}
+          </button>
+          <div className="dropdown-menu">
+            <button className="dropdown-item" type="button" onClick={() => setScopeChildren(false)}>
+              { t('header_search_box.item_label.All pages') }
+            </button>
+            <button className="dropdown-item" type="button" onClick={() => setScopeChildren(true)}>
+              { t('header_search_box.item_label.This tree') }
+            </button>
+          </div>
+        </div>
+        <SearchForm
+          isSearchServiceReachable={isSearchServiceReachable}
+          dropup={dropup}
+          onChange={gotoPage}
+          onInputChange={text => setText(text)}
+          onSubmit={search}
+        />
+        <div className="btn-group-submit-search">
+          <span role="button" className="btn-link text-decoration-none" onClick={search}>
+            <i className="icon-magnifier"></i>
+          </span>
+        </div>
+      </div>
+    </div>
+  );
+};
+
+/**
+ * Wrapper component for using unstated
+ */
+const GlobalSearchWrapper = withUnstatedContainers(GlobalSearch, [AppContainer]);
+
+export default GlobalSearchWrapper;

+ 4 - 3
packages/app/src/components/Navbar/GrowiSubNavigation.jsx

@@ -4,10 +4,11 @@ import PropTypes from 'prop-types';
 import { withUnstatedContainers } from '../UnstatedUtils';
 import AppContainer from '~/client/services/AppContainer';
 import PageContainer from '~/client/services/PageContainer';
+import EditorContainer from '~/client/services/EditorContainer';
 import {
   EditorMode, useDrawerMode, useEditorMode, useIsDeviceSmallerThanMd,
 } from '~/stores/ui';
-import EditorContainer from '~/client/services/EditorContainer';
+import { useCurrentCreatedAt, useCurrentUpdatedAt } from '~/stores/context';
 
 import TagLabels from '../Page/TagLabels';
 import SubNavButtons from './SubNavButtons';
@@ -25,6 +26,8 @@ const GrowiSubNavigation = (props) => {
   const { data: isDeviceSmallerThanMd } = useIsDeviceSmallerThanMd();
   const { data: isDrawerMode } = useDrawerMode();
   const { data: editorMode, mutate: mutateEditorMode } = useEditorMode();
+  const { data: createdAt } = useCurrentCreatedAt();
+  const { data: updatedAt } = useCurrentUpdatedAt();
 
   const {
     appContainer, pageContainer, editorContainer, isCompactMode,
@@ -36,9 +39,7 @@ const GrowiSubNavigation = (props) => {
     path,
     isDeletable,
     isAbleToDeleteCompletely,
-    createdAt,
     creator,
-    updatedAt,
     revisionAuthor,
     isPageExist,
     isTrashPage,

+ 3 - 1
packages/app/src/components/Page/TrashPageAlert.jsx

@@ -7,6 +7,7 @@ import { UserPicture } from '@growi/ui';
 import { withUnstatedContainers } from '../UnstatedUtils';
 import AppContainer from '~/client/services/AppContainer';
 import PageContainer from '~/client/services/PageContainer';
+import { useCurrentUpdatedAt } from '~/stores/context';
 import PutbackPageModal from '../PutbackPageModal';
 import EmptyTrashModal from '../EmptyTrashModal';
 import PageDeleteModal from '../PageDeleteModal';
@@ -15,8 +16,9 @@ import PageDeleteModal from '../PageDeleteModal';
 const TrashPageAlert = (props) => {
   const { t, pageContainer } = props;
   const {
-    pageId, revisionId, path, isDeleted, lastUpdateUsername, updatedAt, deletedUserName, deletedAt, isAbleToDeleteCompletely,
+    pageId, path, isDeleted, lastUpdateUsername, deletedUserName, deletedAt, isAbleToDeleteCompletely,
   } = pageContainer.state;
+  const { data: updatedAt } = useCurrentUpdatedAt();
   const [isEmptyTrashModalShown, setIsEmptyTrashModalShown] = useState(false);
   const [isPutbackPageModalShown, setIsPutbackPageModalShown] = useState(false);
   const [isPageDeleteModalShown, setIsPageDeleteModalShown] = useState(false);

+ 7 - 2
packages/app/src/components/PageContentFooter.jsx

@@ -6,14 +6,19 @@ import AuthorInfo from './Navbar/AuthorInfo';
 import AppContainer from '~/client/services/AppContainer';
 import PageContainer from '~/client/services/PageContainer';
 import { withUnstatedContainers } from './UnstatedUtils';
-import { usePath } from '~/stores/context';
+import { useCurrentCreatedAt, useCurrentUpdatedAt } from '~/stores/context';
 
 const PageContentFooter = (props) => {
   const { pageContainer } = props;
+  const { data: createdAt } = useCurrentCreatedAt();
+  const { data: updatedAt } = useCurrentUpdatedAt();
+
+
   const {
-    createdAt, creator, updatedAt, revisionAuthor,
+    creator, revisionAuthor,
   } = pageContainer.state;
 
+
   return (
     <div className="page-content-footer py-4 d-edit-none d-print-none">
       <div className="grw-container-convertible">

+ 27 - 1
packages/app/src/components/PageEditor/CodeMirrorEditor.jsx

@@ -66,6 +66,7 @@ require('codemirror/addon/display/placeholder');
 require('codemirror/addon/lint/lint');
 require('codemirror/addon/lint/lint.css');
 require('~/client/util/codemirror/autorefresh.ext');
+require('~/client/util/codemirror/drawio-fold.ext');
 require('~/client/util/codemirror/gfm-growi.mode');
 // import modes to highlight
 require('codemirror/mode/clike/clike');
@@ -149,6 +150,9 @@ export default class CodeMirrorEditor extends AbstractEditor {
     this.showLinkEditHandler = this.showLinkEditHandler.bind(this);
     this.showHandsonTableHandler = this.showHandsonTableHandler.bind(this);
     this.showDrawioHandler = this.showDrawioHandler.bind(this);
+
+    this.foldDrawioSection = this.foldDrawioSection.bind(this);
+    this.onSaveForDrawio = this.onSaveForDrawio.bind(this);
   }
 
   init() {
@@ -185,6 +189,9 @@ export default class CodeMirrorEditor extends AbstractEditor {
     // set keymap
     const keymapMode = this.props.editorOptions.keymapMode;
     this.setKeymapMode(keymapMode);
+
+    // fold drawio section
+    this.foldDrawioSection();
   }
 
   componentWillReceiveProps(nextProps) {
@@ -195,6 +202,9 @@ export default class CodeMirrorEditor extends AbstractEditor {
     // set keymap
     const keymapMode = nextProps.editorOptions.keymapMode;
     this.setKeymapMode(keymapMode);
+
+    // fold drawio section
+    this.foldDrawioSection();
   }
 
   async initializeTextlint() {
@@ -741,6 +751,22 @@ export default class CodeMirrorEditor extends AbstractEditor {
     this.drawioModal.current.show(mdu.getMarkdownDrawioMxfile(this.getCodeMirror()));
   }
 
+  // fold draw.io section (::: drawio ~ :::)
+  foldDrawioSection() {
+    const editor = this.getCodeMirror();
+    const lineNumbers = mdu.findAllDrawioSection(editor);
+    lineNumbers.forEach((lineNumber) => {
+      editor.foldCode({ line: lineNumber, ch: 0 }, { scanUp: false }, 'fold');
+    });
+  }
+
+  onSaveForDrawio(drawioData) {
+    const range = mdu.replaceFocusedDrawioWithEditor(this.getCodeMirror(), drawioData);
+    // Fold the section after the drawio section (:::drawio) has been updated.
+    this.foldDrawioSection();
+    return range;
+  }
+
   getNavbarItems() {
     return [
       <Button
@@ -974,7 +1000,7 @@ export default class CodeMirrorEditor extends AbstractEditor {
         />
         <DrawioModal
           ref={this.drawioModal}
-          onSave={(drawioData) => { return mdu.replaceFocusedDrawioWithEditor(this.getCodeMirror(), drawioData) }}
+          onSave={this.onSaveForDrawio}
         />
 
       </React.Fragment>

+ 16 - 0
packages/app/src/components/PageEditor/MarkdownDrawioUtil.js

@@ -155,6 +155,22 @@ class MarkdownDrawioUtil {
     return newMarkdown;
   }
 
+  /**
+   * return an array of the starting line numbers of the drawio sections found in markdown
+   */
+  findAllDrawioSection(editor) {
+    const lineNumbers = [];
+    // refs: https://github.com/codemirror/CodeMirror/blob/5.64.0/addon/fold/foldcode.js#L106-L111
+    for (let i = editor.firstLine(), e = editor.lastLine(); i <= e; i++) {
+      const line = editor.getLine(i);
+      const match = this.lineBeginPartOfDrawioRE.exec(line);
+      if (match) {
+        lineNumbers.push(i);
+      }
+    }
+    return lineNumbers;
+  }
+
 }
 
 // singleton pattern

+ 36 - 0
packages/app/src/components/PageEditor/OptionsSelector.jsx

@@ -22,6 +22,7 @@ export const defaultEditorOptions = {
 
 export const defaultPreviewOptions = {
   renderMathJaxInRealtime: false,
+  renderDrawioInRealtime: true,
 };
 
 class OptionsSelector extends React.Component {
@@ -54,6 +55,7 @@ class OptionsSelector extends React.Component {
     this.onChangeKeymapMode = this.onChangeKeymapMode.bind(this);
     this.onClickStyleActiveLine = this.onClickStyleActiveLine.bind(this);
     this.onClickRenderMathJaxInRealtime = this.onClickRenderMathJaxInRealtime.bind(this);
+    this.onClickRenderDrawioInRealtime = this.onClickRenderDrawioInRealtime.bind(this);
     this.onClickMarkdownTableAutoFormatting = this.onClickMarkdownTableAutoFormatting.bind(this);
     this.switchTextlintEnabledHandler = this.switchTextlintEnabledHandler.bind(this);
     this.confirmEnableTextlintHandler = this.confirmEnableTextlintHandler.bind(this);
@@ -108,6 +110,17 @@ class OptionsSelector extends React.Component {
     editorContainer.saveOptsToLocalStorage();
   }
 
+  onClickRenderDrawioInRealtime(event) {
+    const { editorContainer } = this.props;
+
+    const newValue = !editorContainer.state.previewOptions.renderDrawioInRealtime;
+    const newOpts = Object.assign(editorContainer.state.previewOptions, { renderDrawioInRealtime: newValue });
+    editorContainer.setState({ previewOptions: newOpts });
+
+    // save to localStorage
+    editorContainer.saveOptsToLocalStorage();
+  }
+
   onClickMarkdownTableAutoFormatting(event) {
     const { editorContainer } = this.props;
 
@@ -249,6 +262,7 @@ class OptionsSelector extends React.Component {
           <DropdownMenu>
             {this.renderActiveLineMenuItem()}
             {this.renderRealtimeMathJaxMenuItem()}
+            {this.renderRealtimeDrawioMenuItem()}
             {this.renderMarkdownTableAutoFormattingMenuItem()}
             {this.renderIsTextlintEnabledMenuItem()}
             {/* <DropdownItem divider /> */}
@@ -308,6 +322,28 @@ class OptionsSelector extends React.Component {
     );
   }
 
+  renderRealtimeDrawioMenuItem() {
+    const { editorContainer } = this.props;
+
+    const isActive = editorContainer.state.previewOptions.renderDrawioInRealtime;
+
+    const iconClasses = ['text-info'];
+    if (isActive) {
+      iconClasses.push('ti-check');
+    }
+    const iconClassName = iconClasses.join(' ');
+
+    return (
+      <DropdownItem toggle={false} onClick={this.onClickRenderDrawioInRealtime}>
+        <div className="d-flex justify-content-between">
+          <span className="icon-container"><img src="/images/icons/fx.svg" width="14px" alt="fx"></img></span>
+          <span className="menuitem-label">draw.io Rendering</span>
+          <span className="icon-container"><i className={iconClassName}></i></span>
+        </div>
+      </DropdownItem>
+    );
+  }
+
   renderMarkdownTableAutoFormattingMenuItem() {
     const { t, editorContainer } = this.props;
     // Auto-formatting was enabled before optionalizing, so we made it a disabled option(ignoreMarkdownTableAutoFormatting).

+ 0 - 178
packages/app/src/components/SearchForm.jsx

@@ -1,178 +0,0 @@
-import React from 'react';
-import PropTypes from 'prop-types';
-import { withTranslation } from 'react-i18next';
-import { withUnstatedContainers } from './UnstatedUtils';
-import AppContainer from '~/client/services/AppContainer';
-
-import SearchTypeahead from './SearchTypeahead';
-
-// SearchTypeahead wrapper
-class SearchForm extends React.Component {
-
-  constructor(props) {
-    super(props);
-
-    this.state = {
-      searchError: null,
-      isShownHelp: false,
-    };
-
-    this.onSearchError = this.onSearchError.bind(this);
-    this.onChange = this.onChange.bind(this);
-    this.onBlur = this.onBlur.bind(this);
-    this.onFocus = this.onFocus.bind(this);
-  }
-
-  componentDidMount() {
-  }
-
-  componentWillUnmount() {
-  }
-
-  onSearchError(err) {
-    this.setState({
-      searchError: err,
-    });
-  }
-
-  onChange(selected) {
-    const page = selected[0]; // should be single page selected
-
-    // navigate to page
-    if (page != null) {
-      window.location = page.pageData._id;
-    }
-  }
-
-  onBlur() {
-    this.setState({
-      isShownHelp: false,
-    });
-
-    this.getHelpElement();
-  }
-
-  onFocus() {
-    this.setState({
-      isShownHelp: true,
-    });
-  }
-
-  getHelpElement() {
-    const { t, appContainer } = this.props;
-    const { isShownHelp } = this.state;
-
-    const config = appContainer.getConfig();
-    const isReachable = config.isSearchServiceReachable;
-
-
-    if (!isReachable) {
-      return (
-        <>
-          <h5 className="text-danger">Error occured on Search Service</h5>
-          Try to reconnect from management page.
-        </>
-      );
-    }
-
-    if (!isShownHelp) {
-      return <></>;
-    }
-
-    return (
-      <table className="table grw-search-table search-help m-0">
-        <caption className="text-left text-primary p-2">
-          <h5 className="h6"><i className="icon-magnifier pr-2 mb-2" />{ t('search_help.title') }</h5>
-        </caption>
-        <tbody>
-          <tr>
-            <th className="py-2">
-              <code>word1</code> <code>word2</code><br></br>
-              <small>({ t('search_help.and.syntax help') })</small>
-            </th>
-            <td><h6 className="m-0">{ t('search_help.and.desc', { word1: 'word1', word2: 'word2' }) }</h6></td>
-          </tr>
-          <tr>
-            <th className="py-2">
-              <code>&quot;This is GROWI&quot;</code><br></br>
-              <small>({ t('search_help.phrase.syntax help') })</small>
-            </th>
-            <td><h6 className="m-0">{ t('search_help.phrase.desc', { phrase: 'This is GROWI' }) }</h6></td>
-          </tr>
-          <tr>
-            <th className="py-2"><code>-keyword</code></th>
-            <td><h6 className="m-0">{ t('search_help.exclude.desc', { word: 'keyword' }) }</h6></td>
-          </tr>
-          <tr>
-            <th className="py-2"><code>prefix:/user/</code></th>
-            <td><h6 className="m-0">{ t('search_help.prefix.desc', { path: '/user/' }) }</h6></td>
-          </tr>
-          <tr>
-            <th className="py-2"><code>-prefix:/user/</code></th>
-            <td><h6 className="m-0">{ t('search_help.exclude_prefix.desc', { path: '/user/' }) }</h6></td>
-          </tr>
-          <tr>
-            <th className="py-2"><code>tag:wiki</code></th>
-            <td><h6 className="m-0">{ t('search_help.tag.desc', { tag: 'wiki' }) }</h6></td>
-          </tr>
-          <tr>
-            <th className="py-2"><code>-tag:wiki</code></th>
-            <td><h6 className="m-0">{ t('search_help.exclude_tag.desc', { tag: 'wiki' }) }</h6></td>
-          </tr>
-        </tbody>
-      </table>
-    );
-  }
-
-  render() {
-    const { t, appContainer, dropup } = this.props;
-
-    const config = appContainer.getConfig();
-    const isReachable = config.isSearchServiceReachable;
-
-    const placeholder = isReachable
-      ? 'Search ...'
-      : 'Error on Search Service';
-    const emptyLabel = (this.state.searchError !== null)
-      ? 'Error on searching.'
-      : t('search.search page bodies');
-
-    return (
-      <SearchTypeahead
-        dropup={dropup}
-        onChange={this.onChange}
-        onSubmit={this.props.onSubmit}
-        onInputChange={this.props.onInputChange}
-        onSearchError={this.onSearchError}
-        emptyLabel={emptyLabel}
-        placeholder={placeholder}
-        helpElement={this.getHelpElement()}
-        keywordOnInit={this.props.keyword}
-        onBlur={this.onBlur}
-        onFocus={this.onFocus}
-      />
-    );
-  }
-
-}
-
-/**
- * Wrapper component for using unstated
- */
-const SearchFormWrapper = withUnstatedContainers(SearchForm, [AppContainer]);
-
-SearchForm.propTypes = {
-  t: PropTypes.func.isRequired, // i18next
-  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
-
-  dropup: PropTypes.bool,
-  keyword: PropTypes.string,
-  onSubmit: PropTypes.func.isRequired,
-  onInputChange: PropTypes.func,
-};
-
-SearchForm.defaultProps = {
-  onInputChange: () => {},
-};
-
-export default withTranslation()(SearchFormWrapper);

+ 141 - 0
packages/app/src/components/SearchForm.tsx

@@ -0,0 +1,141 @@
+import React, {
+  FC, forwardRef, ForwardRefRenderFunction, useImperativeHandle,
+  useRef, useState,
+} from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { IPageSearchResultData } from '~/interfaces/search';
+import { IFocusable } from '~/client/interfaces/focusable';
+
+import SearchTypeahead from './SearchTypeahead';
+
+
+type SearchFormHelpProps = {
+  isReachable: boolean,
+  isShownHelp: boolean,
+}
+
+const SearchFormHelp: FC<SearchFormHelpProps> = (props: SearchFormHelpProps) => {
+  const { t } = useTranslation();
+
+  const { isReachable, isShownHelp } = props;
+
+  if (!isReachable) {
+    return (
+      <>
+        <h5 className="text-danger">Error occured on Search Service</h5>
+        Try to reconnect from management page.
+      </>
+    );
+  }
+
+  if (!isShownHelp) {
+    return <></>;
+  }
+
+  return (
+    <table className="table grw-search-table search-help m-0">
+      <caption className="text-left text-primary p-2">
+        <h5 className="h6"><i className="icon-magnifier pr-2 mb-2" />{ t('search_help.title') }</h5>
+      </caption>
+      <tbody>
+        <tr>
+          <th className="py-2">
+            <code>word1</code> <code>word2</code><br></br>
+            <small>({ t('search_help.and.syntax help') })</small>
+          </th>
+          <td><h6 className="m-0">{ t('search_help.and.desc', { word1: 'word1', word2: 'word2' }) }</h6></td>
+        </tr>
+        <tr>
+          <th className="py-2">
+            <code>&quot;This is GROWI&quot;</code><br></br>
+            <small>({ t('search_help.phrase.syntax help') })</small>
+          </th>
+          <td><h6 className="m-0">{ t('search_help.phrase.desc', { phrase: 'This is GROWI' }) }</h6></td>
+        </tr>
+        <tr>
+          <th className="py-2"><code>-keyword</code></th>
+          <td><h6 className="m-0">{ t('search_help.exclude.desc', { word: 'keyword' }) }</h6></td>
+        </tr>
+        <tr>
+          <th className="py-2"><code>prefix:/user/</code></th>
+          <td><h6 className="m-0">{ t('search_help.prefix.desc', { path: '/user/' }) }</h6></td>
+        </tr>
+        <tr>
+          <th className="py-2"><code>-prefix:/user/</code></th>
+          <td><h6 className="m-0">{ t('search_help.exclude_prefix.desc', { path: '/user/' }) }</h6></td>
+        </tr>
+        <tr>
+          <th className="py-2"><code>tag:wiki</code></th>
+          <td><h6 className="m-0">{ t('search_help.tag.desc', { tag: 'wiki' }) }</h6></td>
+        </tr>
+        <tr>
+          <th className="py-2"><code>-tag:wiki</code></th>
+          <td><h6 className="m-0">{ t('search_help.exclude_tag.desc', { tag: 'wiki' }) }</h6></td>
+        </tr>
+      </tbody>
+    </table>
+  );
+};
+
+
+type Props = {
+  isSearchServiceReachable: boolean,
+
+  dropup?: boolean,
+  keyword?: string,
+  onChange?: (data: IPageSearchResultData[]) => void,
+  onSubmit?: (input: string) => void,
+  onInputChange?: (text: string) => void,
+};
+
+
+const SearchForm: ForwardRefRenderFunction<IFocusable, Props> = (props: Props, ref) => {
+  const { t } = useTranslation();
+  const {
+    isSearchServiceReachable, dropup,
+    onChange, onSubmit, onInputChange,
+  } = props;
+
+  const [searchError, setSearchError] = useState<Error | null>(null);
+  const [isShownHelp, setShownHelp] = useState(false);
+
+  const searchTyheaheadRef = useRef<IFocusable>(null);
+
+  // publish focus()
+  useImperativeHandle(ref, () => ({
+    focus() {
+      const instance = searchTyheaheadRef?.current;
+      if (instance != null) {
+        instance.focus();
+      }
+    },
+  }));
+
+  const placeholder = isSearchServiceReachable
+    ? 'Search ...'
+    : 'Error on Search Service';
+
+  const emptyLabel = (searchError != null)
+    ? 'Error on searching.'
+    : t('search.search page bodies');
+
+  return (
+    <SearchTypeahead
+      ref={searchTyheaheadRef}
+      dropup={dropup}
+      emptyLabel={emptyLabel}
+      placeholder={placeholder}
+      onChange={onChange}
+      onSubmit={onSubmit}
+      onInputChange={onInputChange}
+      onSearchError={err => setSearchError(err)}
+      onBlur={() => setShownHelp(false)}
+      onFocus={() => setShownHelp(true)}
+      helpElement={<SearchFormHelp isShownHelp={isShownHelp} isReachable={isSearchServiceReachable} />}
+      keywordOnInit={props.keyword}
+    />
+  );
+};
+
+export default forwardRef(SearchForm);

+ 4 - 0
packages/app/src/components/SearchPage/SearchPageForm.jsx

@@ -39,11 +39,15 @@ class SearchPageForm extends React.Component {
   }
 
   render() {
+    const { appContainer } = this.props;
+    const isSearchServiceReachable = appContainer.getConfig().isSearchServiceReachable;
+
     return (
       // TODO: modify design after other component is created
       <div className="grw-search-form-in-search-result-page d-flex align-items-center">
         <div className="input-group flex-nowrap">
           <SearchForm
+            isSearchServiceReachable={isSearchServiceReachable}
             onSubmit={this.search}
             keyword={this.state.searchedKeyword}
             onInputChange={this.onInputChange}

+ 0 - 274
packages/app/src/components/SearchTypeahead.jsx

@@ -1,274 +0,0 @@
-import React from 'react';
-import PropTypes from 'prop-types';
-
-import { noop } from 'lodash/noop';
-import { AsyncTypeahead } from 'react-bootstrap-typeahead';
-
-import { UserPicture, PageListMeta, PagePathLabel } from '@growi/ui';
-
-import AppContainer from '~/client/services/AppContainer';
-import { withUnstatedContainers } from './UnstatedUtils';
-
-class SearchTypeahead extends React.Component {
-
-  constructor(props) {
-
-    super(props);
-
-    this.state = {
-      input: this.props.keywordOnInit,
-      pages: [],
-      isLoading: false,
-      searchError: null,
-    };
-
-    this.restoreInitialData = this.restoreInitialData.bind(this);
-    this.clearKeyword = this.clearKeyword.bind(this);
-    this.changeKeyword = this.changeKeyword.bind(this);
-    this.search = this.search.bind(this);
-    this.onInputChange = this.onInputChange.bind(this);
-    this.onKeyDown = this.onKeyDown.bind(this);
-    this.dispatchSubmit = this.dispatchSubmit.bind(this);
-    this.getEmptyLabel = this.getEmptyLabel.bind(this);
-    this.getResetFormButton = this.getResetFormButton.bind(this);
-    this.renderMenuItemChildren = this.renderMenuItemChildren.bind(this);
-    this.getTypeahead = this.getTypeahead.bind(this);
-  }
-
-  /**
-   * Get instance of AsyncTypeahead
-   */
-  getTypeahead() {
-    return this.typeahead ? this.typeahead.getInstance() : null;
-  }
-
-  componentDidMount() {
-  }
-
-  componentWillUnmount() {
-  }
-
-  /**
-   * Initialize keywordyword
-   */
-  restoreInitialData() {
-    this.changeKeyword(this.props.keywordOnInit);
-  }
-
-  /**
-   * clear keyword
-   */
-  clearKeyword(text) {
-    this.changeKeyword('');
-  }
-
-  /**
-   * change keyword
-   */
-  changeKeyword(text) {
-    // see https://github.com/ericgio/react-bootstrap-typeahead/issues/266#issuecomment-414987723
-    const instance = this.typeahead.getInstance();
-    instance.clear();
-    instance.setState({ text });
-  }
-
-  search(keyword) {
-
-    if (keyword === '') {
-      return;
-    }
-
-    this.setState({ isLoading: true });
-
-    this.props.appContainer.apiGet('/search', { q: keyword })
-      .then((res) => { this.onSearchSuccess(res) })
-      .catch((err) => { this.onSearchError(err) });
-  }
-
-  /**
-   * Callback function which is occured when search is exit successfully
-   * @param {*} pages
-   */
-  onSearchSuccess(res) {
-    this.setState({
-      isLoading: false,
-      pages: res.data,
-    });
-    if (this.props.onSearchSuccess != null) {
-      this.props.onSearchSuccess(res);
-    }
-  }
-
-  /**
-   * Callback function which is occured when search is exit abnormaly
-   * @param {*} err
-   */
-  onSearchError(err) {
-    this.setState({
-      isLoading: false,
-      searchError: err,
-    });
-    if (this.props.onSearchError != null) {
-      this.props.onSearchError(err);
-    }
-  }
-
-  onInputChange(text) {
-    this.setState({ input: text });
-    this.props.onInputChange(text);
-    if (text === '') {
-      this.setState({ pages: [] });
-    }
-  }
-
-  onKeyDown(event) {
-    if (event.keyCode === 13) {
-      this.dispatchSubmit();
-    }
-  }
-
-  dispatchSubmit() {
-    if (this.props.onSubmit != null) {
-      this.props.onSubmit(this.state.input);
-    }
-  }
-
-  getEmptyLabel() {
-    const { emptyLabel, helpElement } = this.props;
-    const { input } = this.state;
-
-    // show help element if empty
-    if (input.length === 0) {
-      return helpElement;
-    }
-
-    // use props.emptyLabel as is if defined
-    if (emptyLabel !== undefined) {
-      return this.props.emptyLabel;
-    }
-
-    let emptyLabelExceptError = 'No matches found on title...';
-    if (this.props.emptyLabelExceptError !== undefined) {
-      emptyLabelExceptError = this.props.emptyLabelExceptError;
-    }
-
-    return (this.state.searchError !== null)
-      ? 'Error on searching.'
-      : emptyLabelExceptError;
-  }
-
-  /**
-   * Get restore form button to initialize button
-   */
-  getResetFormButton() {
-    const isClearBtn = this.props.behaviorOfResetBtn === 'clear';
-    const initialKeyword = isClearBtn ? '' : this.props.keywordOnInit;
-    const isHidden = this.state.input === initialKeyword;
-    const resetForm = isClearBtn ? this.clearKeyword : this.restoreInitialData;
-
-    return isHidden ? (
-      <span />
-    ) : (
-      <button type="button" className="btn btn-link search-clear" onMouseDown={resetForm}>
-        <i className="icon-close" />
-      </button>
-    );
-  }
-
-  renderMenuItemChildren(option, props, index) {
-    const page = option.pageData;
-    return (
-      <span>
-        <UserPicture user={page.lastUpdateUser} size="sm" noLink />
-        <span className="ml-1 text-break text-wrap"><PagePathLabel path={page.path} /></span>
-        <PageListMeta page={page} />
-      </span>
-    );
-  }
-
-  render() {
-    const defaultSelected = (this.props.keywordOnInit !== '')
-      ? [{ path: this.props.keywordOnInit }]
-      : [];
-    const inputProps = { autoComplete: 'off' };
-    if (this.props.inputName != null) {
-      inputProps.name = this.props.inputName;
-    }
-
-    const resetFormButton = this.getResetFormButton();
-
-    return (
-      <div className="search-typeahead">
-        <AsyncTypeahead
-          {...this.props}
-          id="search-typeahead-asynctypeahead"
-          ref={(c) => { this.typeahead = c }}
-          inputProps={inputProps}
-          isLoading={this.state.isLoading}
-          labelKey={data => data?.pageData?.path || this.props.keywordOnInit || ''} // https://github.com/ericgio/react-bootstrap-typeahead/blob/master/docs/Rendering.md#labelkey-stringfunction
-          minLength={0}
-          options={this.state.pages} // Search result (Some page names)
-          promptText={this.props.helpElement}
-          emptyLabel={this.getEmptyLabel()}
-          align="left"
-          submitFormOnEnter
-          onSearch={this.search}
-          onInputChange={this.onInputChange}
-          onKeyDown={this.onKeyDown}
-          renderMenuItemChildren={this.renderMenuItemChildren}
-          caseSensitive={false}
-          defaultSelected={defaultSelected}
-          autoFocus={this.props.autoFocus}
-          onBlur={this.props.onBlur}
-          onFocus={this.props.onFocus}
-        />
-        {resetFormButton}
-      </div>
-    );
-  }
-
-}
-
-/**
- * Wrapper component for using unstated
- */
-const SearchTypeaheadWrapper = withUnstatedContainers(SearchTypeahead, [AppContainer]);
-
-/**
- * Properties
- */
-SearchTypeahead.propTypes = {
-  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
-
-  onSearchSuccess: PropTypes.func,
-  onSearchError:   PropTypes.func,
-  onChange:        PropTypes.func,
-  onBlur:          PropTypes.func,
-  onFocus:         PropTypes.func,
-  onSubmit:        PropTypes.func,
-  onInputChange:   PropTypes.func,
-  inputName:       PropTypes.string,
-  emptyLabel:      PropTypes.string,
-  emptyLabelExceptError: PropTypes.string,
-  placeholder:     PropTypes.string,
-  keywordOnInit:   PropTypes.string,
-  helpElement:     PropTypes.object,
-  autoFocus:       PropTypes.bool,
-  behaviorOfResetBtn: PropTypes.oneOf(['restore', 'clear']),
-};
-
-/**
- * Properties
- */
-SearchTypeahead.defaultProps = {
-  onSearchSuccess: noop,
-  onSearchError:   noop,
-  onChange:        noop,
-  placeholder:     '',
-  keywordOnInit:   '',
-  behaviorOfResetBtn: 'restore',
-  autoFocus:       false,
-  onInputChange: () => {},
-};
-
-export default SearchTypeaheadWrapper;

+ 250 - 0
packages/app/src/components/SearchTypeahead.tsx

@@ -0,0 +1,250 @@
+import React, {
+  FC, ForwardRefRenderFunction, forwardRef, useImperativeHandle,
+  KeyboardEvent, useCallback, useRef, useState,
+} from 'react';
+// eslint-disable-next-line no-restricted-imports
+import { AxiosResponse } from 'axios';
+
+import { AsyncTypeahead } from 'react-bootstrap-typeahead';
+
+import { UserPicture, PageListMeta, PagePathLabel } from '@growi/ui';
+
+import { IFocusable } from '~/client/interfaces/focusable';
+import { TypeaheadProps } from '~/client/interfaces/react-bootstrap-typeahead';
+import { apiGet } from '~/client/util/apiv1-client';
+import { IPageSearchResultData, IFormattedSearchResult } from '~/interfaces/search';
+
+
+type ResetFormButtonProps = {
+  keywordOnInit: string,
+  behaviorOfResetBtn: 'restore' | 'clear',
+  input: string,
+  onReset: () => void,
+}
+
+const ResetFormButton: FC<ResetFormButtonProps> = (props: ResetFormButtonProps) => {
+  const isClearBtn = props.behaviorOfResetBtn === 'clear';
+  const initialKeyword = isClearBtn ? '' : props.keywordOnInit;
+  const isHidden = props.input === initialKeyword;
+
+  return isHidden ? (
+    <span />
+  ) : (
+    <button type="button" className="btn btn-link search-clear" onMouseDown={props.onReset}>
+      <i className="icon-close" />
+    </button>
+  );
+};
+
+
+type Props = TypeaheadProps & {
+  onSearchSuccess?: (res: IPageSearchResultData[]) => void,
+  onSearchError?: (err: Error) => void,
+  onSubmit?: (input: string) => void,
+  inputName?: string,
+  keywordOnInit?: string,
+  // eslint-disable-next-line @typescript-eslint/no-explicit-any
+  helpElement?: any,
+  behaviorOfResetBtn?: 'restore' | 'clear',
+};
+
+// see https://github.com/ericgio/react-bootstrap-typeahead/issues/266#issuecomment-414987723
+type TypeaheadInstance = {
+  clear: () => void,
+  focus: () => void,
+  setState: ({ text: string }) => void,
+}
+type TypeaheadInstanceFactory = {
+  getInstance: () => TypeaheadInstance,
+}
+
+const SearchTypeahead: ForwardRefRenderFunction<IFocusable, Props> = (props: Props, ref) => {
+  const {
+    keywordOnInit,
+    onSearchSuccess, onSearchError, onInputChange, onSubmit,
+    emptyLabel, helpElement,
+  } = props;
+
+  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+  const [input, setInput] = useState(props.keywordOnInit!);
+  const [pages, setPages] = useState<IPageSearchResultData[]>();
+  // eslint-disable-next-line @typescript-eslint/no-unused-vars
+  const [searchError, setSearchError] = useState<Error | null>(null);
+  const [isLoading, setLoading] = useState(false);
+
+  const typeaheadRef = useRef<TypeaheadInstanceFactory>(null);
+
+
+  // publish focus()
+  useImperativeHandle(ref, () => ({
+    focus() {
+      const instance = typeaheadRef.current?.getInstance();
+      if (instance != null) {
+        instance.focus();
+      }
+    },
+  }));
+
+
+  const changeKeyword = (text: string | undefined) => {
+    const instance = typeaheadRef.current?.getInstance();
+    if (instance != null) {
+      instance.clear();
+      instance.setState({ text });
+    }
+  };
+
+  const restoreInitialData = () => {
+    changeKeyword(keywordOnInit);
+  };
+
+  const clearKeyword = () => {
+    changeKeyword('');
+  };
+
+  /**
+   * Callback function which is occured when search is exit successfully
+   */
+  const searchSuccessHandler = useCallback((result: IFormattedSearchResult) => {
+    const searchResultData = result.data;
+    setPages(searchResultData);
+
+    if (onSearchSuccess != null) {
+      onSearchSuccess(searchResultData);
+    }
+  }, [onSearchSuccess]);
+
+  /**
+   * Callback function which is occured when search is exit abnormaly
+   */
+  const searchErrorHandler = useCallback((err: Error) => {
+    setSearchError(err);
+
+    if (onSearchError != null) {
+      onSearchError(err);
+    }
+  }, [onSearchError]);
+
+  const search = useCallback(async(keyword: string) => {
+    if (keyword === '') {
+      return;
+    }
+
+    setLoading(true);
+
+    try {
+      const result = await apiGet('/search', { q: keyword }) as IFormattedSearchResult;
+      searchSuccessHandler(result);
+    }
+    catch (err) {
+      searchErrorHandler(err);
+    }
+    finally {
+      setLoading(false);
+    }
+
+  }, [searchErrorHandler, searchSuccessHandler]);
+
+  const inputChangeHandler = useCallback((text: string) => {
+    setInput(text);
+
+    if (onInputChange != null) {
+      onInputChange(text);
+    }
+
+    if (text === '') {
+      setPages([]);
+    }
+  }, [onInputChange]);
+
+  const keyDownHandler = useCallback((event: KeyboardEvent) => {
+    if (event.keyCode === 13) { // Enter key
+      if (onSubmit != null) {
+        onSubmit(input);
+      }
+    }
+  }, [input, onSubmit]);
+
+  const getEmptyLabel = () => {
+    // show help element if empty
+    if (input.length === 0) {
+      return helpElement;
+    }
+
+    // use props.emptyLabel as is if defined
+    if (emptyLabel !== undefined) {
+      return emptyLabel;
+    }
+
+    return false;
+  };
+
+  const defaultSelected = (props.keywordOnInit !== '')
+    ? [{ path: props.keywordOnInit }]
+    : [];
+  // eslint-disable-next-line @typescript-eslint/no-explicit-any
+  const inputProps: any = { autoComplete: 'off' };
+  if (props.inputName != null) {
+    inputProps.name = props.inputName;
+  }
+
+  const isClearBtn = props.behaviorOfResetBtn === 'clear';
+  const resetForm = isClearBtn ? clearKeyword : restoreInitialData;
+
+  const renderMenuItemChildren = (option: IPageSearchResultData) => {
+    const { pageData } = option;
+    return (
+      <span>
+        <UserPicture user={pageData.lastUpdateUser} size="sm" noLink />
+        <span className="ml-1 text-break text-wrap"><PagePathLabel path={pageData.path} /></span>
+        <PageListMeta page={pageData} />
+      </span>
+    );
+  };
+
+  return (
+    <div className="search-typeahead">
+      <AsyncTypeahead
+        {...props}
+        id="search-typeahead-asynctypeahead"
+        ref={typeaheadRef}
+        inputProps={inputProps}
+        isLoading={isLoading}
+        labelKey={data => data?.pageData?.path || keywordOnInit || ''} // https://github.com/ericgio/react-bootstrap-typeahead/blob/master/docs/Rendering.md#labelkey-stringfunction
+        minLength={0}
+        options={pages} // Search result (Some page names)
+        promptText={props.helpElement}
+        emptyLabel={getEmptyLabel()}
+        align="left"
+        onSearch={search}
+        onInputChange={inputChangeHandler}
+        onKeyDown={keyDownHandler}
+        renderMenuItemChildren={renderMenuItemChildren}
+        caseSensitive={false}
+        defaultSelected={defaultSelected}
+        autoFocus={props.autoFocus}
+        onBlur={props.onBlur}
+        onFocus={props.onFocus}
+      />
+      <ResetFormButton
+        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+        keywordOnInit={props.keywordOnInit!}
+        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+        behaviorOfResetBtn={props.behaviorOfResetBtn!}
+        input={input}
+        onReset={resetForm}
+      />
+    </div>
+  );
+};
+
+const ForwardedSearchTypeahead = forwardRef(SearchTypeahead);
+
+ForwardedSearchTypeahead.defaultProps = {
+  placeholder: '',
+  keywordOnInit: '',
+  behaviorOfResetBtn: 'restore',
+  autoFocus: false,
+};
+
+export default ForwardedSearchTypeahead;

+ 12 - 0
packages/app/src/interfaces/search.ts

@@ -18,6 +18,18 @@ export type IPageSearchResultData = {
   };
 };
 
+export type IFormattedSearchResult = {
+  data: IPageSearchResultData[]
+
+  totalCount: number
+
+  meta: {
+    total: number
+    took?: number
+    count?: number
+  }
+}
+
 export const SORT_AXIS = {
   RELATION_SCORE: 'relationScore',
   CREATED_AT: 'createdAt',

+ 4 - 16
packages/app/src/server/service/search.ts

@@ -2,6 +2,8 @@ import RE2 from 're2';
 import xss from 'xss';
 
 import { SearchDelegatorName } from '~/interfaces/named-query';
+import { IFormattedSearchResult } from '~/interfaces/search';
+import loggerFactory from '~/utils/logger';
 
 import NamedQuery from '../models/named-query';
 import {
@@ -10,10 +12,8 @@ import {
 import ElasticsearchDelegator from './search-delegator/elasticsearch';
 import PrivateLegacyPagesDelegator from './search-delegator/private-legacy-pages';
 
-import loggerFactory from '~/utils/logger';
 import { PageModel } from '../models/page';
 import { serializeUserSecurely } from '../models/serializers/user-serializer';
-import { IPageSearchResultData } from '~/interfaces/search';
 
 // eslint-disable-next-line no-unused-vars
 const logger = loggerFactory('growi:service:search');
@@ -34,18 +34,6 @@ const normalizeQueryString = (_queryString: string): string => {
   return queryString;
 };
 
-export type FormattedSearchResult = {
-  data: IPageSearchResultData[]
-
-  totalCount: number
-
-  meta: {
-    total: number
-    took?: number
-    count?: number
-  }
-}
-
 class SearchService implements SearchQueryParser, SearchResolver {
 
   crowi!: any
@@ -355,7 +343,7 @@ class SearchService implements SearchQueryParser, SearchResolver {
   /**
    * formatting result
    */
-  async formatSearchResult(searchResult: Result<any> & MetaData, delegatorName): Promise<FormattedSearchResult> {
+  async formatSearchResult(searchResult: Result<any> & MetaData, delegatorName): Promise<IFormattedSearchResult> {
     if (!this.checkIsFormattable(searchResult, delegatorName)) {
       const data = searchResult.data.map((page) => {
         return {
@@ -376,7 +364,7 @@ class SearchService implements SearchQueryParser, SearchResolver {
      */
     const Page = this.crowi.model('Page') as PageModel;
     const User = this.crowi.model('User');
-    const result = {} as FormattedSearchResult;
+    const result = {} as IFormattedSearchResult;
 
     // get page data
     const pageIds = searchResult.data.map((page) => { return page._id });

+ 2 - 2
packages/app/src/server/views/widget/page_content.html

@@ -17,10 +17,10 @@
   data-page-is-not-creatable="false"
   data-page-is-able-to-delete-completely="{% if user.canDeleteCompletely(page.creator._id) %}true{% else %}false{% endif %}"
   data-slack-channels="{% if page %}{{ page.slackChannels }}{% endif %}"
-  data-page-created-at="{% if page %}{{ page.createdAt|datetz('Y/m/d H:i:s') }}{% endif %}"
+  data-page-created-at="{{ page.createdAt|datetz('Y/m/d H:i:s') }}"
   data-page-creator="{% if page && page.creator %}{{ page.creator|json }}{% endif %}"
   data-page-last-update-username="{% if page && page.lastUpdateUser %}{{ page.lastUpdateUser.name }}{% endif %}"
-  data-page-updated-at="{% if page %}{{ page.updatedAt|datetz('Y/m/d H:i:s') }}{% endif %}"
+  data-page-updated-at="{{ page.updatedAt|datetz('Y/m/d H:i:s') }}"
   data-page-delete-username="{% if page && page.deleteUser %}{{ page.deleteUser.name }}{% endif %}"
   data-page-deleted-at="{% if page && page.deletedAt %}{{ page.deletedAt|datetz('Y/m/d H:i:s') }}{% endif %}"
   data-page-has-children="{% if pages.length > 0 %}true{% else %}false{% endif %}"

+ 4 - 4
packages/app/src/stores/context.tsx

@@ -32,12 +32,12 @@ export const useRevisionCreatedAt = (initialData?: Nullable<any>): SWRResponse<N
   return useStaticSWR<Nullable<any>, Error>('revisionCreatedAt', initialData ?? null);
 };
 
-export const useCreatedAt = (initialData?: Nullable<any>): SWRResponse<Nullable<any>, Error> => {
-  return useStaticSWR<Nullable<any>, Error>('createdAt', initialData ?? null);
+export const useCurrentCreatedAt = (initialData?: Nullable<Date>): SWRResponse<Nullable<Date>, Error> => {
+  return useStaticSWR<Nullable<Date>, Error>('createdAt', initialData ?? null);
 };
 
-export const useUpdatedAt = (initialData?: Nullable<any>): SWRResponse<Nullable<any>, Error> => {
-  return useStaticSWR<Nullable<any>, Error>('updatedAt', initialData ?? null);
+export const useCurrentUpdatedAt = (initialData?: Nullable<Date>): SWRResponse<Nullable<Date>, Error> => {
+  return useStaticSWR<Nullable<Date>, Error>('updatedAt', initialData ?? null);
 };
 
 export const useDeletedAt = (initialData?: Nullable<any>): SWRResponse<Nullable<any>, Error> => {

+ 2 - 1
packages/app/src/styles/_sidebar.scss

@@ -22,7 +22,8 @@
   position: sticky;
   top: $grw-navbar-border-width;
 
-  height: 100vh;
+  // set the max value that should be taken when sticky
+  height: calc(100vh - $grw-navbar-border-width);
 
   .grw-navigation-resize-button {
     position: fixed;

Разница между файлами не показана из-за своего большого размера
+ 349 - 272
yarn.lock


Некоторые файлы не были показаны из-за большого количества измененных файлов