sanity-plugin-markdown 9.0.0 → 9.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,24 @@
1
+ /// <reference path="operators/index.d.ts" />
2
+ /// <reference path="testing/index.d.ts" />
1
3
  import { Plugin, StringDefinition, StringInputProps } from "sanity";
2
4
  import { Options } from "easymde";
3
5
  import { SimpleMDEReactProps } from "react-simplemde-editor";
6
+ /**
7
+ * Note: This will add Symbol.observable globally for all TypeScript users,
8
+ * however, we are no longer polyfilling Symbol.observable
9
+ */
10
+ declare global {
11
+ interface SymbolConstructor {
12
+ readonly observable: symbol;
13
+ }
14
+ }
15
+ /**
16
+ * A function type interface that describes a function that accepts one parameter `T`
17
+ * and returns another parameter `R`.
18
+ *
19
+ * Usually used to describe {@link OperatorFunction} - it always takes a single
20
+ * parameter (the source Observable) and returns another Observable.
21
+ */
4
22
  /**
5
23
  * Used to tag types that is set to `any` as a temporary measure, but should be replaced with proper typings in the future
6
24
  * @internal
@@ -0,0 +1 @@
1
+ {"version":3,"file":"commonExports.d.ts","names":["global","SymbolConstructor","observable","T","R","source","UnaryFunction","Observable","OperatorFunction","value","timestamp","interval","unsubscribe","Subscription","Unsubscribable","closed","Subscribable","PromiseLike","InteropObservable","subscribe","Partial","Observer","observer","AsyncIterable","ArrayLike","Iterable","ReadableStreamLike","Symbol","kind","error","NextNotification","ErrorNotification","CompleteNotification","next","err","complete","NextObserver","ErrorObserver","CompletionObserver","TimestampProvider","schedule","SchedulerAction","this","state","work","delay","now","O","ObservableInput","X","Array","ObservedValueUnionFromArray","K","ObservedValueOf","Y","arg","rest","args","U","A","V","Falsy","read","done","releaseLock","getReader","ReadableStreamDefaultReaderLike","connect","CreateAction","ReplaceDraftAction","EditAction","DeleteAction","DiscardAction","PublishAction","UnpublishAction","VersionAction","ReleaseAction","type","description","items","ActionErrorItem","error","value","index","async","TParamConfig","docIdRequired","ConstantAgentActionParam","FieldAgentActionParam","DocumentAgentActionParam","GroqAgentActionParam","Record","AgentActionParam","AgentActionPathSegment","_key","AgentActionSchema","localeSettings","locale","timeZone","temperature","schemaId","forcePublishedWrite","conditionalPaths","defaultReadOnly","defaultHidden","paths","path","AgentActionPath","readOnly","hidden","private","constructor","SanityClient","client","HttpRequest","httpRequest","generate","DocumentShape","Any","GenerateInstruction","request","Promise","_id","IdentifiedSanityDocumentStub","transform","TransformDocument","translate","TranslateDocument","prompt","PromptRequest","patch","PatchDocument","noWrite","maxPathDepth","exclude","types","AgentActionTypeConfig","include","BaseMutationOptions","returnFirst","returnDocuments","width","height","start","end","fps","format","AnimatedImageFormat","Exclude","message","statusCode","actionType","releaseId","upload","assetType","UploadBody","body","UploadClientConfig","options","SanityAssetDocument","SanityImageAssetDocument","key","name","title","url","providers","AuthProvider","RequestOptions","transactionId","skipCrossDatasetReferenceValidation","dryRun","visibility","autoGenerateArrayKeys","selection","PatchSelection","operations","PatchOperations","set","AttributeSet","attrs","setIfMissing","diffMatchPatch","unset","inc","dec","insert","at","selector","append","prepend","splice","deleteCount","ifRevisionId","rev","serialize","PatchMutationOperation","toJSON","reset","_assign","op","props","merge","_set","Mutation","trxId","create","R","SanityDocumentStub","doc","createIfNotExists","createOrReplace","delete","documentId","id","_add","mut","Error","data","projectId","dataset","useCdn","token","resource","ClientConfigResource","perspective","ClientPerspective","apiHost","apiVersion","proxy","requestTagPrefix","headers","ignoreBrowserTokenWarning","ignoreWarnings","RegExp","Array","withCredentials","allowReconfigure","timeout","maxRetries","retryDelay","attemptNumber","useProjectHostname","requester","Requester","resultSourceMap","fetch","cache","ResponseQueryOptions","next","stega","StegaConfig","lineage","_requestHandler","RequestHandler","response","ErrorProps","responseBody","traceId","details","res","HttpContext","context","DeprecatedPreviewDrafts","StackablePerspective","GroqString","Fallback","SanityQueries","EventName","EventSourceInstance","Observable","initEventSource","events","ServerSentEvent","mappings","ContentSourceMapMappings","documents","ContentSourceMapDocuments","ContentSourceMapPaths","ContentSourceMapDocumentBase","_projectId","_dataset","_type","ContentSourceMapDocument","ContentSourceMapRemoteDocument","document","ContentSourceMapValueMapping","ContentSourceMapMapping","ContentSourceMapDocumentValueSource","ContentSourceMapLiteralSource","ContentSourceMapUnknownSource","source","ContentSourceMapSource","addOriginUrl","URL","credentials","publishedId","attributes","ifExists","ClientConfig","config","metadata","Partial","ReleaseDocument","baseId","versionId","ifBaseRevisionId","email","profileImage","role","provider","aclMode","DatasetAclMode","embeddings","enabled","projection","datasetName","DatasetCreateOptions","DatasetResponse","edit","DatasetEditOptions","deleted","list","DatasetsResponse","getEmbeddingsSettings","EmbeddingsSettings","editEmbeddingsSettings","EmbeddingsSettingsBody","settings","createdAt","createdByUserId","addonFor","datasetProfile","features","tags","includeDrafts","purge","draftId","reason","ErrorOptions","DocIdParam","Omit","PartialExcept","status","Name","InstanceType","globalThis","EventSource","sourcePath","ContentSourceMapParsedPath","sourceDocument","ContentSourceMapDocuments_2","resultPath","filterDefault","FilterDefault","filterResponse","QueryParseError","tag","T","GenerateExistingDocumentRequest","GenerateTargetDocumentRequest","GenerateRequestBase","AgentActionAsync","targetDocument","GenerateSyncInstruction","GenerateAsyncInstruction","AgentActionRequestBase","instruction","instructionParams","AgentActionParams","target","GenerateTarget","AgentActionSync","AgentActionTarget","operation","GenerateOperation","GenerateTargetInclude","initialValues","GenerateTargetDocument","AgentActionTargetInclude","query","params","ClientPerspective_2","method","statusMessage","ReturnType","ResponseEvent","ProgressEvent_2","P","imageUrl","isDefaultApi","cdnUrl","InitializedStegaConfig","StegaConfigRequiredKeys","Required","Pick","before","after","replace","HttpError","ObservableSanityClient","this","ListenParams","MutationEvent","Opts","ListenOptions","ResumableListenOptions","ListenEventFromOptions","ReconnectEvent","WelcomeBackEvent","ResetEvent","WelcomeEvent","OpenEvent","ResumableListenEventNames","ListenEventName","MapListenEventNamesToListenEvents","ListenEvent","includeResult","includeMutations","includePreviousRevision","includeAllVersions","effectFormat","enableResume","includeMembers","includeFeatures","organizationId","onlyExplicitMembership","_tag","waitFor","LiveEvent","LiveEventRestart","LiveEventReconnect","LiveEventMessage","LiveEventWelcome","LiveEventGoAway","SyncTag","console","Events","E","SanityReference","transformations","MediaLibraryVideoPlaybackTransformations","expiration","getPlaybackInfo","MediaLibraryAssetInstanceIdentifier","assetIdentifier","MediaLibraryPlaybackInfoOptions","VideoPlaybackInfo","thumbnail","ThumbnailTransformOptions","animated","AnimatedTransformOptions","storyboard","StoryboardTransformOptions","documentIds","results","MutationOperation","MutationSelection","MutationErrorItem","eventId","identity","mutations","previousRev","resultRev","result","SanityDocument","previous","effects","apply","revert","timestamp","transition","transactionTotalEvents","transactionCurrentEvent","MutationSelectionQueryParams","HttpRequestEvent","BasePatch","clone","ObservablePatch","commit","FirstDocumentMutationOptions","AllDocumentsMutationOptions","FirstDocumentIdMutationOptions","SingleMutationResult","AllDocumentIdsMutationOptions","MultipleMutationResult","ListOptions","SanityProject","OmittedProjectFields","getById","get","signal","AbortSignal","BaseActionOptions","SingleActionResult","release","publish","archive","unarchive","schedule","publishAt","unschedule","fetchDocuments","RawQueryResponse","assets","ObservableAssetsClient","datasets","ObservableDatasetsClient","live","LiveClient","mediaLibrary","video","ObservableMediaLibraryVideoClient","projects","ObservableProjectsClient","users","ObservableUsersClient","agent","action","ObservableAgentsActionClient","releases","ObservableReleasesClient","listen","_listen","InitializedClientConfig","newConfig","withConfig","Q","QueryWithoutParams","G","ClientReturn","QueryParams","FilteredResponseQueryOptions","UnfilteredResponseQueryOptions","UnfilteredResponseWithoutQuery","RawQuerylessQueryResponse","getDocument","getDocuments","ids","documentsExists","Set","createVersion","args","MultipleActionResult","discardVersion","replaceVersion","unpublishVersion","mutate","ObservableTransaction","transaction","Action","RawRequestOptions","getUrl","uri","canUseCdn","getDataUrl","BaseTransaction","TransactionFirstDocumentMutationOptions","TransactionAllDocumentsMutationOptions","TransactionFirstDocumentIdMutationOptions","TransactionAllDocumentIdsMutationOptions","ObservablePatchBuilder","patchOps","CurrentSanityUser","SanityUser","K","Patch","PatchDocumentSync","PatchDocumentAsync","PatchExistingDocumentRequest","PatchTargetDocumentRequest","PatchRequestBase","InsertPatch","ifRevisionID","PatchTarget","PatchOperation","AnyNonNullable","stage","percent","total","loaded","lengthComputable","PromptTextResponse","PromptJsonResponse","PromptRequestBase","ifDraftRevisionId","ifPublishedRevisionId","RequestInit","returnQuery","lastLiveEventId","cacheMode","ms","ContentSourceMap","syncTags","json","useGlobalApi","maxRedirects","CreateReleaseAction","EditReleaseAction","PublishReleaseAction","ArchiveReleaseAction","UnarchiveReleaseAction","ScheduleReleaseAction","UnscheduleReleaseAction","DeleteReleaseAction","ImportReleaseAction","_createdAt","_updatedAt","_rev","state","ReleaseState","finalDocumentStates","publishedAt","intendedPublishAt","releaseType","ReleaseType","cardinality","ReleaseCardinality","defaultRequester","size","assetId","mimeType","sha1hash","extension","uploadId","originalFilename","AssetsClient","DatasetsClient","MediaLibraryVideoClient","ProjectsClient","UsersClient","AgentActionsClient","ReleasesClient","observable","Transaction","dataRequest","endpoint","_originalId","hasAlpha","isOpaque","lqip","blurHash","thumbHash","dimensions","aspectRatio","palette","darkMuted","SanityImagePalette","darkVibrant","dominant","lightMuted","lightVibrant","muted","vibrant","image","exif","background","foreground","population","displayName","studioHost","isBlocked","isDisabled","isDisabledByUser","pendingInvites","maxRetentionDays","members","SanityProjectMember","cliInitializedAt","color","externalStudioHost","isRobot","isCurrentUser","_ref","familyName","givenName","middleName","updatedAt","studioUrl","StudioUrl","ResolveStudioUrl","filter","logger","Logger","omitCrossDatasetReferenceData","Extract","StillImageFormat","time","fit","FitMode","PatchBuilder","TransformDocumentSync","TransformDocumentAsync","TransformRequestBase","ImageDescriptionOperation","TransformTargetDocument","TransformTarget","TransformTargetInclude","TransformOperation","TranslateDocumentSync","TranslateDocumentAsync","TranslateRequestBase","fromLanguage","TranslateLanguage","toLanguage","styleGuide","styleGuideParams","protectedPhrases","languageFieldPath","TranslateTarget","TranslateTargetInclude","File","Blob","Buffer","NodeJS","ReadableStream","preserveFilename","filename","contentType","extract","AssetMetadataType","label","creditLine","CreateVersionAction","DiscardVersionAction","ReplaceVersionAction","UnpublishVersionAction","VideoPlaybackInfoItem","VideoRenditionInfo","VideoPlaybackInfoItemSigned","VideoRenditionInfoSigned","S","VideoSubtitleInfo","VideoSubtitleInfoSigned","stream","duration","renditions","subtitles","VideoPlaybackInfoItemPublic","VideoRenditionInfoPublic","resolution","expiresAt","VideoSubtitleInfoPublic","trackId","languageCode","closedCaptions","listenerName"],"sources":["../../../node_modules/.pnpm/rxjs@7.8.2/node_modules/rxjs/dist/types/internal/types.d.ts","../../../node_modules/.pnpm/@sanity+client@7.23.0/node_modules/@sanity/client/dist/index.d.ts","../src/schema.ts","../src/components/MarkdownInput.tsx","../src/plugin.tsx"],"x_google_ignoreList":[0,1],"mappings":";;;;;;AAE8C;;;QAKtCA,MAAAA;EAAAA,UACMC,iBAAAA;IAAAA,SACGC,UAAAA;EAAAA;AAAAA;;AAAU;;AC0Y3B;;;;;;;;aAAoB,GAAA;;kBA68IK,mBAAA,SAA4B,cAAc;EACjEkK,GAAAA;EACA1D,IAAAA;EACAggB,IAAAA;EACAC,OAAAA;EACAC,QAAAA;EACAC,QAAAA;EACAC,SAAAA;EACAC,QAAAA;EACAC,gBAAAA;AAAAA;;aA8xBkB,cAAA,WAAyB,MAAA,SAAe,GAAA,IAAO,MAAA,SAAe,GAAA,mBACpE,CAAA,GAAI,CAAA,CAAE,CAAA;EAElBtf,GAAAA;EACAqe,IAAAA;EACAtU,KAAAA;EACAoU,UAAAA;EACAC,UAAAA;;;;EAIA8B,WAAAA;AAAAA;;kBAWuB,wBAAA,SAAiC,mBAAA;EACxDhV,QAAAA;IACEnB,KAAAA;IACAoW,QAAAA;IACAC,QAAAA;IACAC,IAAAA;IACAC,QAAAA;IACAC,SAAAA;IACAC,UAAAA;MACEzW,KAAAA;MACA0W,WAAAA;MACArf,MAAAA;MACAD,KAAAA;IAAAA;IAEFuf,OAAAA;MACE3W,KAA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{ PatchEvent, definePlugin, defineType, set, unset, useClient } from "sanity";
2
+ import { c } from "react/compiler-runtime";
3
+ import { Box, Text } from "@sanity/ui";
4
+ import { Suspense, lazy, useEffect, useImperativeHandle, useRef, useState } from "react";
5
+ import { styled } from "styled-components";
6
+ import { jsx } from "react/jsx-runtime";
7
+ const SimpleMdeReact = lazy(() => import("react-simplemde-editor")), MarkdownInputStyles = styled(Box).withConfig({
8
+ displayName: "MarkdownInputStyles",
9
+ componentId: "sc-xfwgdd-0"
10
+ })`& .CodeMirror.CodeMirror{color:${({ theme }) => theme.sanity.color.card.enabled.fg};border-color:${({ theme }) => theme.sanity.color.card.enabled.border};background-color:inherit;}& .cm-s-easymde .CodeMirror-cursor{border-color:${({ theme }) => theme.sanity.color.card.enabled.fg};}& .editor-toolbar,.editor-preview-side{border-color:${({ theme }) => theme.sanity.color.card.enabled.border};}& .CodeMirror-focused .CodeMirror-selected.CodeMirror-selected.CodeMirror-selected{background-color:${({ theme }) => theme.sanity.color.selectable?.primary?.hovered?.bg};}& .CodeMirror-selected.CodeMirror-selected.CodeMirror-selected{background-color:${({ theme }) => theme.sanity.color.card.enabled.bg};}& .editor-toolbar > *{color:${({ theme }) => theme.sanity.color.card.enabled.fg};}& .editor-toolbar > .active,.editor-toolbar > button:hover,.editor-preview pre,.cm-s-easymde .cm-comment{background-color:${({ theme }) => theme.sanity.color.card.enabled.bg};}& .editor-preview{background-color:${({ theme }) => theme.sanity.color.card.enabled.bg};& h1,h2,h3,h4,h5,h6{font-size:revert;}& ul,li{list-style:revert;padding:revert;}& a{text-decoration:revert;}}`, defaultMdeTools = [
11
+ "heading",
12
+ "bold",
13
+ "italic",
14
+ "|",
15
+ "quote",
16
+ "unordered-list",
17
+ "ordered-list",
18
+ "|",
19
+ "link",
20
+ "image",
21
+ "code",
22
+ "|",
23
+ "preview",
24
+ "side-by-side"
25
+ ];
26
+ function MarkdownInput(props) {
27
+ let $ = c(29), { value: t0, onChange, elementProps: t1, reactMdeProps: t2, schemaType, focused } = props, value = t0 === void 0 ? "" : t0, { onBlur, onFocus, ref: elementRef } = t1, t3;
28
+ $[0] === t2 ? t3 = $[1] : (t3 = t2 === void 0 ? {} : t2, $[0] = t2, $[1] = t3);
29
+ let mdeCustomOptions, reactMdeProps;
30
+ $[2] === t3 ? (mdeCustomOptions = $[3], reactMdeProps = $[4]) : ({options: mdeCustomOptions, ...reactMdeProps} = t3, $[2] = t3, $[3] = mdeCustomOptions, $[4] = reactMdeProps);
31
+ let t4;
32
+ $[5] === Symbol.for("react.memo_cache_sentinel") ? (t4 = { apiVersion: "2022-01-01" }, $[5] = t4) : t4 = $[5];
33
+ let client = useClient(t4), t5;
34
+ $[6] === schemaType.options ? t5 = $[7] : (t5 = schemaType.options ?? {}, $[6] = schemaType.options, $[7] = t5);
35
+ let { imageUrl } = t5, [shouldAutoFocus, setShouldAutoFocus] = useState(!1), ref = useRef(null), t6;
36
+ $[8] === Symbol.for("react.memo_cache_sentinel") ? (t6 = () => ref.current, $[8] = t6) : t6 = $[8], useImperativeHandle(elementRef, t6);
37
+ let t7;
38
+ $[9] !== client || $[10] !== imageUrl ? (t7 = (file, onSuccess, onError) => {
39
+ client.assets.upload("image", file).then((doc) => onSuccess(imageUrl ? imageUrl(doc) : `${doc.url}?w=450`)).catch((e) => {
40
+ console.error(e), onError(e.message);
41
+ });
42
+ }, $[9] = client, $[10] = imageUrl, $[11] = t7) : t7 = $[11];
43
+ let imageUpload = t7, t8;
44
+ $[12] !== imageUpload || $[13] !== mdeCustomOptions || $[14] !== shouldAutoFocus ? (t8 = {
45
+ spellChecker: !1,
46
+ sideBySideFullscreen: !1,
47
+ uploadImage: !0,
48
+ imageUploadFunction: imageUpload,
49
+ toolbar: defaultMdeTools,
50
+ status: !1,
51
+ ...mdeCustomOptions,
52
+ autofocus: shouldAutoFocus
53
+ }, $[12] = imageUpload, $[13] = mdeCustomOptions, $[14] = shouldAutoFocus, $[15] = t8) : t8 = $[15];
54
+ let mdeOptions = t8, t10, t9;
55
+ $[16] !== focused || $[17] !== shouldAutoFocus ? (t9 = () => {
56
+ let node = ref.current;
57
+ if (node) {
58
+ if (focused && !shouldAutoFocus) {
59
+ let raf = requestAnimationFrame(() => setShouldAutoFocus(!node.contains(document.activeElement)));
60
+ return () => cancelAnimationFrame(raf);
61
+ }
62
+ if (!focused && shouldAutoFocus) {
63
+ let raf_0 = requestAnimationFrame(() => setShouldAutoFocus(node.contains(document.activeElement)));
64
+ return () => cancelAnimationFrame(raf_0);
65
+ }
66
+ }
67
+ }, t10 = [focused, shouldAutoFocus], $[16] = focused, $[17] = shouldAutoFocus, $[18] = t10, $[19] = t9) : (t10 = $[18], t9 = $[19]), useEffect(t9, t10);
68
+ let t11;
69
+ $[20] === onChange ? t11 = $[21] : (t11 = (newValue) => {
70
+ onChange(PatchEvent.from(newValue ? set(newValue) : unset()));
71
+ }, $[20] = onChange, $[21] = t11);
72
+ let handleChange = t11, t12;
73
+ return $[22] !== handleChange || $[23] !== mdeOptions || $[24] !== onBlur || $[25] !== onFocus || $[26] !== reactMdeProps || $[27] !== value ? (t12 = /* @__PURE__ */ jsx(MarkdownInputStyles, { children: /* @__PURE__ */ jsx(Suspense, {
74
+ fallback,
75
+ children: /* @__PURE__ */ jsx(SimpleMdeReact, {
76
+ ...reactMdeProps,
77
+ ref,
78
+ value,
79
+ onChange: handleChange,
80
+ onBlur,
81
+ onFocus,
82
+ options: mdeOptions,
83
+ spellCheck: !1
84
+ })
85
+ }) }), $[22] = handleChange, $[23] = mdeOptions, $[24] = onBlur, $[25] = onFocus, $[26] = reactMdeProps, $[27] = value, $[28] = t12) : t12 = $[28], t12;
86
+ }
87
+ const fallback = /* @__PURE__ */ jsx(Box, {
88
+ padding: 3,
89
+ children: /* @__PURE__ */ jsx(Text, { children: "Loading editor..." })
90
+ }), markdownSchemaType = defineType({
91
+ type: "string",
92
+ name: "markdown",
93
+ title: "Markdown",
94
+ components: { input: MarkdownInput }
95
+ }), markdownSchema = definePlugin((config) => ({
96
+ name: "markdown-editor",
97
+ schema: { types: [config && config.input ? {
98
+ ...markdownSchemaType,
99
+ components: { input: config.input }
100
+ } : markdownSchemaType] }
101
+ }));
102
+ export { defaultMdeTools as i, markdownSchemaType as n, MarkdownInput as r, markdownSchema as t };
103
+
104
+ //# sourceMappingURL=commonExports.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"commonExports.js","names":["Box","Text","Options","EasyMdeOptions","lazy","Suspense","useCallback","useEffect","useImperativeHandle","useMemo","useRef","useState","SimpleMDEReactProps","PatchEvent","set","StringInputProps","unset","useClient","styled","MarkdownOptions","SimpleMdeReact","MarkdownInputStyles","theme","sanity","color","card","enabled","fg","border","selectable","primary","hovered","bg","MarkdownInputProps","reactMdeProps","Omit","defaultMdeTools","MarkdownInput","props","$","_c","value","t0","onChange","elementProps","t1","t2","schemaType","focused","undefined","onBlur","onFocus","ref","elementRef","t3","mdeCustomOptions","options","t4","Symbol","for","apiVersion","client","t5","imageUrl","shouldAutoFocus","setShouldAutoFocus","t6","current","t7","file","onSuccess","onError","assets","upload","then","doc","url","catch","e","console","error","message","imageUpload","t8","spellChecker","sideBySideFullscreen","uploadImage","imageUploadFunction","toolbar","status","autofocus","mdeOptions","t10","t9","node","raf","requestAnimationFrame","contains","document","activeElement","cancelAnimationFrame","raf_0","t11","newValue","from","handleChange","t12","fallback","SanityImageAssetDocument","defineType","StringDefinition","MarkdownInput","markdownTypeName","MarkdownOptions","imageUrl","imageAsset","MarkdownDefinition","Omit","type","options","IntrinsicDefinitions","markdown","markdownSchemaType","name","title","components","input","definePlugin","Plugin","StringInputProps","markdownSchemaType","MarkdownConfig","input","props","React","ReactElement","markdownSchema","config","name","schema","types","components"],"sources":["../src/components/MarkdownInput.tsx","../src/schema.ts","../src/plugin.tsx"],"sourcesContent":["// TODO: when upgrading to @sanity/ui@4 start using the new tokens\n// oxlint-disable typescript/no-deprecated\n\nimport {Box, Text} from '@sanity/ui'\n// `import type` (not an inline type specifier) so the bundle keeps no side-effect\n// `import 'easymde'`, which would break SSR/Node (easymde touches `document` on load)\nimport type {Options as EasyMdeOptions} from 'easymde'\nimport {\n lazy,\n Suspense,\n useCallback,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from 'react'\n// dont import non-types here, it will break SSR on next\nimport type {SimpleMDEReactProps} from 'react-simplemde-editor'\nimport {PatchEvent, set, type StringInputProps, unset, useClient} from 'sanity'\nimport {styled} from 'styled-components'\n\nimport type {MarkdownOptions} from '../schema'\n\nconst SimpleMdeReact = lazy(() => import('react-simplemde-editor'))\n\nconst MarkdownInputStyles = styled(Box)`\n & .CodeMirror.CodeMirror {\n color: ${({theme}) => theme.sanity.color.card.enabled.fg};\n border-color: ${({theme}) => theme.sanity.color.card.enabled.border};\n background-color: inherit;\n }\n\n & .cm-s-easymde .CodeMirror-cursor {\n border-color: ${({theme}) => theme.sanity.color.card.enabled.fg};\n }\n\n & .editor-toolbar,\n .editor-preview-side {\n border-color: ${({theme}) => theme.sanity.color.card.enabled.border};\n }\n\n & .CodeMirror-focused .CodeMirror-selected.CodeMirror-selected.CodeMirror-selected {\n background-color: ${({theme}) => theme.sanity.color.selectable?.primary?.hovered?.bg};\n }\n\n & .CodeMirror-selected.CodeMirror-selected.CodeMirror-selected {\n background-color: ${({theme}) => theme.sanity.color.card.enabled.bg};\n }\n\n & .editor-toolbar > * {\n color: ${({theme}) => theme.sanity.color.card.enabled.fg};\n }\n\n & .editor-toolbar > .active,\n .editor-toolbar > button:hover,\n .editor-preview pre,\n .cm-s-easymde .cm-comment {\n background-color: ${({theme}) => theme.sanity.color.card.enabled.bg};\n }\n\n & .editor-preview {\n background-color: ${({theme}) => theme.sanity.color.card.enabled.bg};\n\n & h1,\n h2,\n h3,\n h4,\n h5,\n h6 {\n font-size: revert;\n }\n\n & ul,\n li {\n list-style: revert;\n padding: revert;\n }\n\n & a {\n text-decoration: revert;\n }\n }\n`\n\nexport interface MarkdownInputProps extends StringInputProps {\n /**\n * These are passed along directly to\n *\n * Note: MarkdownInput sets certain reactMdeProps.options by default.\n * These will be merged with any custom options.\n */\n reactMdeProps?: Omit<SimpleMDEReactProps, 'value' | 'onChange'>\n}\n\nexport const defaultMdeTools: EasyMdeOptions['toolbar'] = [\n 'heading',\n 'bold',\n 'italic',\n '|',\n 'quote',\n 'unordered-list',\n 'ordered-list',\n '|',\n 'link',\n 'image',\n 'code',\n '|',\n 'preview',\n 'side-by-side',\n]\n\nexport function MarkdownInput(props: MarkdownInputProps): React.JSX.Element {\n const {\n value = '',\n onChange,\n elementProps: {onBlur, onFocus, ref: elementRef},\n reactMdeProps: {options: mdeCustomOptions, ...reactMdeProps} = {},\n schemaType,\n focused,\n } = props\n const client = useClient({apiVersion: '2022-01-01'})\n // oxlint-disable-next-line no-unsafe-type-assertion\n const {imageUrl} = (schemaType.options as MarkdownOptions | undefined) ?? {}\n const [shouldAutoFocus, setShouldAutoFocus] = useState(false)\n const ref = useRef<HTMLDivElement>(null)\n\n // Forward ref to parent form state\n useImperativeHandle(elementRef, () => ref.current)\n\n const imageUpload = useCallback(\n (file: File, onSuccess: (url: string) => void, onError: (error: string) => void) => {\n client.assets\n .upload('image', file)\n .then((doc) => onSuccess(imageUrl ? imageUrl(doc) : `${doc.url}?w=450`))\n .catch((e) => {\n console.error(e)\n onError(e.message)\n })\n },\n [client, imageUrl],\n )\n\n const mdeOptions: EasyMdeOptions = useMemo(() => {\n return {\n spellChecker: false,\n sideBySideFullscreen: false,\n uploadImage: true,\n imageUploadFunction: imageUpload,\n toolbar: defaultMdeTools,\n status: false,\n ...mdeCustomOptions,\n autofocus: shouldAutoFocus,\n }\n }, [imageUpload, mdeCustomOptions, shouldAutoFocus])\n\n useEffect(() => {\n const node = ref.current\n if (!node) return undefined\n\n if (focused && !shouldAutoFocus) {\n // Do not set autofocus if the field already has focus\n const raf = requestAnimationFrame(() =>\n setShouldAutoFocus(!node.contains(document.activeElement)),\n )\n return () => cancelAnimationFrame(raf)\n }\n\n if (!focused && shouldAutoFocus) {\n // If `focused` is false, and the current active focus is no longer within the editor, reset autofocus state\n const raf = requestAnimationFrame(() =>\n setShouldAutoFocus(node.contains(document.activeElement)),\n )\n return () => cancelAnimationFrame(raf)\n }\n\n return undefined\n }, [focused, shouldAutoFocus])\n\n const handleChange = useCallback(\n (newValue: string) => {\n onChange(PatchEvent.from(newValue ? set(newValue) : unset()))\n },\n [onChange],\n )\n\n return (\n <MarkdownInputStyles>\n <Suspense fallback={fallback}>\n <SimpleMdeReact\n {...reactMdeProps}\n ref={ref}\n value={value}\n onChange={handleChange}\n onBlur={onBlur}\n onFocus={onFocus}\n options={mdeOptions}\n spellCheck={false}\n />\n </Suspense>\n </MarkdownInputStyles>\n )\n}\n\nconst fallback = (\n <Box padding={3}>\n <Text>Loading editor...</Text>\n </Box>\n)\n","import type {SanityImageAssetDocument} from '@sanity/client'\nimport {defineType, type StringDefinition} from 'sanity'\n\nimport {MarkdownInput} from './components/MarkdownInput'\n\nexport const markdownTypeName = 'markdown'\n\nexport interface MarkdownOptions {\n /**\n * Used to create image url for any uploaded image.\n * The function will be invoked whenever an image is pasted or dragged into the\n * markdown editor, after upload completes.\n *\n * The default implementation uses\n * ```js\n * imageAsset => `${imageAsset.url}?w=450`\n * ```\n * ## Example\n * ```js\n * {\n * imageUrl: imageAsset => `${imageAsset.url}?w=400&h=400`\n * }\n * ```\n * @param imageAsset\n */\n imageUrl?: (imageAsset: SanityImageAssetDocument) => string\n}\n\n/**\n * @public\n */\nexport interface MarkdownDefinition extends Omit<StringDefinition, 'type' | 'fields' | 'options'> {\n type: typeof markdownTypeName\n options?: MarkdownOptions\n}\n\ndeclare module 'sanity' {\n // makes type: 'markdown' narrow correctly when using defineType/defineField/defineArrayMember\n export interface IntrinsicDefinitions {\n markdown: MarkdownDefinition\n }\n}\n\nexport const markdownSchemaType = defineType({\n type: 'string',\n name: markdownTypeName,\n title: 'Markdown',\n components: {input: MarkdownInput},\n})\n","import {definePlugin, type Plugin, type StringInputProps} from 'sanity'\n\nimport {markdownSchemaType} from './schema'\n\nexport interface MarkdownConfig {\n /**\n * When provided, will replace the default input component.\n *\n * Use this to customize MarkdownInput by wrapping it in a custom component,\n * and provide any custom props for https://github.com/RIP21/react-simplemde-editor#react-simplemde-easymde-markdown-editor\n * via the `reactMdeProps` prop.\n *\n * ### Example\n *\n * ```tsx\n * // CustomMarkdownInput.tsx\n * import { MarkdownInput, MarkdownInputProps } from 'sanity-plugin-markdown'\n *\n * export function CustomMarkdownInput(props) {\n * const reactMdeProps: MarkdownInputProps['reactMdeProps'] =\n * useMemo(() => {\n * return {\n * options: {\n * toolbar: ['bold', 'italic'],\n * // more options available, see:\n * // https://github.com/Ionaru/easy-markdown-editor#options-list\n * },\n * // more props available, see:\n * // https://github.com/RIP21/react-simplemde-editor#react-simplemde-easymde-markdown-editor\n * }\n * }, [])\n *\n * return <MarkdownInput {...props} reactMdeProps={reactMdeProps} />\n * }\n *\n * // studio.config.ts\n * markdownSchema({input: CustomMarkdownInput})\n * ```\n */\n input?: (props: StringInputProps) => React.ReactElement\n}\n\nexport const markdownSchema: Plugin<MarkdownConfig | void> = definePlugin(\n (config: MarkdownConfig | void) => {\n return {\n name: 'markdown-editor',\n schema: {\n types: [\n config && config.input\n ? {...markdownSchemaType, components: {input: config.input}}\n : markdownSchemaType,\n ],\n },\n }\n },\n)\n"],"mappings":";;;;;;AAwBA,MAAMoB,iBAAiBhB,WAAW,OAAO,yBAAyB,GAE5DiB,sBAAsBH,OAAOlB,GAAG,CAAC,CAAA,WAAA;;;qCAEzB,EAACsB,YAAWA,MAAMC,OAAOC,MAAMC,KAAKC,QAAQC,GAAE,iBACvC,EAACL,YAAWA,MAAMC,OAAOC,MAAMC,KAAKC,QAAQE,OAAM,8EAKlD,EAACN,YAAWA,MAAMC,OAAOC,MAAMC,KAAKC,QAAQC,GAAE,yDAK9C,EAACL,YAAWA,MAAMC,OAAOC,MAAMC,KAAKC,QAAQE,OAAM,yGAI9C,EAACN,YAAWA,MAAMC,OAAOC,MAA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AK,EAAA,MAAAE,OAAAF,EAAA,MAAAmE,OAAAA,MAAAnE,EAAA,KAbtBmE;AAasB;AAI1B,MAAMC,WACJ,oBAAC,KAAD;CAAK,SAAS;WACZ,oBAAC,MAAD,EAAA,UAAM,oBAAuB,CAAA;AAC1B,CAAA,GCpKMe,qBAAqBb,WAAW;CAC3CS,MAAM;CACNK,MAAMX;CACNY,OAAO;CACPC,YAAY,EAACC,OAAOf,cAAa;AACnC,CAAC,GCNYyB,iBAAgDT,cAC1DU,YACQ;CACLC,MAAM;CACNC,QAAQ,EACNC,OAAO,CACLH,UAAUA,OAAOL,QACb;EAAC,GAAGF;EAAoBW,YAAY,EAACT,OAAOK,OAAOL,MAAK;CAAC,IACzDF,kBAAkB,EAE1B;AACF,EAEJ"}
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as defaultMdeTools, i as MarkdownInputProps, n as markdownSchema, o as MarkdownDefinition, r as MarkdownInput, s as markdownSchemaType, t as MarkdownConfig } from "./_chunks-dts/commonExports.js";
1
+ import { a as defaultMdeTools, i as MarkdownInputProps, n as markdownSchema, o as MarkdownDefinition, r as MarkdownInput, s as markdownSchemaType, t as MarkdownConfig } from "./commonExports.js";
2
2
  export { type MarkdownConfig, type MarkdownDefinition, MarkdownInput, type MarkdownInputProps, defaultMdeTools, markdownSchema, markdownSchemaType };
