Skip to content
This repository has been archived by the owner on Oct 25, 2023. It is now read-only.

Commit

Permalink
[fix] Backward compatibility with text doc types (chunks, draft) (#68)
Browse files Browse the repository at this point in the history
  • Loading branch information
akindyakov committed Oct 26, 2021
1 parent 1b9df78 commit 213f19f
Show file tree
Hide file tree
Showing 13 changed files with 155 additions and 208 deletions.
6 changes: 3 additions & 3 deletions smuggler-api/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ async function getNode({
const node = new TNode(
nid,
ntype,
NodeTextData.fromJson(text),
text as NodeTextData,
moment(res.headers[kHeaderCreatedAt]),
moment(res.headers[kHeaderLastModified]),
meta,
Expand All @@ -174,7 +174,7 @@ async function updateNode({
text: NodeTextData
cancelToken: CancelToken
}) {
const value = { text: text.toJson() }
const value = { text }
const headers = {
[kHeaderContentType]: Mime.JSON,
}
Expand Down Expand Up @@ -247,7 +247,7 @@ async function getNodesSlice({
index_text = null,
meta = null,
} = item
const textObj = NodeTextData.fromJson(text)
const textObj = text as NodeTextData
const extattrsObj = extattrs ? NodeExtattrs.fromJson(extattrs) : null
return new TNode(
nid,
Expand Down
46 changes: 4 additions & 42 deletions smuggler-api/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,50 +24,12 @@ export function makeEmptySlate(): SlateText {
}

// see smuggler/src/types.rs
export class NodeTextData {
slate: SlateText

export type NodeTextData = {
slate: SlateText | undefined
// Deprecated
draft: Optional<any>

draft: any | undefined
// Deprecated
chunks: Optional<any>

constructor(slate: SlateText) {
this.slate = slate
}

static fromJson({
slate,
draft,
chunks,
}: {
slate?: SlateText
draft?: object
chunks?: any
}): NodeTextData {
if (slate == null) {
slate = makeEmptySlate()
}
return new NodeTextData(slate)
}

toJson(): { slate: SlateText } {
const { slate } = this
return { slate }
}

getText(): SlateText {
const { slate } = this
if (slate) {
return slate
}
return makeEmptySlate()
}

updateText(slate: SlateText): NodeTextData {
return new NodeTextData(slate)
}
chunks: any | undefined
}

export enum NodeType {
Expand Down
1 change: 1 addition & 0 deletions truthsayer/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
"ts-node": "^9.1.1",
"typescript": "4.1.3",
"universal-cookie": "^4.0",
"use-async-effect": "^2.2.3",
"uuid": "^3.3"
},
"scripts": {
Expand Down
7 changes: 2 additions & 5 deletions truthsayer/src/card/ChainActionBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,8 @@ async function cloneNode({
if (!node) {
return null
}
const doc = makeACopy(
TDoc.fromNodeTextData(node.getText()),
node.getNid(),
isBlank || false
)
let doc = await TDoc.fromNodeTextData(node.getText())
doc = doc.makeACopy(node.getNid(), isBlank || false)
return await smuggler.node.create({
doc: doc.toNodeTextData(),
cancelToken,
Expand Down
5 changes: 3 additions & 2 deletions truthsayer/src/card/FullCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { WideCard } from './WideCard'
import { DocEditor } from '../doc/DocEditor'
import { ImageNode } from '../doc/image/ImageNode'
import { SlateText } from '../doc/types'
import { TDoc } from '../doc/doc_util'

import { Loader } from '../lib/loader'

Expand All @@ -18,8 +19,8 @@ export function FullCard({ node, addRef, stickyEdges, saveNode }) {
editor = <Loader />
} else {
const saveText = (text: SlateText) => {
const newText = node.getText().updateText(text)
saveNode(newText)
const doc = new TDoc(text)
saveNode(doc.toNodeTextData())
}
editor = (
<DocEditor className={styles.editor} node={node} saveText={saveText} />
Expand Down
44 changes: 23 additions & 21 deletions truthsayer/src/card/FullCardFootbar.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,28 +59,30 @@ class PrivateFullCardFootbarImpl extends React.Component {

handleCopyMarkdown = () => {
const toaster = this.props.context.toaster
const md = this.props.getMarkdown()
navigator.clipboard.writeText(md).then(
() => {
/* clipboard successfully set */
toaster.push({
title: 'Copied',
message: 'Note copied to clipboard as markdown',
})
},
() => {
/* clipboard write failed */
toaster.push({
title: 'Error',
message: 'Write to system clipboard failed',
})
}
)
this.props.getMarkdown().then((md) => {
navigator.clipboard.writeText(md).then(
() => {
/* clipboard successfully set */
toaster.push({
title: 'Copied',
message: 'Note copied to clipboard as markdown',
})
},
() => {
/* clipboard write failed */
toaster.push({
title: 'Error',
message: 'Write to system clipboard failed',
})
}
)
})
}

handleDownloadMarkdown = () => {
const md = this.props.getMarkdown()
downloadAsFile(`${this.props.nid}.txt`, md)
this.props.getMarkdown().then((md) => {
downloadAsFile(`${this.props.nid}.txt`, md)
})
}

handleArchiveDoc = () => {
Expand Down Expand Up @@ -238,8 +240,8 @@ export function FullCardFootbar({ children, node, ...rest }) {
if (node && node.meta) {
const { nid, meta } = node
if (node.isOwnedBy(account)) {
const getMarkdown = () => {
return docAsMarkdown(node)
const getMarkdown = async () => {
return await docAsMarkdown(node)
}
return (
<PrivateFullCardFootbar
Expand Down
34 changes: 22 additions & 12 deletions truthsayer/src/doc/DocEditor.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { useState, useCallback, useMemo, useEffect } from 'react'
import { useAsyncEffect } from 'use-async-effect'
import { Editable, Slate, withReact } from 'slate-react'
import {
Descendant,
Expand Down Expand Up @@ -63,6 +64,8 @@ import { Link } from './editor/components/Link'
import { Leaf } from './editor/components/Leaf'

import { FormatToolbar } from './FormatToolbar'
import { TDoc } from './doc_util'
import { SlateText } from './types'

import styles from './DocEditor.module.css'

Expand All @@ -80,14 +83,18 @@ export type CheckListItemElement = {
}

export const DocEditor = ({ className, node, saveText }) => {
const [value, setValue] = useState<Descendant[]>([])
const [value, setValue] = useState<SlateText>([])
const [showJinn, setShowJinn] = useState<boolean>(false)
const nid = node.nid
useEffect(() => {
let isSubscribed = true
setValue(node.getText().getText())
return () => (isSubscribed = false)
}, [nid])
useAsyncEffect(
async (isMounted) => {
const doc = await TDoc.fromNodeTextData(node.getText())
if (isMounted()) {
setValue(doc.slate)
}
},
[nid]
)
const renderElement = useCallback(
(props) => <Element nid={nid} {...props} />,
[nid]
Expand Down Expand Up @@ -133,12 +140,15 @@ export const DocEditor = ({ className, node, saveText }) => {

export const ReadOnlyDoc = ({ className, node }) => {
const [value, setValue] = useState<Descendant[]>([])
useEffect(() => {
let isSubscribed = true
const slateDoc = node.getText().getText()
setValue(slateDoc)
return () => (isSubscribed = false)
}, [node])
useAsyncEffect(
async (isMounted) => {
const doc = await TDoc.fromNodeTextData(node.getText())
if (isMounted()) {
setValue(doc.slate)
}
},
[node]
)
const renderElement = useCallback(
(props) => <ReadOnlyElement nid={node.nid} {...props} />,
[node]
Expand Down
43 changes: 25 additions & 18 deletions truthsayer/src/doc/doc_util.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@ import { render } from '@testing-library/react'
import {
exctractDocTitle,
getPlainText,
getDocSlate,
makeParagraph,
makeLeaf,
TDoc,
makeDoc,
} from './doc_util'
import { makeChunk } from './chunk_util.jsx'
import { markdownToDraft } from '../markdown/conv'
Expand All @@ -16,32 +15,38 @@ import lodash from 'lodash'

test('exctractDocTitle - raw string', async () => {
const text = 'RmdBzaGUgdHJpZWQgdG8gd2FzaCBvZm'
const doc = await getDocSlate(text)
const title = exctractDocTitle(doc)
const doc = await makeDoc({ plain: text })
const title = exctractDocTitle(doc.slate)
expect(title).toStrictEqual(text)
})

test('exctractDocTitle - empty object', () => {
const slate = [makeParagraph([makeLeaf()])]
const slate = [makeParagraph([makeLeaf('')])]
const title = exctractDocTitle(slate)
expect(title).toStrictEqual('Some page' + '\u2026')
})

test('exctractDocTitle - multiple chunks', async () => {
const text = 'RmdB zaGUgdHJpZWQgd G8gd2FzaCBvZm'
const doc: TDoc = {
const doc = await makeDoc({
chunks: [makeChunk(text), makeChunk('asdf'), , makeChunk('123')],
}
const title = exctractDocTitle(await getDocSlate(doc))
})
const title = exctractDocTitle(doc.slate)
expect(title).toStrictEqual(text)
})

test('getPlainText - chunks', () => {
const text = 'RmdB zaGUgdHJpZWQgd G8gd2FzaCBvZm'
const doc: TDoc = {
chunks: [makeChunk(text), makeChunk('asdf'), , makeChunk('123')],
}
const texts = getPlainText(doc)
const texts = getPlainText({
chunks: [
makeChunk(text) as any,
makeChunk('asdf') as any,
,
makeChunk('123') as any,
],
slate: undefined,
draft: undefined,
})
expect(texts).toStrictEqual([text, 'asdf', '123'])
})

Expand All @@ -61,10 +66,11 @@ __Trees were swaying__
[](@1618686400/YYYY-MMMM-DD-dddd)
-----`
const doc: TDoc = {
const texts = getPlainText({
draft: markdownToDraft(source),
}
const texts = getPlainText(doc)
slate: undefined,
chunks: undefined,
})
expect(texts).toContain('Header 1')
expect(texts).toContain('Header 2')
expect(texts).toContain('Schools')
Expand Down Expand Up @@ -105,10 +111,11 @@ __Trees were swaying__
[](@1618686400/YYYY-MMMM-DD-dddd)
-----`
const doc: TDoc = {
const texts = getPlainText({
slate: await markdownToSlate(source),
}
const texts = getPlainText(doc)
draft: undefined,
chunks: undefined,
})
expect(texts).toContain('Header 1')
expect(texts).toContain('Header 2')
expect(texts).toContain(
Expand Down

0 comments on commit 213f19f

Please sign in to comment.