package/dist/index.js CHANGED
@@ -1,9 +1,3 @@
1
+ import { i as defaultMdeTools, n as markdownSchemaType, r as MarkdownInput, t as markdownSchema } from "./commonExports.js";
1
2
  import "easymde/dist/easymde.min.css";
2
- import { MarkdownInput, defaultMdeTools, markdownSchema, markdownSchemaType } from "./indexNext.js";
3
- export {
4
- MarkdownInput,
5
- defaultMdeTools,
6
- markdownSchema,
7
- markdownSchemaType
8
- };
9
- //# sourceMappingURL=index.js.map
3
+ export { MarkdownInput, defaultMdeTools, markdownSchema, markdownSchemaType };
@@ -1,2 +1,2 @@
1
- import { a as defaultMdeTools, i as MarkdownInputProps, n as markdownSchema, o as MarkdownDefinition, r as MarkdownInput, s as markdownSchemaType, t as MarkdownConfig } from "./_chunks-dts/commonExports.js";
1
+ import { a as defaultMdeTools, i as MarkdownInputProps, n as markdownSchema, o as MarkdownDefinition, r as MarkdownInput, s as markdownSchemaType, t as MarkdownConfig } from "./commonExports.js";
2
2
  export { type MarkdownConfig, type MarkdownDefinition, MarkdownInput, type MarkdownInputProps, defaultMdeTools, markdownSchema, markdownSchemaType };
package/dist/next.js ADDED
@@ -0,0 +1,2 @@
1
+ import { i as defaultMdeTools, n as markdownSchemaType, r as MarkdownInput, t as markdownSchema } from "./commonExports.js";
2
+ export { MarkdownInput, defaultMdeTools, markdownSchema, markdownSchemaType };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sanity-plugin-markdown",
3
- "version": "9.0.0",
3
+ "version": "9.0.2",
4
4
  "description": "Markdown fields in Sanity Studio. Supports Github flavored Markdown and image uploads.",
5
5
  "keywords": [
6
6
  "github flavored markdown",
@@ -27,26 +27,25 @@
27
27
  "types": "./dist/index.d.ts",
28
28
  "exports": {
29
29
  ".": "./dist/index.js",
30
- "./next": "./dist/indexNext.js",
30
+ "./next": "./dist/next.js",
31
31
  "./package.json": "./package.json"
32
32
  },
33
33
  "dependencies": {
34
- "@sanity/ui": "^3.2.0",
34
+ "@sanity/ui": "^3.3.0",
35
35
  "react-simplemde-editor": "^5.2.0"
36
36
  },
37
37
  "devDependencies": {
38
38
  "@sanity/client": "^7.23.0",
39
- "@sanity/pkg-utils": "^10.5.7",
39
+ "@sanity/tsconfig": "^2.2.0",
40
+ "@sanity/tsdown-config": "^0.11.0",
40
41
  "@types/node": "^24.13.2",
41
42
  "@types/react": "^19.2.17",
42
43
  "babel-plugin-react-compiler": "^1.0.0",
43
- "babel-plugin-styled-components": "^2.3.0",
44
- "easymde": "^2.20.0",
44
+ "easymde": "^2.21.0",
45
45
  "react": "^19.2.7",
46
- "sanity": "^6.1.0",
47
- "styled-components": "^6.4.2",
48
- "@repo/package.config": "0.0.0",
49
- "@repo/tsconfig": "0.0.0"
46
+ "sanity": "^6.3.0",
47
+ "styled-components": "^6.4.3",
48
+ "tsdown": "^0.22.3"
50
49
  },
51
50
  "peerDependencies": {
52
51
  "easymde": "^2.18",
@@ -57,7 +56,11 @@
57
56
  "engines": {
58
57
  "node": ">=20.19 <22 || >=22.12"
59
58
  },
59
+ "inlinedDependencies": {
60
+ "@sanity/client": "7.23.0",
61
+ "rxjs": "7.8.2"
62
+ },
60
63
  "scripts": {
61
- "build": "pkg build --strict --check --clean"
64
+ "build": "tsdown"
62
65
  }
63
66
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"commonExports.d.ts","names":["CreateAction","ReplaceDraftAction","EditAction","DeleteAction","DiscardAction","PublishAction","UnpublishAction","VersionAction","ReleaseAction","type","description","items","ActionErrorItem","error","value","index","async","TParamConfig","docIdRequired","ConstantAgentActionParam","FieldAgentActionParam","DocumentAgentActionParam","GroqAgentActionParam","Record","AgentActionParam","AgentActionPathSegment","_key","AgentActionSchema","localeSettings","locale","timeZone","temperature","schemaId","forcePublishedWrite","conditionalPaths","defaultReadOnly","defaultHidden","paths","path","AgentActionPath","readOnly","hidden","private","constructor","SanityClient","client","HttpRequest","httpRequest","generate","DocumentShape","Any","GenerateInstruction","request","Promise","_id","IdentifiedSanityDocumentStub","transform","TransformDocument","translate","TranslateDocument","prompt","PromptRequest","patch","PatchDocument","noWrite","maxPathDepth","exclude","types","AgentActionTypeConfig","include","BaseMutationOptions","returnFirst","returnDocuments","width","height","start","end","fps","format","AnimatedImageFormat","Exclude","message","statusCode","actionType","releaseId","upload","assetType","UploadBody","body","UploadClientConfig","options","SanityAssetDocument","SanityImageAssetDocument","key","name","title","url","providers","AuthProvider","RequestOptions","transactionId","skipCrossDatasetReferenceValidation","dryRun","visibility","autoGenerateArrayKeys","selection","PatchSelection","operations","PatchOperations","set","AttributeSet","attrs","setIfMissing","diffMatchPatch","unset","inc","dec","insert","at","selector","append","prepend","splice","deleteCount","ifRevisionId","rev","serialize","PatchMutationOperation","toJSON","reset","_assign","op","props","merge","_set","Mutation","trxId","create","R","SanityDocumentStub","doc","createIfNotExists","createOrReplace","delete","documentId","id","_add","mut","Error","data","projectId","dataset","useCdn","token","resource","ClientConfigResource","perspective","ClientPerspective","apiHost","apiVersion","proxy","requestTagPrefix","headers","ignoreBrowserTokenWarning","ignoreWarnings","RegExp","Array","withCredentials","allowReconfigure","timeout","maxRetries","retryDelay","attemptNumber","useProjectHostname","requester","Requester","resultSourceMap","fetch","cache","ResponseQueryOptions","next","stega","StegaConfig","lineage","_requestHandler","RequestHandler","response","ErrorProps","responseBody","traceId","details","res","HttpContext","context","DeprecatedPreviewDrafts","StackablePerspective","GroqString","Fallback","SanityQueries","EventName","EventSourceInstance","Observable","initEventSource","events","ServerSentEvent","mappings","ContentSourceMapMappings","documents","ContentSourceMapDocuments","ContentSourceMapPaths","ContentSourceMapDocumentBase","_projectId","_dataset","_type","ContentSourceMapDocument","ContentSourceMapRemoteDocument","document","ContentSourceMapValueMapping","ContentSourceMapMapping","ContentSourceMapDocumentValueSource","ContentSourceMapLiteralSource","ContentSourceMapUnknownSource","source","ContentSourceMapSource","addOriginUrl","URL","credentials","publishedId","attributes","ifExists","ClientConfig","config","metadata","Partial","ReleaseDocument","baseId","versionId","ifBaseRevisionId","email","profileImage","role","provider","aclMode","DatasetAclMode","embeddings","enabled","projection","datasetName","DatasetCreateOptions","DatasetResponse","edit","DatasetEditOptions","deleted","list","DatasetsResponse","getEmbeddingsSettings","EmbeddingsSettings","editEmbeddingsSettings","EmbeddingsSettingsBody","settings","createdAt","createdByUserId","addonFor","datasetProfile","features","tags","includeDrafts","purge","draftId","reason","ErrorOptions","DocIdParam","Omit","PartialExcept","status","Name","InstanceType","globalThis","EventSource","sourcePath","ContentSourceMapParsedPath","sourceDocument","ContentSourceMapDocuments_2","resultPath","filterDefault","FilterDefault","filterResponse","QueryParseError","tag","T","GenerateExistingDocumentRequest","GenerateTargetDocumentRequest","GenerateRequestBase","AgentActionAsync","targetDocument","GenerateSyncInstruction","GenerateAsyncInstruction","AgentActionRequestBase","instruction","instructionParams","AgentActionParams","target","GenerateTarget","AgentActionSync","AgentActionTarget","operation","GenerateOperation","GenerateTargetInclude","initialValues","GenerateTargetDocument","AgentActionTargetInclude","query","params","ClientPerspective_2","method","statusMessage","ReturnType","ResponseEvent","ProgressEvent_2","P","imageUrl","isDefaultApi","cdnUrl","InitializedStegaConfig","StegaConfigRequiredKeys","Required","Pick","before","after","replace","HttpError","ObservableSanityClient","this","ListenParams","MutationEvent","Opts","ListenOptions","ResumableListenOptions","ListenEventFromOptions","ReconnectEvent","WelcomeBackEvent","ResetEvent","WelcomeEvent","OpenEvent","ResumableListenEventNames","ListenEventName","MapListenEventNamesToListenEvents","ListenEvent","includeResult","includeMutations","includePreviousRevision","includeAllVersions","effectFormat","enableResume","includeMembers","includeFeatures","organizationId","onlyExplicitMembership","_tag","waitFor","LiveEvent","LiveEventRestart","LiveEventReconnect","LiveEventMessage","LiveEventWelcome","LiveEventGoAway","SyncTag","console","Events","E","SanityReference","transformations","MediaLibraryVideoPlaybackTransformations","expiration","getPlaybackInfo","MediaLibraryAssetInstanceIdentifier","assetIdentifier","MediaLibraryPlaybackInfoOptions","VideoPlaybackInfo","thumbnail","ThumbnailTransformOptions","animated","AnimatedTransformOptions","storyboard","StoryboardTransformOptions","documentIds","results","MutationOperation","MutationSelection","MutationErrorItem","eventId","identity","mutations","previousRev","resultRev","result","SanityDocument","previous","effects","apply","revert","timestamp","transition","transactionTotalEvents","transactionCurrentEvent","MutationSelectionQueryParams","HttpRequestEvent","BasePatch","clone","ObservablePatch","commit","FirstDocumentMutationOptions","AllDocumentsMutationOptions","FirstDocumentIdMutationOptions","SingleMutationResult","AllDocumentIdsMutationOptions","MultipleMutationResult","ListOptions","SanityProject","OmittedProjectFields","getById","get","signal","AbortSignal","BaseActionOptions","SingleActionResult","release","publish","archive","unarchive","schedule","publishAt","unschedule","fetchDocuments","RawQueryResponse","assets","ObservableAssetsClient","datasets","ObservableDatasetsClient","live","LiveClient","mediaLibrary","video","ObservableMediaLibraryVideoClient","projects","ObservableProjectsClient","users","ObservableUsersClient","agent","action","ObservableAgentsActionClient","releases","ObservableReleasesClient","listen","_listen","InitializedClientConfig","newConfig","withConfig","Q","QueryWithoutParams","G","ClientReturn","QueryParams","FilteredResponseQueryOptions","UnfilteredResponseQueryOptions","UnfilteredResponseWithoutQuery","RawQuerylessQueryResponse","getDocument","getDocuments","ids","documentsExists","Set","createVersion","args","MultipleActionResult","discardVersion","replaceVersion","unpublishVersion","mutate","ObservableTransaction","transaction","Action","RawRequestOptions","getUrl","uri","canUseCdn","getDataUrl","BaseTransaction","TransactionFirstDocumentMutationOptions","TransactionAllDocumentsMutationOptions","TransactionFirstDocumentIdMutationOptions","TransactionAllDocumentIdsMutationOptions","ObservablePatchBuilder","patchOps","CurrentSanityUser","SanityUser","K","Patch","PatchDocumentSync","PatchDocumentAsync","PatchExistingDocumentRequest","PatchTargetDocumentRequest","PatchRequestBase","InsertPatch","ifRevisionID","PatchTarget","PatchOperation","AnyNonNullable","stage","percent","total","loaded","lengthComputable","PromptTextResponse","PromptJsonResponse","PromptRequestBase","ifDraftRevisionId","ifPublishedRevisionId","RequestInit","returnQuery","lastLiveEventId","cacheMode","ms","ContentSourceMap","syncTags","json","useGlobalApi","maxRedirects","CreateReleaseAction","EditReleaseAction","PublishReleaseAction","ArchiveReleaseAction","UnarchiveReleaseAction","ScheduleReleaseAction","UnscheduleReleaseAction","DeleteReleaseAction","ImportReleaseAction","_createdAt","_updatedAt","_rev","state","ReleaseState","finalDocumentStates","publishedAt","intendedPublishAt","releaseType","ReleaseType","cardinality","ReleaseCardinality","defaultRequester","size","assetId","mimeType","sha1hash","extension","uploadId","originalFilename","AssetsClient","DatasetsClient","MediaLibraryVideoClient","ProjectsClient","UsersClient","AgentActionsClient","ReleasesClient","observable","Transaction","dataRequest","endpoint","_originalId","hasAlpha","isOpaque","lqip","blurHash","thumbHash","dimensions","aspectRatio","palette","darkMuted","SanityImagePalette","darkVibrant","dominant","lightMuted","lightVibrant","muted","vibrant","image","exif","background","foreground","population","displayName","studioHost","isBlocked","isDisabled","isDisabledByUser","pendingInvites","maxRetentionDays","members","SanityProjectMember","cliInitializedAt","color","externalStudioHost","isRobot","isCurrentUser","_ref","familyName","givenName","middleName","updatedAt","studioUrl","StudioUrl","ResolveStudioUrl","filter","logger","Logger","omitCrossDatasetReferenceData","Extract","StillImageFormat","time","fit","FitMode","PatchBuilder","TransformDocumentSync","TransformDocumentAsync","TransformRequestBase","ImageDescriptionOperation","TransformTargetDocument","TransformTarget","TransformTargetInclude","TransformOperation","TranslateDocumentSync","TranslateDocumentAsync","TranslateRequestBase","fromLanguage","TranslateLanguage","toLanguage","styleGuide","styleGuideParams","protectedPhrases","languageFieldPath","TranslateTarget","TranslateTargetInclude","File","Blob","Buffer","NodeJS","ReadableStream","preserveFilename","filename","contentType","extract","AssetMetadataType","label","creditLine","CreateVersionAction","DiscardVersionAction","ReplaceVersionAction","UnpublishVersionAction","VideoPlaybackInfoItem","VideoRenditionInfo","VideoPlaybackInfoItemSigned","VideoRenditionInfoSigned","S","VideoSubtitleInfo","VideoSubtitleInfoSigned","stream","duration","renditions","subtitles","VideoPlaybackInfoItemPublic","VideoRenditionInfoPublic","resolution","expiresAt","VideoSubtitleInfoPublic","trackId","languageCode","closedCaptions","listenerName"],"sources":["../../../../node_modules/.pnpm/@sanity+client@7.23.0/node_modules/@sanity/client/dist/index.d.ts","../../src/schema.ts","../../src/components/MarkdownInput.tsx","../../src/plugin.tsx"],"x_google_ignoreList":[0],"mappings":";;;;;;;aAmZoB,GAAA;;kBA68IK,mBAAA,SAA4B,cAAc;EACjEgG,GAAAA;EACA1D,IAAAA;EACAggB,IAAAA;EACAC,OAAAA;EACAC,QAAAA;EACAC,QAAAA;EACAC,SAAAA;EACAC,QAAAA;EACAC,gBAAAA;AAAAA;;aA8xBkB,cAAA,W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FgUxB;;;;AAAG;AA68IvB;EEtwJE,aAAA,GAAgB,IAAA,CAAK,mBAAA;AAAA;AAAA,cAGV,eAAA,EAAiB,OAAc;AAAA,iBAiB5B,aAAA,CAAc,KAAA,EAAO,kBAAA,GAAqB,KAAA,CAAM,GAAA,CAAI,OAAO;AAAA,UC1G1D,cAAA;;;AH+YjB;;;;AAAuB;AA68IvB;;;;;;;;;;;;;;;AASkB;AA8xBlB;;;;;;;;;;;EGhmLE,KAAA,IAAS,KAAA,EAAO,gBAAA,KAAqB,KAAA,CAAM,YAAY;AAAA;AAAA,cAG5C,cAAA,EAAgB,MAAM,CAAC,cAAA"}
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;"}
package/dist/indexNext.js DELETED
@@ -1,126 +0,0 @@
1
- import { useClient, PatchEvent, set, unset, defineType, definePlugin } from "sanity";
2
- import { jsx } from "react/jsx-runtime";
3
- import { c } from "react/compiler-runtime";
4
- import { Box, Text } from "@sanity/ui";
5
- import { lazy, useState, useRef, useImperativeHandle, useEffect, Suspense } from "react";
6
- import { styled } from "styled-components";
7
- const SimpleMdeReact = lazy(() => import("react-simplemde-editor")), MarkdownInputStyles = styled(Box).withConfig({
8
- displayName: "MarkdownInputStyles",
9
- componentId: "sc-syau23-0"
10
- })`& .CodeMirror.CodeMirror{color:${({
11
- theme
12
- }) => theme.sanity.color.card.enabled.fg};border-color:${({
13
- theme
14
- }) => theme.sanity.color.card.enabled.border};background-color:inherit;}& .cm-s-easymde .CodeMirror-cursor{border-color:${({
15
- theme
16
- }) => theme.sanity.color.card.enabled.fg};}& .editor-toolbar,.editor-preview-side{border-color:${({
17
- theme
18
- }) => theme.sanity.color.card.enabled.border};}& .CodeMirror-focused .CodeMirror-selected.CodeMirror-selected.CodeMirror-selected{background-color:${({
19
- theme
20
- }) => theme.sanity.color.selectable?.primary?.hovered?.bg};}& .CodeMirror-selected.CodeMirror-selected.CodeMirror-selected{background-color:${({
21
- theme
22
- }) => theme.sanity.color.card.enabled.bg};}& .editor-toolbar > *{color:${({
23
- theme
24
- }) => theme.sanity.color.card.enabled.fg};}& .editor-toolbar > .active,.editor-toolbar > button:hover,.editor-preview pre,.cm-s-easymde .cm-comment{background-color:${({
25
- theme
26
- }) => theme.sanity.color.card.enabled.bg};}& .editor-preview{background-color:${({
27
- theme
28
- }) => theme.sanity.color.card.enabled.bg};& h1,h2,h3,h4,h5,h6{font-size:revert;}& ul,li{list-style:revert;padding:revert;}& a{text-decoration:revert;}}`, defaultMdeTools = ["heading", "bold", "italic", "|", "quote", "unordered-list", "ordered-list", "|", "link", "image", "code", "|", "preview", "side-by-side"];
29
- function MarkdownInput(props) {
30
- const $ = c(29), {
31
- value: t0,
32
- onChange,
33
- elementProps: t1,
34
- reactMdeProps: t2,
35
- schemaType,
36
- focused
37
- } = props, value = t0 === void 0 ? "" : t0, {
38
- onBlur,
39
- onFocus,
40
- ref: elementRef
41
- } = t1;
42
- let t3;
43
- $[0] !== t2 ? (t3 = t2 === void 0 ? {} : t2, $[0] = t2, $[1] = t3) : t3 = $[1];
44
- let mdeCustomOptions, reactMdeProps;
45
- $[2] !== t3 ? ({
46
- options: mdeCustomOptions,
47
- ...reactMdeProps
48
- } = t3, $[2] = t3, $[3] = mdeCustomOptions, $[4] = reactMdeProps) : (mdeCustomOptions = $[3], reactMdeProps = $[4]);
49
- let t4;
50
- $[5] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t4 = {
51
- apiVersion: "2022-01-01"
52
- }, $[5] = t4) : t4 = $[5];
53
- const client = useClient(t4);
54
- let t5;
55
- $[6] !== schemaType.options ? (t5 = schemaType.options ?? {}, $[6] = schemaType.options, $[7] = t5) : t5 = $[7];
56
- const {
57
- imageUrl
58
- } = t5, [shouldAutoFocus, setShouldAutoFocus] = useState(!1), ref = useRef(null);
59
- let t6;
60
- $[8] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t6 = () => ref.current, $[8] = t6) : t6 = $[8], useImperativeHandle(elementRef, t6);
61
- let t7;
62
- $[9] !== client || $[10] !== imageUrl ? (t7 = (file, onSuccess, onError) => {
63
- client.assets.upload("image", file).then((doc) => onSuccess(imageUrl ? imageUrl(doc) : `${doc.url}?w=450`)).catch((e) => {
64
- console.error(e), onError(e.message);
65
- });
66
- }, $[9] = client, $[10] = imageUrl, $[11] = t7) : t7 = $[11];
67
- const imageUpload = t7;
68
- let t8;
69
- $[12] !== imageUpload || $[13] !== mdeCustomOptions || $[14] !== shouldAutoFocus ? (t8 = {
70
- spellChecker: !1,
71
- sideBySideFullscreen: !1,
72
- uploadImage: !0,
73
- imageUploadFunction: imageUpload,
74
- toolbar: defaultMdeTools,
75
- status: !1,
76
- ...mdeCustomOptions,
77
- autofocus: shouldAutoFocus
78
- }, $[12] = imageUpload, $[13] = mdeCustomOptions, $[14] = shouldAutoFocus, $[15] = t8) : t8 = $[15];
79
- const mdeOptions = t8;
80
- let t10, t9;
81
- $[16] !== focused || $[17] !== shouldAutoFocus ? (t9 = () => {
82
- const node = ref.current;
83
- if (node) {
84
- if (focused && !shouldAutoFocus) {
85
- const raf = requestAnimationFrame(() => setShouldAutoFocus(!node.contains(document.activeElement)));
86
- return () => cancelAnimationFrame(raf);
87
- }
88
- if (!focused && shouldAutoFocus) {
89
- const raf_0 = requestAnimationFrame(() => setShouldAutoFocus(node.contains(document.activeElement)));
90
- return () => cancelAnimationFrame(raf_0);
91
- }
92
- }
93
- }, t10 = [focused, shouldAutoFocus], $[16] = focused, $[17] = shouldAutoFocus, $[18] = t10, $[19] = t9) : (t10 = $[18], t9 = $[19]), useEffect(t9, t10);
94
- let t11;
95
- $[20] !== onChange ? (t11 = (newValue) => {
96
- onChange(PatchEvent.from(newValue ? set(newValue) : unset()));
97
- }, $[20] = onChange, $[21] = t11) : t11 = $[21];
98
- const handleChange = t11;
99
- let t12;
100
- return $[22] !== handleChange || $[23] !== mdeOptions || $[24] !== onBlur || $[25] !== onFocus || $[26] !== reactMdeProps || $[27] !== value ? (t12 = /* @__PURE__ */ jsx(MarkdownInputStyles, { children: /* @__PURE__ */ jsx(Suspense, { fallback, children: /* @__PURE__ */ jsx(SimpleMdeReact, { ...reactMdeProps, ref, value, onChange: handleChange, onBlur, onFocus, options: mdeOptions, spellCheck: !1 }) }) }), $[22] = handleChange, $[23] = mdeOptions, $[24] = onBlur, $[25] = onFocus, $[26] = reactMdeProps, $[27] = value, $[28] = t12) : t12 = $[28], t12;
101
- }
102
- const fallback = /* @__PURE__ */ jsx(Box, { padding: 3, children: /* @__PURE__ */ jsx(Text, { children: "Loading editor..." }) }), markdownTypeName = "markdown", markdownSchemaType = defineType({
103
- type: "string",
104
- name: markdownTypeName,
105
- title: "Markdown",
106
- components: {
107
- input: MarkdownInput
108
- }
109
- }), markdownSchema = definePlugin((config) => ({
110
- name: "markdown-editor",
111
- schema: {
112
- types: [config && config.input ? {
113
- ...markdownSchemaType,
114
- components: {
115
- input: config.input
116
- }
117
- } : markdownSchemaType]
118
- }
119
- }));
120
- export {
121
- MarkdownInput,
122
- defaultMdeTools,
123
- markdownSchema,
124
- markdownSchemaType
125
- };
126
- //# sourceMappingURL=indexNext.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"indexNext.js","sources":["../src/components/MarkdownInput.tsx","../src/schema.ts","../src/plugin.tsx"],"sourcesContent":["// TODO: when upgrading to @sanity/ui@4 start using the new tokens\n// oxlint-disable typescript/no-deprecated\n\nimport {Box, Text} from '@sanity/ui'\nimport {type Options as EasyMdeOptions} from 'easymde'\nimport {\n lazy,\n Suspense,\n useCallback,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from 'react'\n// dont import non-types here, it will break SSR on next\nimport type {SimpleMDEReactProps} from 'react-simplemde-editor'\nimport {PatchEvent, set, type StringInputProps, unset, useClient} from 'sanity'\nimport {styled} from 'styled-components'\n\nimport type {MarkdownOptions} from '../schema'\n\nconst SimpleMdeReact = lazy(() => import('react-simplemde-editor'))\n\nconst MarkdownInputStyles = styled(Box)`\n & .CodeMirror.CodeMirror {\n color: ${({theme}) => theme.sanity.color.card.enabled.fg};\n border-color: ${({theme}) => theme.sanity.color.card.enabled.border};\n background-color: inherit;\n }\n\n & .cm-s-easymde .CodeMirror-cursor {\n border-color: ${({theme}) => theme.sanity.color.card.enabled.fg};\n }\n\n & .editor-toolbar,\n .editor-preview-side {\n border-color: ${({theme}) => theme.sanity.color.card.enabled.border};\n }\n\n & .CodeMirror-focused .CodeMirror-selected.CodeMirror-selected.CodeMirror-selected {\n background-color: ${({theme}) => theme.sanity.color.selectable?.primary?.hovered?.bg};\n }\n\n & .CodeMirror-selected.CodeMirror-selected.CodeMirror-selected {\n background-color: ${({theme}) => theme.sanity.color.card.enabled.bg};\n }\n\n & .editor-toolbar > * {\n color: ${({theme}) => theme.sanity.color.card.enabled.fg};\n }\n\n & .editor-toolbar > .active,\n .editor-toolbar > button:hover,\n .editor-preview pre,\n .cm-s-easymde .cm-comment {\n background-color: ${({theme}) => theme.sanity.color.card.enabled.bg};\n }\n\n & .editor-preview {\n background-color: ${({theme}) => theme.sanity.color.card.enabled.bg};\n\n & h1,\n h2,\n h3,\n h4,\n h5,\n h6 {\n font-size: revert;\n }\n\n & ul,\n li {\n list-style: revert;\n padding: revert;\n }\n\n & a {\n text-decoration: revert;\n }\n }\n`\n\nexport interface MarkdownInputProps extends StringInputProps {\n /**\n * These are passed along directly to\n *\n * Note: MarkdownInput sets certain reactMdeProps.options by default.\n * These will be merged with any custom options.\n */\n reactMdeProps?: Omit<SimpleMDEReactProps, 'value' | 'onChange'>\n}\n\nexport const defaultMdeTools: EasyMdeOptions['toolbar'] = [\n 'heading',\n 'bold',\n 'italic',\n '|',\n 'quote',\n 'unordered-list',\n 'ordered-list',\n '|',\n 'link',\n 'image',\n 'code',\n '|',\n 'preview',\n 'side-by-side',\n]\n\nexport function MarkdownInput(props: MarkdownInputProps): React.JSX.Element {\n const {\n value = '',\n onChange,\n elementProps: {onBlur, onFocus, ref: elementRef},\n reactMdeProps: {options: mdeCustomOptions, ...reactMdeProps} = {},\n schemaType,\n focused,\n } = props\n const client = useClient({apiVersion: '2022-01-01'})\n // oxlint-disable-next-line no-unsafe-type-assertion\n const {imageUrl} = (schemaType.options as MarkdownOptions | undefined) ?? {}\n const [shouldAutoFocus, setShouldAutoFocus] = useState(false)\n const ref = useRef<HTMLDivElement>(null)\n\n // Forward ref to parent form state\n useImperativeHandle(elementRef, () => ref.current)\n\n const imageUpload = useCallback(\n (file: File, onSuccess: (url: string) => void, onError: (error: string) => void) => {\n client.assets\n .upload('image', file)\n .then((doc) => onSuccess(imageUrl ? imageUrl(doc) : `${doc.url}?w=450`))\n .catch((e) => {\n console.error(e)\n onError(e.message)\n })\n },\n [client, imageUrl],\n )\n\n const mdeOptions: EasyMdeOptions = useMemo(() => {\n return {\n spellChecker: false,\n sideBySideFullscreen: false,\n uploadImage: true,\n imageUploadFunction: imageUpload,\n toolbar: defaultMdeTools,\n status: false,\n ...mdeCustomOptions,\n autofocus: shouldAutoFocus,\n }\n }, [imageUpload, mdeCustomOptions, shouldAutoFocus])\n\n useEffect(() => {\n const node = ref.current\n if (!node) return undefined\n\n if (focused && !shouldAutoFocus) {\n // Do not set autofocus if the field already has focus\n const raf = requestAnimationFrame(() =>\n setShouldAutoFocus(!node.contains(document.activeElement)),\n )\n return () => cancelAnimationFrame(raf)\n }\n\n if (!focused && shouldAutoFocus) {\n // If `focused` is false, and the current active focus is no longer within the editor, reset autofocus state\n const raf = requestAnimationFrame(() =>\n setShouldAutoFocus(node.contains(document.activeElement)),\n )\n return () => cancelAnimationFrame(raf)\n }\n\n return undefined\n }, [focused, shouldAutoFocus])\n\n const handleChange = useCallback(\n (newValue: string) => {\n onChange(PatchEvent.from(newValue ? set(newValue) : unset()))\n },\n [onChange],\n )\n\n return (\n <MarkdownInputStyles>\n <Suspense fallback={fallback}>\n <SimpleMdeReact\n {...reactMdeProps}\n ref={ref}\n value={value}\n onChange={handleChange}\n onBlur={onBlur}\n onFocus={onFocus}\n options={mdeOptions}\n spellCheck={false}\n />\n </Suspense>\n </MarkdownInputStyles>\n )\n}\n\nconst fallback = (\n <Box padding={3}>\n <Text>Loading editor...</Text>\n </Box>\n)\n","import type {SanityImageAssetDocument} from '@sanity/client'\nimport {defineType, type StringDefinition} from 'sanity'\n\nimport {MarkdownInput} from './components/MarkdownInput'\n\nexport const markdownTypeName = 'markdown'\n\nexport interface MarkdownOptions {\n /**\n * Used to create image url for any uploaded image.\n * The function will be invoked whenever an image is pasted or dragged into the\n * markdown editor, after upload completes.\n *\n * The default implementation uses\n * ```js\n * imageAsset => `${imageAsset.url}?w=450`\n * ```\n * ## Example\n * ```js\n * {\n * imageUrl: imageAsset => `${imageAsset.url}?w=400&h=400`\n * }\n * ```\n * @param imageAsset\n */\n imageUrl?: (imageAsset: SanityImageAssetDocument) => string\n}\n\n/**\n * @public\n */\nexport interface MarkdownDefinition extends Omit<StringDefinition, 'type' | 'fields' | 'options'> {\n type: typeof markdownTypeName\n options?: MarkdownOptions\n}\n\ndeclare module 'sanity' {\n // makes type: 'markdown' narrow correctly when using defineType/defineField/defineArrayMember\n export interface IntrinsicDefinitions {\n markdown: MarkdownDefinition\n }\n}\n\nexport const markdownSchemaType = defineType({\n type: 'string',\n name: markdownTypeName,\n title: 'Markdown',\n components: {input: MarkdownInput},\n})\n","import {definePlugin, type Plugin, type StringInputProps} from 'sanity'\n\nimport {markdownSchemaType} from './schema'\n\nexport interface MarkdownConfig {\n /**\n * When provided, will replace the default input component.\n *\n * Use this to customize MarkdownInput by wrapping it in a custom component,\n * and provide any custom props for https://github.com/RIP21/react-simplemde-editor#react-simplemde-easymde-markdown-editor\n * via the `reactMdeProps` prop.\n *\n * ### Example\n *\n * ```tsx\n * // CustomMarkdownInput.tsx\n * import { MarkdownInput, MarkdownInputProps } from 'sanity-plugin-markdown'\n *\n * export function CustomMarkdownInput(props) {\n * const reactMdeProps: MarkdownInputProps['reactMdeProps'] =\n * useMemo(() => {\n * return {\n * options: {\n * toolbar: ['bold', 'italic'],\n * // more options available, see:\n * // https://github.com/Ionaru/easy-markdown-editor#options-list\n * },\n * // more props available, see:\n * // https://github.com/RIP21/react-simplemde-editor#react-simplemde-easymde-markdown-editor\n * }\n * }, [])\n *\n * return <MarkdownInput {...props} reactMdeProps={reactMdeProps} />\n * }\n *\n * // studio.config.ts\n * markdownSchema({input: CustomMarkdownInput})\n * ```\n */\n input?: (props: StringInputProps) => React.ReactElement\n}\n\nexport const markdownSchema: Plugin<MarkdownConfig | void> = definePlugin(\n (config: MarkdownConfig | void) => {\n return {\n name: 'markdown-editor',\n schema: {\n types: [\n config && config.input\n ? {...markdownSchemaType, components: {input: config.input}}\n : markdownSchemaType,\n ],\n },\n }\n },\n)\n"],"names":["SimpleMdeReact","lazy","MarkdownInputStyles","styled","Box","withConfig","displayName","componentId","theme","sanity","color","card","enabled","fg","border","selectable","primary","hovered","bg","defaultMdeTools","MarkdownInput","props","$","_c","value","t0","onChange","elementProps","t1","reactMdeProps","t2","schemaType","focused","undefined","onBlur","onFocus","ref","elementRef","t3","mdeCustomOptions","options","t4","for","apiVersion","client","useClient","t5","imageUrl","shouldAutoFocus","setShouldAutoFocus","useState","useRef","t6","Symbol","current","useImperativeHandle","t7","file","onSuccess","onError","assets","upload","then","doc","url","catch","e","console","error","message","imageUpload","t8","spellChecker","sideBySideFullscreen","uploadImage","imageUploadFunction","toolbar","status","autofocus","mdeOptions","t10","t9","node","raf","requestAnimationFrame","contains","document","activeElement","cancelAnimationFrame","raf_0","useEffect","t11","newValue","PatchEvent","from","set","unset","handleChange","t12","fallback","markdownTypeName","markdownSchemaType","defineType","type","name","title","components","input","markdownSchema","definePlugin","config","schema","types"],"mappings":";;;;;;AAsBA,MAAMA,iBAAiBC,KAAK,MAAM,OAAO,wBAAwB,CAAC,GAE5DC,sBAAsBC,OAAOC,GAAG,EAACC,WAAA;AAAA,EAAAC,aAAA;AAAA,EAAAC,aAAA;AAAA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